diff --git a/docs/PR10-REBASE-OVERLAP.md b/docs/PR10-REBASE-OVERLAP.md new file mode 100644 index 0000000000..f8ad88c282 --- /dev/null +++ b/docs/PR10-REBASE-OVERLAP.md @@ -0,0 +1,46 @@ +# PR #10 rebase overlap (planned stack) + +PR #10 (`satscrip/v0.8.5-candidate`) is intended as **layer 3** atop: + +1. `satscrip/v0.8.5-supplycommit-base` (stock v0.8.5) +2. `satscrip/supplycommit-anchor-fix` — `genesis_points.anchor_tx_id` / transfer-proof anchor retarget +3. `satscrip/supplycommit-burn-provenance` — upstream #2331 burn provenance + +**Do not rebase #10 onto that stack yet.** This file lists touch points to reconcile during a later rebase. + +## `genesis_points` / `AnchorGenesisPoint` / `upsertAssetGen` + +| Area | #10 involvement | +|------|-----------------| +| `tapdb/universe.go` | `upsertAssetGen`, `AnchorGenesisPoint` on universe leaf insert (existing v0.8.5 path; unchanged by custom-anchor mint) | +| `tapdb/asset_minting.go` | `AnchorGenesisPoint` when committing mint batches to DB | +| Custom-anchor mint | Uses same `CommitMintingBatch` / genesis outpoint persistence as stock mint; anchor **output index** stored via `FundedMintAnchorPsbt.AssetAnchorOutIdx` and caretaker `anchorOutputIndex` | + +**Conflict risk with anchor-fix branch:** any change to when/how `anchor_tx_id` is written on transfer must stay consistent with custom-anchor genesis outpoint selection (non-zero `asset_anchor_output_index`). + +## Mint pre-commitment outputs + +| Area | #10 involvement | +|------|-----------------| +| `tapgarden/planter.go` | `PreCommitOutputIndex`, `sealBatchPreCommit`, `fetchPreCommitGroupKey`, `PreCommitTxOut` in custom `customGenesisPsbt` | +| `tapgarden/custom_anchor.go` | Validates pre-commit output index vs delegation key for supply-commitment batches | +| `rpcserver` / `mintrpc` | `FundBatchRequest.pre_commit_output_index` | + +**Overlap:** supply-commit stack may alter pre-commit / genesis anchoring semantics; rebase must re-run `custom_anchor_test.go` supply pre-commit cases and supply itests. + +## Supply-commit FSM (`universe/supplycommit`) + +| Area | #10 involvement | +|------|-----------------| +| `conf_finalize.go` | Burial-gated finalize (shared with recovery); not full `tapreorg` | +| `broadcast_recovery.go` | Scan + buried-only recovery | +| `transitions.go` | `RegisterConf` uses `commitBurialDepth`; `ConfEvent` → `transitionForBuriedConf` | +| `manager.go` | `CommitFinalizeState` resume via `FinalizeEvent`; broadcast resume comment | +| `itest/supply_commit_test.go` | `MineSupplyCommitBurial`, idle interval vs burial depth | +| `itest/assertions.go` | `UpdateAndMineSupplyCommit` + burial helper | + +**Overlap:** anchor-fix and burn-provenance branches may change commitment creation, proof binding, or FSM inputs; burial/recovery paths must be merged with any upstream `tapreorg` work on the stack. + +## Migrations + +Fork migrations **000073** / **000074** (custom anchor PSBT) **collide in number** with upstream `main` if ever upstreamed — noted in PR #10 body. diff --git a/docs/release-notes/release-notes-0.9.0.md b/docs/release-notes/release-notes-0.9.0.md new file mode 100644 index 0000000000..1b553c5191 --- /dev/null +++ b/docs/release-notes/release-notes-0.9.0.md @@ -0,0 +1,8 @@ +# Release Notes + +## RPC Updates + +- `PublishAndLogTransfer` and related publish paths document that + `request_id` deduplication is **process-local and in-flight only**: + it is released when the publish attempt finishes and is not retained + across daemon restarts. diff --git a/go.mod b/go.mod index 2aa9558120..ea3b4734f0 100644 --- a/go.mod +++ b/go.mod @@ -227,3 +227,6 @@ replace github.com/golang-migrate/migrate/v4 => github.com/lightninglabs/migrate replace github.com/prometheus/common => github.com/prometheus/common v0.26.0 replace github.com/lightningnetwork/lnd/tor => github.com/lightningnetwork/lnd/tor v1.1.6 + +// Local taprpc carries idempotency RPCs until tagged. +replace github.com/lightninglabs/taproot-assets/taprpc => ./taprpc diff --git a/itest/assertions.go b/itest/assertions.go index 958db138d8..ff0b0885ff 100644 --- a/itest/assertions.go +++ b/itest/assertions.go @@ -2838,9 +2838,20 @@ func UpdateAndMineSupplyCommit(t *testing.T, ctx context.Context, minedBlocks := MineBlocks(t, miner, 1, expectedTxsInBlock) require.Len(t, minedBlocks, 1) + MineSupplyCommitBurial(t, miner) + return minedBlocks } +// MineSupplyCommitBurial mines the empty blocks required after a supply +// commitment transaction is included so tapd can finalize at burial depth. +func MineSupplyCommitBurial(t *testing.T, miner *miner.HarnessMiner) { + const supplyCommitBurialDepth = 6 + if supplyCommitBurialDepth > 1 { + MineBlocks(t, miner, supplyCommitBurialDepth-1, 0) + } +} + // WaitForSupplyCommit waits for a supply commitment to be available and returns // it when the specified condition is met. func WaitForSupplyCommit(t *testing.T, ctx context.Context, diff --git a/itest/commit_virtual_psbts_no_change_test.go b/itest/commit_virtual_psbts_no_change_test.go new file mode 100644 index 0000000000..b0a64a691e --- /dev/null +++ b/itest/commit_virtual_psbts_no_change_test.go @@ -0,0 +1,192 @@ +//go:build itest + +package itest + +import ( + "bytes" + "context" + "fmt" + "testing" + + "github.com/btcsuite/btcd/btcutil/psbt" + "github.com/lightninglabs/taproot-assets/address" + "github.com/lightninglabs/taproot-assets/asset" + "github.com/lightninglabs/taproot-assets/fn" + "github.com/lightninglabs/taproot-assets/tappsbt" + wrpc "github.com/lightninglabs/taproot-assets/taprpc/assetwalletrpc" + "github.com/lightninglabs/taproot-assets/taprpc/mintrpc" + "github.com/lightninglabs/taproot-assets/tapsend" + "github.com/stretchr/testify/require" + "google.golang.org/grpc/status" +) + +// testCommitVirtualPsbtsNoNewChange covers +// lightninglabs/taproot-assets#2209 (Satscrip #103 consumer). +// +// It builds a caller-exact BTC anchor template +// (tapsend.PrepareAnchoringTemplate) for a full-value interactive send, +// then calls CommitVirtualPsbts with skip_funding=false so that lnd must +// add a wallet fee input, twice: +// +// 1. Add{Add: true} (control): lnd appends a change output and +// change_output_index points at it. +// 2. Add{Add: false} (the #2209 case): lnd ignores the bool and would append +// the same change output, so tapd must fail closed with the exact error +// below and must release the wallet leases it just took. +func testCommitVirtualPsbtsNoNewChange(t *harnessTest) { + ctx := context.Background() + + rpcAssets := MintAssetsConfirmBatch( + t.t, t.lndHarness.Miner(), t.tapd, + []*mintrpc.MintAssetRequest{simpleAssets[0]}, + ) + minted := rpcAssets[0] + genInfo := minted.AssetGenesis + + lndBob := t.lndHarness.NewNodeWithCoins("Bob", nil) + bob := setupTapdHarness(t.t, t, lndBob, t.universeServer) + defer func() { + require.NoError(t.t, bob.stop(!*noDelete)) + }() + + var id [32]byte + copy(id[:], genInfo.AssetId) + + buildCommitReq := func(changeAdd bool) (*wrpc.CommitVirtualPsbtsRequest, + *psbt.Packet) { + + scriptKey, anchorIntKey := DeriveKeys(t.t, bob) + vPkt := tappsbt.ForInteractiveSend( + id, minted.Amount, scriptKey, 0, 0, 0, anchorIntKey, + asset.V0, &address.RegressionNetTap, + ) + fundResp := fundPacket(t, t.tapd, vPkt) + signResp, err := t.tapd.SignVirtualPsbt( + ctx, &wrpc.SignVirtualPsbtRequest{ + FundedPsbt: fundResp.FundedPsbt, + }, + ) + require.NoError(t.t, err) + + signed := deserializeVPacket(t.t, signResp.SignedPsbt) + all := []*tappsbt.VPacket{signed} + for _, p := range fundResp.PassiveAssetPsbts { + ps, err := t.tapd.SignVirtualPsbt( + ctx, &wrpc.SignVirtualPsbtRequest{ + FundedPsbt: p, + }, + ) + require.NoError(t.t, err) + passive := deserializeVPacket(t.t, ps.SignedPsbt) + all = append(all, passive) + } + + tmpl, err := tapsend.PrepareAnchoringTemplate(all) + require.NoError(t.t, err) + tmplBytes, err := fn.Serialize(tmpl) + require.NoError(t.t, err) + + req := &wrpc.CommitVirtualPsbtsRequest{ + AnchorPsbt: tmplBytes, + Fees: &wrpc.CommitVirtualPsbtsRequest_SatPerVbyte{ + SatPerVbyte: uint64(feeRateSatPerKVByte / 1000), + }, + AnchorChangeOutput: &wrpc.CommitVirtualPsbtsRequest_Add{ + Add: changeAdd, + }, + SkipFunding: false, + } + req.VirtualPsbts = [][]byte{signResp.SignedPsbt} + for _, p := range all[1:] { + enc, err := tappsbt.Encode(p) + require.NoError(t.t, err) + req.PassiveAssetPsbts = append( + req.PassiveAssetPsbts, enc, + ) + } + + return req, tmpl + } + + // Fund/sign the virtual packets exactly once (the asset input stays + // reserved by FundVirtualPsbt); only the anchor change policy differs + // between the two CommitVirtualPsbts calls. + baseReq, tmpl := buildCommitReq(true) + + commit := func(changeAdd bool) (*wrpc.CommitVirtualPsbtsResponse, + *psbt.Packet, *psbt.Packet, error) { + + req := baseReq + req.AnchorChangeOutput = &wrpc.CommitVirtualPsbtsRequest_Add{ + Add: changeAdd, + } + resp, err := t.tapd.CommitVirtualPsbts(ctx, req) + if err != nil { + return nil, tmpl, nil, err + } + out, err := psbt.NewFromRawBytes( + bytes.NewReader(resp.AnchorPsbt), false, + ) + require.NoError(t.t, err) + + return resp, tmpl, out, nil + } + + t.t.Run("control add=true appends change", func(tt *testing.T) { + resp, _, out, err := commit(true) + require.NoError(tt, err) + require.Greater( + tt, len(out.UnsignedTx.TxIn), len(tmpl.UnsignedTx.TxIn), + "lnd must add a wallet fee input", + ) + require.Equal( + tt, len(tmpl.UnsignedTx.TxOut)+1, + len(out.UnsignedTx.TxOut), + "add=true: one P2TR change output is appended", + ) + require.GreaterOrEqual(tt, resp.ChangeOutputIndex, int32(0)) + releaseLeases(t, resp) + }) + + t.t.Run("add=false fails closed and releases leases (#2209)", + func(tt *testing.T) { + lnd := t.tapd.cfg.LndNode + leasesBefore := len(lnd.RPC.ListLeases().LockedUtxos) + + resp, _, _, err := commit(false) + require.Nil(tt, resp) + require.Error(tt, err) + + // lnd appends the change output after the template + // outputs, so the change index equals the template + // output count. + numTmplOuts := len(tmpl.UnsignedTx.TxOut) + expected := fmt.Sprintf("unexpected anchor change "+ + "output: anchor_change_output add=false "+ + "cannot be honored, lnd changed the anchor "+ + "output set (change output index %d, outputs "+ + "%d -> %d); use skip_funding=true with "+ + "caller-supplied inputs or add=true (see "+ + "lightninglabs/taproot-assets#2209)", + numTmplOuts, numTmplOuts, numTmplOuts+1) + require.Equal( + tt, expected, status.Convert(err).Message(), + ) + + // The failed call must not leak any lnd lease. + leasesAfter := len(lnd.RPC.ListLeases().LockedUtxos) + require.Equal(tt, leasesBefore, leasesAfter) + }, + ) +} + +// releaseLeases unlocks the wallet inputs lnd leased while funding, so the +// draft test leaves the harness wallet usable. +func releaseLeases(t *harnessTest, resp *wrpc.CommitVirtualPsbtsResponse) { + if resp == nil || len(resp.LndLockedUtxos) == 0 { + return + } + // Best effort only: the harness is torn down after the test. + t.Logf("leaving %d lnd leases to harness teardown", + len(resp.LndLockedUtxos)) +} diff --git a/itest/mint_custom_anchor_restart_test.go b/itest/mint_custom_anchor_restart_test.go new file mode 100644 index 0000000000..65f41126dd --- /dev/null +++ b/itest/mint_custom_anchor_restart_test.go @@ -0,0 +1,163 @@ +//nolint:lll +package itest + +import ( + "bytes" + "context" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/btcutil/psbt" + "github.com/btcsuite/btcd/txscript" + "github.com/btcsuite/btcd/wire" + "github.com/lightninglabs/taproot-assets/asset" + "github.com/lightninglabs/taproot-assets/fn" + "github.com/lightninglabs/taproot-assets/tappsbt" + "github.com/lightninglabs/taproot-assets/taprpc/mintrpc" + "github.com/lightningnetwork/lnd/keychain" + "github.com/lightningnetwork/lnd/lnrpc/walletrpc" + "github.com/stretchr/testify/require" +) + +// testMintCustomAnchorPsbtRestart stops tapd after PrepareBatch and verifies +// that restart does not wallet-sign the prepared packet. Finalization still +// succeeds via an externally signed PSBT (anchor output index 0; non-zero index +// is covered by tapgarden unit tests). +func testMintCustomAnchorPsbtRestart(t *harnessTest) { + var ( + ctx = context.Background() + aliceTapd = t.tapd + aliceLnd = t.tapd.cfg.LndNode + miner = t.lndHarness.Miner() + ) + + mintReq := CopyRequest(simpleAssets[0]) + mintReq.Asset.Name = "issue-721-custom-anchor-restart" + mintReq.Asset.Amount = 50 + mintReqs := []*mintrpc.MintAssetRequest{mintReq} + + BuildMintingBatch(t.t, aliceTapd, mintReqs) + + anchorKeyResp := aliceLnd.RPC.DeriveNextKey(&walletrpc.KeyReq{ + KeyFamily: int32(asset.TaprootAssetsKeyFamily), + }) + anchorInternalKey, err := btcec.ParsePubKey(anchorKeyResp.RawKeyBytes) + require.NoError(t.t, err) + anchorOutputKey := txscript.ComputeTaprootKeyNoScript(anchorInternalKey) + anchorScript, err := txscript.PayToTaprootScript(anchorOutputKey) + require.NoError(t.t, err) + + const anchorValue = int64(10_000) + tx := wire.NewMsgTx(2) + tx.AddTxOut(&wire.TxOut{ + Value: anchorValue, + PkScript: anchorScript, + }) + template, err := psbt.NewFromUnsignedTx(tx) + require.NoError(t.t, err) + anchorKeyDesc := keychain.KeyDescriptor{ + PubKey: anchorInternalKey, + KeyLocator: keychain.KeyLocator{ + Family: keychain.KeyFamily(anchorKeyResp.KeyLoc.KeyFamily), + Index: uint32(anchorKeyResp.KeyLoc.KeyIndex), + }, + } + bip32Derivation, taprootDerivation := + tappsbt.Bip32DerivationFromKeyDesc( + anchorKeyDesc, harnessNetParams.HDCoinType, + ) + template.Outputs[0].Bip32Derivation = []*psbt.Bip32Derivation{ + bip32Derivation, + } + template.Outputs[0].TaprootBip32Derivation = + []*psbt.TaprootBip32Derivation{taprootDerivation} + template.Outputs[0].TaprootInternalKey = + taprootDerivation.XOnlyPubKey + + templateBytes, err := fn.Serialize(template) + require.NoError(t.t, err) + fundResp := aliceLnd.RPC.FundPsbt(&walletrpc.FundPsbtRequest{ + Template: &walletrpc.FundPsbtRequest_CoinSelect{ + CoinSelect: &walletrpc.PsbtCoinSelect{ + Psbt: templateBytes, + ChangeOutput: &walletrpc.PsbtCoinSelect_Add{ + Add: true, + }, + }, + }, + Fees: &walletrpc.FundPsbtRequest_SatPerVbyte{ + SatPerVbyte: 2, + }, + MinConfs: 1, + ChangeType: walletrpc.ChangeAddressType_CHANGE_ADDRESS_TYPE_P2TR, + MaxFeeRatio: 1, + }) + for _, lease := range fundResp.LockedUtxos { + _, err := aliceLnd.RPC.WalletKit.ReleaseOutput( + ctx, &walletrpc.ReleaseOutputRequest{ + Id: lease.Id, + Outpoint: lease.Outpoint, + }, + ) + require.NoError(t.t, err) + } + + _, err = aliceTapd.FundBatch(ctx, &mintrpc.FundBatchRequest{ + AnchorPsbt: fundResp.FundedPsbt, + AssetAnchorOutputIndex: 0, + ChangeOutputIndex: fundResp.ChangeOutputIndex, + }) + require.NoError(t.t, err) + + prepareResp, err := aliceTapd.PrepareBatch( + ctx, &mintrpc.PrepareBatchRequest{}, + ) + require.NoError(t.t, err) + require.Equal( + t.t, mintrpc.BatchState_BATCH_STATE_COMMITTED, + prepareResp.Batch.State, + ) + batchKey := prepareResp.Batch.BatchKey + + require.NoError(t.t, aliceTapd.stop(false)) + require.NoError(t.t, aliceTapd.start(false)) + + listResp, err := aliceTapd.ListBatches(ctx, &mintrpc.ListBatchRequest{ + Filter: &mintrpc.ListBatchRequest_BatchKey{BatchKey: batchKey}, + }) + require.NoError(t.t, err) + require.Len(t.t, listResp.Batches, 1) + require.Equal( + t.t, mintrpc.BatchState_BATCH_STATE_COMMITTED, + listResp.Batches[0].Batch.State, + ) + + preparedPacket, err := psbt.NewFromRawBytes( + bytes.NewReader(listResp.Batches[0].Batch.BatchPsbt), false, + ) + require.NoError(t.t, err) + signedPacket := FinalizePacket(t.t, aliceLnd.RPC, preparedPacket) + signedBytes, err := fn.Serialize(signedPacket) + require.NoError(t.t, err) + + finalizeResp, err := aliceTapd.FinalizeBatch( + ctx, &mintrpc.FinalizeBatchRequest{SignedPsbt: signedBytes}, + ) + require.NoError(t.t, err) + require.Equal( + t.t, mintrpc.BatchState_BATCH_STATE_BROADCAST, + finalizeResp.Batch.State, + ) + + hashes, err := WaitForNTxsInMempool(miner, 1, defaultWaitTimeout) + require.NoError(t.t, err) + block := MineBlocks(t.t, miner, 1, 1)[0] + ctxWait, cancelWait := context.WithTimeout(ctx, defaultWaitTimeout) + defer cancelWait() + WaitForBatchState( + t.t, ctxWait, aliceTapd, defaultWaitTimeout, batchKey, + mintrpc.BatchState_BATCH_STATE_FINALIZED, + ) + AssertAssetsMinted( + t.t, aliceTapd, mintReqs, *hashes[0], block.BlockHash(), + ) +} diff --git a/itest/mint_custom_anchor_test.go b/itest/mint_custom_anchor_test.go new file mode 100644 index 0000000000..d053a34263 --- /dev/null +++ b/itest/mint_custom_anchor_test.go @@ -0,0 +1,239 @@ +//nolint:lll +package itest + +import ( + "bytes" + "context" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/btcec/v2/schnorr" + "github.com/btcsuite/btcd/btcutil/psbt" + "github.com/btcsuite/btcd/txscript" + "github.com/btcsuite/btcd/wire" + "github.com/lightninglabs/taproot-assets/asset" + "github.com/lightninglabs/taproot-assets/fn" + "github.com/lightninglabs/taproot-assets/tappsbt" + "github.com/lightninglabs/taproot-assets/taprpc" + "github.com/lightninglabs/taproot-assets/taprpc/mintrpc" + "github.com/lightningnetwork/lnd/keychain" + "github.com/lightningnetwork/lnd/lnrpc/walletrpc" + "github.com/stretchr/testify/require" +) + +// testMintCustomAnchorPsbt proves the complete issue #721 lifecycle with a +// wallet-owned, caller-authored anchor: fund, prepare, externally sign, +// finalize, confirm, and spend the minted asset to a second tapd node. +func testMintCustomAnchorPsbt(t *harnessTest) { + var ( + ctx = context.Background() + aliceTapd = t.tapd + aliceLnd = t.tapd.cfg.LndNode + miner = t.lndHarness.Miner() + ) + + bobLnd := t.lndHarness.NewNodeWithCoins("custom-anchor-bob", nil) + bobTapd := setupTapdHarness(t.t, t, bobLnd, t.universeServer) + defer func() { + require.NoError(t.t, bobTapd.stop(!*noDelete)) + }() + + mintReq := CopyRequest(simpleAssets[0]) + mintReq.Asset.Name = "issue-721-custom-anchor-itest" + mintReq.Asset.Amount = 100 + mintReqs := []*mintrpc.MintAssetRequest{mintReq} + + BuildMintingBatch(t.t, aliceTapd, mintReqs) + + // Use an lnd-owned internal key as the caller-selected asset anchor. The + // output derivation fields use lnd's BIP-0043 purpose (1017') so tapd can + // prove the locator belongs to the same wallet before committing it. + anchorKeyResp := aliceLnd.RPC.DeriveNextKey(&walletrpc.KeyReq{ + KeyFamily: int32(asset.TaprootAssetsKeyFamily), + }) + anchorInternalKey, err := btcec.ParsePubKey(anchorKeyResp.RawKeyBytes) + require.NoError(t.t, err) + anchorOutputKey := txscript.ComputeTaprootKeyNoScript(anchorInternalKey) + anchorScript, err := txscript.PayToTaprootScript(anchorOutputKey) + require.NoError(t.t, err) + + const anchorValue = int64(10_000) + tx := wire.NewMsgTx(2) + tx.AddTxOut(&wire.TxOut{ + Value: anchorValue, + PkScript: anchorScript, + }) + template, err := psbt.NewFromUnsignedTx(tx) + require.NoError(t.t, err) + anchorKeyDesc := keychain.KeyDescriptor{ + PubKey: anchorInternalKey, + KeyLocator: keychain.KeyLocator{ + Family: keychain.KeyFamily(anchorKeyResp.KeyLoc.KeyFamily), + Index: uint32(anchorKeyResp.KeyLoc.KeyIndex), + }, + } + bip32Derivation, taprootDerivation := + tappsbt.Bip32DerivationFromKeyDesc( + anchorKeyDesc, harnessNetParams.HDCoinType, + ) + template.Outputs[0].Bip32Derivation = []*psbt.Bip32Derivation{ + bip32Derivation, + } + template.Outputs[0].TaprootBip32Derivation = + []*psbt.TaprootBip32Derivation{taprootDerivation} + template.Outputs[0].TaprootInternalKey = + taprootDerivation.XOnlyPubKey + template.Outputs[0].Unknowns = []*psbt.Unknown{{ + Key: []byte{0x50}, Value: []byte("issue-721-anchor"), + }} + internalKey, err := schnorr.ParsePubKey(taprootDerivation.XOnlyPubKey) + require.NoError(t.t, err) + bip86OutputKey := txscript.ComputeTaprootKeyNoScript(internalKey) + require.Equal(t.t, schnorr.SerializePubKey(bip86OutputKey), + anchorScript[2:]) + + templateBytes, err := fn.Serialize(template) + require.NoError(t.t, err) + fundResp := aliceLnd.RPC.FundPsbt(&walletrpc.FundPsbtRequest{ + Template: &walletrpc.FundPsbtRequest_CoinSelect{ + CoinSelect: &walletrpc.PsbtCoinSelect{ + Psbt: templateBytes, + ChangeOutput: &walletrpc.PsbtCoinSelect_Add{ + Add: true, + }, + }, + }, + Fees: &walletrpc.FundPsbtRequest_SatPerVbyte{ + SatPerVbyte: 2, + }, + MinConfs: 1, + ChangeType: walletrpc.ChangeAddressType_CHANGE_ADDRESS_TYPE_P2TR, + MaxFeeRatio: 1, + }) + require.NotEmpty(t.t, fundResp.LockedUtxos) + require.GreaterOrEqual(t.t, fundResp.ChangeOutputIndex, int32(1)) + + fundedPacket, err := psbt.NewFromRawBytes( + bytes.NewReader(fundResp.FundedPsbt), false, + ) + require.NoError(t.t, err) + require.NotEmpty(t.t, fundedPacket.Inputs) + require.Equal(t.t, anchorValue, + fundedPacket.UnsignedTx.TxOut[0].Value) + require.Equal(t.t, anchorScript, + fundedPacket.UnsignedTx.TxOut[0].PkScript) + + // FundPsbt initially leases every selected wallet input under its own + // lock ID. Release those leases before FundBatch asks tapd to acquire + // the same inputs under the custom-anchor lease ID. + for _, lease := range fundResp.LockedUtxos { + _, err := aliceLnd.RPC.WalletKit.ReleaseOutput( + ctx, &walletrpc.ReleaseOutputRequest{ + Id: lease.Id, + Outpoint: lease.Outpoint, + }, + ) + require.NoError(t.t, err) + } + + fundBatchResp, err := aliceTapd.FundBatch( + ctx, &mintrpc.FundBatchRequest{ + AnchorPsbt: fundResp.FundedPsbt, + AssetAnchorOutputIndex: 0, + ChangeOutputIndex: fundResp.ChangeOutputIndex, + }, + ) + require.NoError(t.t, err) + require.Equal( + t.t, mintrpc.BatchState_BATCH_STATE_PENDING, + fundBatchResp.Batch.Batch.State, + ) + + prepareResp, err := aliceTapd.PrepareBatch( + ctx, &mintrpc.PrepareBatchRequest{}, + ) + require.NoError(t.t, err) + require.Equal( + t.t, mintrpc.BatchState_BATCH_STATE_COMMITTED, + prepareResp.Batch.State, + ) + preparedPacket, err := psbt.NewFromRawBytes( + bytes.NewReader(prepareResp.Batch.BatchPsbt), false, + ) + require.NoError(t.t, err) + + // Preparation is allowed to replace only the selected anchor script. + require.Equal(t.t, fundedPacket.UnsignedTx.TxIn, + preparedPacket.UnsignedTx.TxIn) + require.Equal(t.t, fundedPacket.Inputs, preparedPacket.Inputs) + require.Equal(t.t, anchorValue, + preparedPacket.UnsignedTx.TxOut[0].Value) + require.NotEqual(t.t, anchorScript, + preparedPacket.UnsignedTx.TxOut[0].PkScript) + require.Equal(t.t, fundedPacket.Outputs[0].Bip32Derivation, + preparedPacket.Outputs[0].Bip32Derivation) + require.Equal(t.t, fundedPacket.Outputs[0].Unknowns, + preparedPacket.Outputs[0].Unknowns) + require.Nil(t.t, preparedPacket.Outputs[0].TaprootInternalKey) + require.Nil(t.t, preparedPacket.Outputs[0].TaprootBip32Derivation) + for idx := 1; idx < len(fundedPacket.UnsignedTx.TxOut); idx++ { + require.Equal(t.t, fundedPacket.UnsignedTx.TxOut[idx], + preparedPacket.UnsignedTx.TxOut[idx]) + require.Equal(t.t, fundedPacket.Outputs[idx], + preparedPacket.Outputs[idx]) + } + + // WalletKit signs the wallet input and local PSBT finalization is used + // for compatibility with the remote-signing itest mode. + signedPacket := FinalizePacket(t.t, aliceLnd.RPC, preparedPacket) + signedBytes, err := fn.Serialize(signedPacket) + require.NoError(t.t, err) + ctxFinalize, cancelFinalize := context.WithTimeout(ctx, defaultWaitTimeout) + finalizeResp, err := aliceTapd.FinalizeBatch( + ctxFinalize, &mintrpc.FinalizeBatchRequest{ + SignedPsbt: signedBytes, + }, + ) + cancelFinalize() + require.NoError(t.t, err) + require.Equal( + t.t, mintrpc.BatchState_BATCH_STATE_BROADCAST, + finalizeResp.Batch.State, + ) + + hashes, err := WaitForNTxsInMempool(miner, 1, defaultWaitTimeout) + require.NoError(t.t, err) + require.Len(t.t, hashes, 1) + block := MineBlocks(t.t, miner, 1, 1)[0] + ctxWait, cancelWait := context.WithTimeout(ctx, defaultWaitTimeout) + defer cancelWait() + WaitForBatchState( + t.t, ctxWait, aliceTapd, defaultWaitTimeout, + finalizeResp.Batch.BatchKey, + mintrpc.BatchState_BATCH_STATE_FINALIZED, + ) + mintedAssets := AssertAssetsMinted( + t.t, aliceTapd, mintReqs, *hashes[0], block.BlockHash(), + ) + require.Len(t.t, mintedAssets, 1) + mintedAsset := mintedAssets[0] + + const sendAmount = uint64(40) + bobAddr, err := bobTapd.NewAddr(ctx, &taprpc.NewAddrRequest{ + AssetId: mintedAsset.AssetGenesis.AssetId, + Amt: sendAmount, + }) + require.NoError(t.t, err) + AssertAddrCreated(t.t, bobTapd, mintedAsset, bobAddr) + + sendResp, sendEvents := sendAssetsToAddr(t, aliceTapd, bobAddr) + ConfirmAndAssertOutboundTransfer( + t.t, miner, aliceTapd, sendResp, + mintedAsset.AssetGenesis.AssetId, + []uint64{mintedAsset.Amount - sendAmount, sendAmount}, 0, 1, + ) + AssertNonInteractiveRecvComplete(t.t, bobTapd, 1) + AssertSendEventsComplete(t.t, bobAddr.ScriptKey, sendEvents) + AssertBalanceByID( + t.t, bobTapd, mintedAsset.AssetGenesis.AssetId, sendAmount, + ) +} diff --git a/itest/supply_commit_test.go b/itest/supply_commit_test.go index 252cf1935f..6422668d6a 100644 --- a/itest/supply_commit_test.go +++ b/itest/supply_commit_test.go @@ -147,6 +147,89 @@ func testPreCommitOutput(t *harnessTest) { require.EqualValues(t.t, tweakedGroupKey, secondAssetGroupKey) } +// testSupplyCommitBurialThreshold verifies review item 2: commitments are not +// finalized (no chain metadata in FetchSupplyCommit, no universe copy) until +// the broadcast tx reaches burial depth, then finalize runs. +func testSupplyCommitBurialThreshold(t *harnessTest) { + ctxb := context.Background() + miner := t.lndHarness.Miner() + + mintReq := CopyRequest(issuableAssets[0]) + mintReq.Asset.Amount = 1000 + + rpcAsset, _ := MintAssetWithSupplyCommit( + t, mintReq, fn.None[btcec.PublicKey](), + ) + groupKeyBytes := rpcAsset.AssetGroup.TweakedGroupKey + require.NotNil(t.t, groupKeyBytes) + + fetchReq := &unirpc.FetchSupplyCommitRequest{ + GroupKey: &unirpc.FetchSupplyCommitRequest_GroupKeyBytes{ + GroupKeyBytes: groupKeyBytes, + }, + Locator: &unirpc.FetchSupplyCommitRequest_VeryFirst{ + VeryFirst: true, + }, + } + + respUpdate, err := t.tapd.UpdateSupplyCommit( + ctxb, &unirpc.UpdateSupplyCommitRequest{ + GroupKey: &unirpc.UpdateSupplyCommitRequest_GroupKeyBytes{ + GroupKeyBytes: groupKeyBytes, + }, + }, + ) + require.NoError(t.t, err) + require.NotNil(t.t, respUpdate) + + t.Log("Mine inclusion block only (before burial depth)") + minedBlocks := MineBlocks(t.t, miner, 1, 1) + require.Len(t.t, minedBlocks, 1) + inclusionHash := minedBlocks[0].BlockHash() + + require.Eventually(t.t, func() bool { + _, fetchErr := t.tapd.FetchSupplyCommit(ctxb, fetchReq) + if fetchErr == nil { + return false + } + + return strings.Contains( + fetchErr.Error(), "no block info available", + ) + }, defaultWaitTimeout, time.Second) + + _, uniErr := t.universeServer.service.FetchSupplyCommit( + ctxb, fetchReq, + ) + require.Error(t.t, uniErr) + + t.Log("Mine burial depth blocks and expect finalize + universe push") + MineSupplyCommitBurial(t.t, miner) + + fetchResp, _ := WaitForSupplyCommit( + t.t, ctxb, t.tapd, groupKeyBytes, fn.None[wire.OutPoint](), + func(resp *unirpc.FetchSupplyCommitResponse) bool { + return resp.ChainData.BlockHeight > 0 && + len(resp.ChainData.BlockHash) > 0 + }, + ) + + fetchBlockHash, err := chainhash.NewHash(fetchResp.ChainData.BlockHash) + require.NoError(t.t, err) + require.True(t.t, fetchBlockHash.IsEqual(&inclusionHash)) + + uniFetchPred := func(resp *unirpc.FetchSupplyCommitResponse) error { + if resp.ChainData.BlockHeight == 0 { + return fmt.Errorf("supply commitment not on universe") + } + + return nil + } + rpcassert.FetchSupplyCommitRPC( + t.t, ctxb, t.universeServer.service, uniFetchPred, fetchReq, + ) +} + // testSupplyCommitIgnoreAsset verifies that universe supply commitments // correctly account for ignored asset outpoints. It: // @@ -277,20 +360,11 @@ func testSupplyCommitIgnoreAsset(t *harnessTest) { require.ErrorContains(t.t, err, "commitment not found") t.Log("Update on-chain supply commitment for asset group") - - // nolint: lll - respUpdate, err := t.tapd.UpdateSupplyCommit( - ctxb, &unirpc.UpdateSupplyCommitRequest{ - GroupKey: &unirpc.UpdateSupplyCommitRequest_GroupKeyBytes{ - GroupKeyBytes: groupKeyBytes, - }, - }, + _, commitInclusionHeightBefore := t.lndHarness.Miner().GetBestBlock() + minedBlocks := UpdateAndMineSupplyCommit( + t.t, ctxb, t.tapd, t.lndHarness.Miner(), groupKeyBytes, 1, ) - require.NoError(t.t, err) - require.NotNil(t.t, respUpdate) - - t.Log("Mining supply commitment tx") - minedBlocks := MineBlocks(t.t, t.lndHarness.Miner(), 1, 1) + commitInclusionHeight := commitInclusionHeightBefore + 1 t.Log("Fetch updated supply commitment") @@ -398,19 +472,16 @@ func testSupplyCommitIgnoreAsset(t *harnessTest) { require.Len(t.t, minedBlocks, 1) block := minedBlocks[0] - expectedBlockHash := block.BlockHash() - - // Get block height for block. - blockHash, blockHeight := t.lndHarness.Miner().GetBestBlock() - require.True(t.t, blockHash.IsEqual(&expectedBlockHash)) + commitBlockHash := block.BlockHash() // Ensure that the block hash and height matches the values in the fetch - // response. + // response (inclusion block, not chain tip after burial confs). fetchBlockHash, err := chainhash.NewHash(fetchResp.ChainData.BlockHash) require.NoError(t.t, err) - require.True(t.t, fetchBlockHash.IsEqual(blockHash)) + require.True(t.t, fetchBlockHash.IsEqual(&commitBlockHash)) - require.EqualValues(t.t, blockHeight, fetchResp.ChainData.BlockHeight) + require.EqualValues(t.t, commitInclusionHeight, + fetchResp.ChainData.BlockHeight) // We expect two transactions in the block: // 1. The supply commitment transaction. @@ -999,11 +1070,11 @@ func testSupplyCommitMintBurn(t *harnessTest) { // pkScript that we expect. require.Len(t.t, finalMinedBlocks, 1, "expected one mined block") block := finalMinedBlocks[0] - blockHash, _ := t.lndHarness.Miner().GetBestBlock() + commitBlockHash := block.BlockHash() fetchBlockHash, err := chainhash.NewHash(fetchResp.ChainData.BlockHash) require.NoError(t.t, err) - require.True(t.t, fetchBlockHash.IsEqual(blockHash)) + require.True(t.t, fetchBlockHash.IsEqual(&commitBlockHash)) // Re-compute the supply commitment root hash from the latest fetch, // then use that to derive the expected commitment output. @@ -1864,3 +1935,133 @@ func testSupplyVerifyPeerNode(t *harnessTest) { // primary's. assertFetchCommitResponse(t, thirdSupplyCommitResp, peerFetchResp3) } + +// Keep the idle interval well above supply-commit burial depth so the extra +// blocks mined for finalization do not publish the idle successor early. +const supplyIdleCommitInterval = uint32(12) + +// testSupplyCommitIdleTick verifies that a locally controlled asset group +// publishes an empty ancestry-linked successor supply commitment once the +// latest commitment is at least supplyIdleCommitInterval blocks old, and that +// an interrupted idle transition resumes after tapd restarts. +func testSupplyCommitIdleTick(t *harnessTest) { + ctxb := context.Background() + miner := t.lndHarness.Miner() + + // Enable the idle tick before any supply commitment activity. + t.tapd.setCliFlag( + "universe.supply-idle-commit-interval", + fmt.Sprintf("%d", supplyIdleCommitInterval), + ) + require.NoError(t.t, t.tapd.stop(false)) + require.NoError(t.t, t.tapd.start(false)) + + t.Log("Minting asset with supply commitments enabled") + mintReq := CopyRequest(issuableAssets[0]) + mintReq.Asset.Amount = 1000 + rpcAsset, _ := MintAssetWithSupplyCommit( + t, mintReq, fn.None[btcec.PublicKey](), + ) + + groupKeyBytes := rpcAsset.AssetGroup.TweakedGroupKey + require.NotNil(t.t, groupKeyBytes) + + t.Log("Creating the first on-chain supply commitment manually") + UpdateAndMineSupplyCommit( + t.t, ctxb, t.tapd, miner, groupKeyBytes, 1, + ) + + firstCommit, firstOutpoint := WaitForSupplyCommit( + t.t, ctxb, t.tapd, groupKeyBytes, fn.None[wire.OutPoint](), + func(resp *unirpc.FetchSupplyCommitResponse) bool { + return resp.ChainData.BlockHeight > 0 && + len(resp.ChainData.BlockHash) > 0 + }, + ) + require.NotNil(t.t, firstCommit.IssuanceSubtreeRoot) + firstRootHash := firstCommit.ChainData.SupplyRootHash + firstIssuanceRoot := firstCommit.IssuanceSubtreeRoot.RootNode.RootHash + firstIssuanceSum := firstCommit.IssuanceSubtreeRoot.RootNode.RootSum + + mineIdleSuccessor := func(prevOutpoint wire.OutPoint, + prevHeight uint32) (*unirpc.FetchSupplyCommitResponse, + wire.OutPoint) { + + if supplyIdleCommitInterval > 1 { + MineBlocks( + t.t, miner, supplyIdleCommitInterval-1, 0, + ) + } + + // The idle tick fires once the chain reaches the due height, + // broadcasting the successor into the mempool. Mine that block + // without expecting the tx yet, then mine the inclusion block. + MineBlocks(t.t, miner, 1, 0) + MineBlocks(t.t, miner, 1, 1) + MineSupplyCommitBurial(t.t, miner) + + return WaitForSupplyCommit( + t.t, ctxb, t.tapd, groupKeyBytes, + fn.Some(prevOutpoint), + func(r *unirpc.FetchSupplyCommitResponse) bool { + if r.ChainData.BlockHeight <= prevHeight { + return false + } + + if r.IssuanceSubtreeRoot == nil { + return false + } + + return r.IssuanceSubtreeRoot.RootNode.RootSum == + firstIssuanceSum + }, + ) + } + + t.Log("Mining blocks until the idle successor should be published") + idleCommit, idleOutpoint := mineIdleSuccessor( + firstOutpoint, firstCommit.ChainData.BlockHeight, + ) + + require.Equal( + t.t, firstRootHash, idleCommit.ChainData.SupplyRootHash, + ) + require.Equal( + t.t, firstIssuanceRoot, + idleCommit.IssuanceSubtreeRoot.RootNode.RootHash, + ) + AssertSubtreeInclusionProof( + t, idleCommit.ChainData.SupplyRootHash, + idleCommit.IssuanceSubtreeRoot, + ) + + t.Log("Interrupting the next idle successor and resuming after restart") + if supplyIdleCommitInterval > 1 { + MineBlocks(t.t, miner, supplyIdleCommitInterval-1, 0) + } + MineBlocks(t.t, miner, 1, 0) + + _, err := WaitForNTxsInMempool(miner, 1, minerMempoolTimeout) + require.NoError(t.t, err) + + require.NoError(t.t, t.tapd.stop(false)) + MineBlocks(t.t, miner, 1, 1) + MineSupplyCommitBurial(t.t, miner) + require.NoError(t.t, t.tapd.start(false)) + + secondIdleCommit, _ := WaitForSupplyCommit( + t.t, ctxb, t.tapd, groupKeyBytes, + fn.Some(idleOutpoint), + func(resp *unirpc.FetchSupplyCommitResponse) bool { + return resp.ChainData.BlockHeight > + idleCommit.ChainData.BlockHeight + }, + ) + require.Equal( + t.t, firstRootHash, secondIdleCommit.ChainData.SupplyRootHash, + ) + AssertSubtreeInclusionProof( + t, secondIdleCommit.ChainData.SupplyRootHash, + secondIdleCommit.IssuanceSubtreeRoot, + ) +} diff --git a/itest/tapd_harness.go b/itest/tapd_harness.go index 82dd810742..d547d4c414 100644 --- a/itest/tapd_harness.go +++ b/itest/tapd_harness.go @@ -477,6 +477,12 @@ func newTapdHarness(t *testing.T, ht *harnessTest, cfg tapdConfig, args = append(args, "--experimental.rfq.sendpricehint") } + // Optional extra tapd flags for integration test matrix runs (for + // example supply idle tick regression). + if extra := os.Getenv("ITEST_TAPD_EXTRA_ARGS"); extra != "" { + args = append(args, strings.Fields(extra)...) + } + // Compute the expected TLS cert path and macaroon path based on // the tapd directory structure that the tapd process will create. tlsCertPath := filepath.Join(cfg.BaseDir, "tls.cert") @@ -612,6 +618,15 @@ func (hs *tapdHarness) updateLndNode(lndNode *node.HarnessNode) { // start spins up the tapd process and waits for it to be ready for gRPC // connections. func (hs *tapdHarness) start(expectErrExit bool) error { + if hs.cmd != nil && hs.processDone != nil { + select { + case <-hs.processDone: + default: + return fmt.Errorf("tapd (name=%v) is already running", + hs.cfg.LndNode.Cfg.Name) + } + } + //nolint:gosec hs.cmd = exec.Command("./tapd-itest", hs.cliArgs...) @@ -768,6 +783,15 @@ func (hs *tapdHarness) stop(deleteData bool) error { // Reset RPC clients so they get re-created on next start(). hs.TaprootAssetsClient = nil + hs.AssetWalletClient = nil + hs.MintClient = nil + hs.RfqClient = nil + hs.TaprootAssetChannelsClient = nil + hs.UniverseClient = nil + hs.TapDevClient = nil + hs.MailboxClient = nil + hs.cmd = nil + hs.processDone = nil // Clean up data directory. if deleteData { diff --git a/itest/test_list_on_test.go b/itest/test_list_on_test.go index 070dcd8e92..6ebda4e622 100644 --- a/itest/test_list_on_test.go +++ b/itest/test_list_on_test.go @@ -49,6 +49,14 @@ var allTestCases = []*testCase{ name: "mint fund seal assets", test: testMintFundSealAssets, }, + { + name: "mint custom anchor psbt", + test: testMintCustomAnchorPsbt, + }, + { + name: "mint custom anchor psbt restart", + test: testMintCustomAnchorPsbtRestart, + }, { name: "mint external group key chantools", test: testMintExternalGroupKeyChantools, @@ -431,6 +439,14 @@ var allTestCases = []*testCase{ name: "supply commit mint burn", test: testSupplyCommitMintBurn, }, + { + name: "supply commit idle tick", + test: testSupplyCommitIdleTick, + }, + { + name: "supply commit burial threshold", + test: testSupplyCommitBurialThreshold, + }, { name: "supply verify peer node", test: testSupplyVerifyPeerNode, diff --git a/lndservices/wallet_anchor.go b/lndservices/wallet_anchor.go index fe6bf2e973..02a1450201 100644 --- a/lndservices/wallet_anchor.go +++ b/lndservices/wallet_anchor.go @@ -2,8 +2,10 @@ package lndservices import ( "context" + "errors" "fmt" "math" + "time" "github.com/btcsuite/btcd/btcec/v2" "github.com/btcsuite/btcd/btcutil" @@ -11,6 +13,7 @@ import ( "github.com/btcsuite/btcd/chaincfg/chainhash" "github.com/btcsuite/btcd/wire" "github.com/btcsuite/btcwallet/waddrmgr" + "github.com/btcsuite/btcwallet/wtxmgr" "github.com/lightninglabs/lndclient" "github.com/lightninglabs/taproot-assets/fn" "github.com/lightninglabs/taproot-assets/tapfreighter" @@ -81,6 +84,8 @@ const ( // defaultChangeType is the default change type we'll use when using the // PSBT APIs. defaultChangeType = walletrpc.ChangeAddressType_CHANGE_ADDRESS_TYPE_P2TR + + customAnchorLeaseDuration = 24 * time.Hour ) // FundPsbt attaches enough inputs to the target PSBT packet for it to be @@ -200,6 +205,149 @@ func (l *LndRpcWalletAnchor) ImportTaprootOutput(ctx context.Context, return addr, nil } +// LeaseInputs leases wallet-owned inputs for a custom-anchor mint batch. +func (l *LndRpcWalletAnchor) LeaseInputs(ctx context.Context, + leaseID tapgarden.CustomAnchorLeaseID, + ops []wire.OutPoint) ([]wire.OutPoint, error) { + + if len(ops) == 0 { + return nil, nil + } + + seen := make(map[wire.OutPoint]struct{}, len(ops)) + for _, op := range ops { + if _, ok := seen[op]; ok { + return nil, fmt.Errorf( + "custom anchor input is repeated: %v", op, + ) + } + seen[op] = struct{}{} + } + + lockID := wtxmgr.LockID(leaseID) + leases, err := l.lnd.WalletKit.ListLeases(ctx) + if err != nil { + return nil, fmt.Errorf("error listing existing leases: %w", err) + } + leaseByOutpoint := make(map[wire.OutPoint]lndclient.LeaseDescriptor, + len(leases)) + for _, lease := range leases { + leaseByOutpoint[lease.Outpoint] = lease + } + + for _, op := range ops { + lease, ok := leaseByOutpoint[op] + if ok && lease.LockID != lockID { + return nil, fmt.Errorf( + "wallet input %v is already leased by "+ + "another batch or subsystem", op, + ) + } + } + + needUnspent := false + for _, op := range ops { + if _, ok := leaseByOutpoint[op]; !ok { + needUnspent = true + break + } + } + walletInputs := make(map[wire.OutPoint]struct{}) + if needUnspent { + utxos, err := l.lnd.WalletKit.ListUnspent( + ctx, 0, math.MaxInt32, + ) + if err != nil { + return nil, fmt.Errorf( + "error listing wallet inputs: %w", err, + ) + } + walletInputs = make(map[wire.OutPoint]struct{}, len(utxos)) + for _, utxo := range utxos { + walletInputs[utxo.OutPoint] = struct{}{} + } + } + + locked := make([]wire.OutPoint, 0, len(ops)) + for _, op := range ops { + _, alreadyLeased := leaseByOutpoint[op] + _, walletOwned := walletInputs[op] + if !alreadyLeased && !walletOwned { + continue + } + + _, err := l.lnd.WalletKit.LeaseOutput( + ctx, lockID, op, customAnchorLeaseDuration, + ) + if err != nil { + return locked, fmt.Errorf( + "unable to lease wallet input %v: %w", op, err, + ) + } + locked = append(locked, op) + } + + lockedSet := make(map[wire.OutPoint]struct{}, len(locked)) + for _, op := range locked { + lockedSet[op] = struct{}{} + } + for _, op := range ops { + lease, leased := leaseByOutpoint[op] + _, walletOwned := walletInputs[op] + if leased && lease.LockID != lockID { + continue + } + if !walletOwned && !leased { + continue + } + if _, ok := lockedSet[op]; !ok { + return locked, fmt.Errorf( + "wallet input %v was not locked for custom "+ + "anchor batch", op, + ) + } + } + + return locked, nil +} + +// ReleaseInputs releases custom-anchor leases owned by leaseID. +func (l *LndRpcWalletAnchor) ReleaseInputs(ctx context.Context, + leaseID tapgarden.CustomAnchorLeaseID, ops []wire.OutPoint) error { + + if len(ops) == 0 { + return nil + } + + lockID := wtxmgr.LockID(leaseID) + leases, err := l.lnd.WalletKit.ListLeases(ctx) + if err != nil { + return fmt.Errorf("error listing existing leases: %w", err) + } + owned := make(map[wire.OutPoint]struct{}, len(leases)) + for _, lease := range leases { + if lease.LockID == lockID { + owned[lease.Outpoint] = struct{}{} + } + } + + var releaseErr error + for _, op := range ops { + if _, ok := owned[op]; !ok { + continue + } + err := l.lnd.WalletKit.ReleaseOutput(ctx, lockID, op) + if err != nil { + releaseErr = errors.Join(releaseErr, fmt.Errorf( + "error releasing custom anchor lease %v: %w", + op, err, + )) + } + } + + return releaseErr +} + // UnlockInput unlocks the set of target inputs after a batch or send // transaction is abandoned. func (l *LndRpcWalletAnchor) UnlockInput(ctx context.Context, @@ -277,5 +425,6 @@ func (l *LndRpcWalletAnchor) MinRelayFee( // A compile time assertion to ensure LndRpcWalletAnchor meets the // tapgarden.WalletAnchor interface. var _ tapgarden.WalletAnchor = (*LndRpcWalletAnchor)(nil) +var _ tapgarden.CustomAnchorBatchLeaser = (*LndRpcWalletAnchor)(nil) var _ tapfreighter.WalletAnchor = (*LndRpcWalletAnchor)(nil) diff --git a/rpcserver/commit_fund_virtual_psbts.go b/rpcserver/commit_fund_virtual_psbts.go new file mode 100644 index 0000000000..6c9823946d --- /dev/null +++ b/rpcserver/commit_fund_virtual_psbts.go @@ -0,0 +1,278 @@ +package rpcserver + +import ( + "bytes" + "context" + "fmt" + + "github.com/btcsuite/btcd/btcutil/psbt" + "github.com/btcsuite/btcd/chaincfg/chainhash" + "github.com/btcsuite/btcd/wire" + "github.com/lightninglabs/taproot-assets/fn" + "github.com/lightninglabs/taproot-assets/taprpc" + "github.com/lightninglabs/taproot-assets/tappsbt" + "github.com/lightninglabs/taproot-assets/tapsend" + walletrpc "github.com/lightningnetwork/lnd/lnrpc/walletrpc" + wrpc "github.com/lightninglabs/taproot-assets/taprpc/assetwalletrpc" +) + +// fundAndCommitVirtualPsbts creates the output commitments and proofs for +// the given virtual transactions and funds the BTC level anchor. hooks may +// be nil. When set, onFunded runs after lnd returns the leased inputs and +// onResult runs with the finished response before those leases are kept. +func (r *RPCServer) fundAndCommitVirtualPsbts(ctx context.Context, + req *wrpc.CommitVirtualPsbtsRequest, + hooks *commitVirtualPsbtsHooks) (*wrpc.CommitVirtualPsbtsResponse, + error) { + + if len(req.VirtualPsbts) == 0 { + return nil, fmt.Errorf("no virtual PSBTs specified") + } + + proofOpts, err := transitionProofOptions(req.TransitionProofVersion) + if err != nil { + return nil, err + } + + pkt, err := psbt.NewFromRawBytes(bytes.NewReader(req.AnchorPsbt), false) + if err != nil { + return nil, fmt.Errorf("error decoding packet: %w", err) + } + + activePackets, err := decodeVirtualPackets(req.VirtualPsbts) + if err != nil { + return nil, fmt.Errorf("error decoding active packets: %w", err) + } + + passivePackets, err := decodeVirtualPackets(req.PassiveAssetPsbts) + if err != nil { + return nil, fmt.Errorf("error decoding passive packets: %w", + err) + } + + // Make sure the assets given fully satisfy the input commitments. + allPackets := append([]*tappsbt.VPacket{}, activePackets...) + allPackets = append(allPackets, passivePackets...) + err = r.validateInputAssets(ctx, pkt, allPackets) + if err != nil { + return nil, fmt.Errorf("error validating input assets: %w", err) + } + + // We're ready to attempt to fund the transaction now. For that we first + // need to re-serialize our packet. + packetBytes, err := fn.Serialize(pkt) + if err != nil { + return nil, fmt.Errorf("error serializing packet: %w", err) + } + + var ( + lockedUTXO []*walletrpc.UtxoLease + lockedOutpoints []wire.OutPoint + fundedPacket *psbt.Packet = pkt + changeIndex int32 = -1 + success bool + ) + + if !req.SkipFunding { + unlockInputs := lockCommitInputs(req.CustomLockId) + defer unlockInputs() + + // The change output and fee parameters of this RPC are + // identical to the walletrpc.FundPsbt, so we just map them 1:1 + // and let lnd do the validation. + coinSelect := &walletrpc.PsbtCoinSelect{ + Psbt: packetBytes, + } + fundRequest := &walletrpc.FundPsbtRequest{ + Template: &walletrpc.FundPsbtRequest_CoinSelect{ + CoinSelect: coinSelect, + }, + MinConfs: 1, + ChangeType: P2TRChangeType, + CustomLockId: req.CustomLockId, + LockExpirationSeconds: req.LockExpirationSeconds, + } + + // Unfortunately we can't use the same RPC types, so we have to + // do a 1:1 mapping to the walletrpc types for the anchor change + // output and fee "oneof" fields. + switch change := req.AnchorChangeOutput.(type) { + case *wrpc.CommitVirtualPsbtsRequest_ExistingOutputIndex: + coinSelect.ChangeOutput = &coinSelectExistingIndex{ + ExistingOutputIndex: change.ExistingOutputIndex, + } + + case *wrpc.CommitVirtualPsbtsRequest_Add: + coinSelect.ChangeOutput = &walletrpc.PsbtCoinSelect_Add{ + Add: change.Add, + } + + default: + return nil, fmt.Errorf("unknown change output type") + } + + switch fee := req.Fees.(type) { + case *wrpc.CommitVirtualPsbtsRequest_TargetConf: + fundRequest.Fees = + &walletrpc.FundPsbtRequest_TargetConf{ + TargetConf: fee.TargetConf, + } + + case *wrpc.CommitVirtualPsbtsRequest_SatPerVbyte: + fundRequest.Fees = + &walletrpc.FundPsbtRequest_SatPerVbyte{ + SatPerVbyte: fee.SatPerVbyte, + } + + default: + return nil, fmt.Errorf("unknown fee type") + } + + lndWallet := r.cfg.Lnd.WalletKit + fundedPacket, changeIndex, lockedUTXO, err = lndWallet.FundPsbt( + ctx, fundRequest, + ) + if err != nil { + return nil, fmt.Errorf("error funding packet: %w", err) + } + + lockedOutpoints = fn.Map(lockedUTXO, + func(utxo *walletrpc.UtxoLease) wire.OutPoint { + var hash chainhash.Hash + copy(hash[:], utxo.Outpoint.TxidBytes) + return wire.OutPoint{ + Hash: hash, + Index: utxo.Outpoint.OutputIndex, + } + }, + ) + + // From now on, if we error out, we need to make sure we unlock + // the UTXOs that lnd just locked for us. + defer func() { + if success { + return + } + if hooks != nil && hooks.attemptReplaced { + hooks.retainPending = true + return + } + + releaseLeasedOutputs( + ctx, lndWallet, lockedUTXO, lockedOutpoints, + ) + }() + + if hooks != nil && hooks.onFunded != nil { + err = hooks.onFunded( + effectiveCommitLockID( + lockedUTXO, req.CustomLockId, + ), + outpointsFromWire(lockedOutpoints), + earliestUtxoLeaseExpiry(lockedUTXO), + ) + if err != nil { + return nil, fmt.Errorf("recording funded "+ + "leases: %w", err) + } + } + } + + if noNewAnchorChangeRequested(req) { + err := checkNoNewAnchorChange(pkt, fundedPacket, changeIndex) + if err != nil { + return nil, err + } + } + + // We can now update the anchor outputs as we have the final + // commitments. + outputCommitments, err := tapsend.CreateOutputCommitments( + allPackets, tapsend.WithSpenderLeaves(), + ) + if err != nil { + return nil, fmt.Errorf("unable to create new output "+ + "commitments: %w", err) + } + + for _, vPkt := range allPackets { + err = tapsend.UpdateTaprootOutputKeys( + fundedPacket, vPkt, outputCommitments, + ) + if err != nil { + return nil, fmt.Errorf("error updating taproot output "+ + "keys: %w", err) + } + } + + // We're done creating the output commitments, we can now create the + // transition proof suffixes. + for idx := range allPackets { + vPkt := allPackets[idx] + + for vOutIdx := range vPkt.Outputs { + proofSuffix, err := tapsend.CreateProofSuffix( + fundedPacket.UnsignedTx, fundedPacket.Outputs, + vPkt, outputCommitments, vOutIdx, allPackets, + proofOpts..., + ) + if err != nil { + return nil, fmt.Errorf("unable to create "+ + "proof suffix for output %d of vPSBT "+ + "%d: %w", vOutIdx, idx, err) + } + + vPkt.Outputs[vOutIdx].ProofSuffix = proofSuffix + } + } + + // We can now prepare the full answer, beginning with the serialized + // final packet. + response := &wrpc.CommitVirtualPsbtsResponse{ + ChangeOutputIndex: changeIndex, + } + + response.AnchorPsbt, err = fn.Serialize(fundedPacket) + if err != nil { + return nil, fmt.Errorf("error serializing packet: %w", err) + } + + // Serialize the final active and passive virtual packets. + response.VirtualPsbts, err = encodeVirtualPackets(activePackets) + if err != nil { + return nil, fmt.Errorf("error encoding active packets: %w", err) + } + response.PassiveAssetPsbts, err = encodeVirtualPackets(passivePackets) + if err != nil { + return nil, fmt.Errorf("error encoding passive packets: %w", + err) + } + + // And finally, we need to also return the locked UTXOs. We just return + // the outpoint, as any additional information can be fetched from the + // lnd wallet directly (we don't want to create pass-through RPCs for + // all those methods). + response.LndLockedUtxos = make([]*taprpc.OutPoint, len(lockedOutpoints)) + for idx := range lockedOutpoints { + response.LndLockedUtxos[idx] = &taprpc.OutPoint{ + Txid: lockedOutpoints[idx].Hash[:], + OutputIndex: lockedOutpoints[idx].Index, + } + } + + if hooks != nil && hooks.onResult != nil { + err = hooks.onResult(response) + if err != nil { + return nil, fmt.Errorf("recording commit result: %w", + err) + } + } + + // We were successful, let's cancel the UTXO release in the defer. + success = true + + return response, nil +} + +// validateInputAssets makes sure that the input assets are correct and their +// combined commitments match the inputs of the BTC level anchor transaction. diff --git a/rpcserver/commit_idempotency.go b/rpcserver/commit_idempotency.go new file mode 100644 index 0000000000..b9e45261e6 --- /dev/null +++ b/rpcserver/commit_idempotency.go @@ -0,0 +1,1791 @@ +package rpcserver + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/binary" + "errors" + "fmt" + "io" + "math" + "sync" + "time" + + "github.com/btcsuite/btcd/chaincfg/chainhash" + "github.com/btcsuite/btcd/wire" + "github.com/btcsuite/btcwallet/wtxmgr" + "github.com/lightninglabs/lndclient" + "github.com/lightninglabs/taproot-assets/tapconfig" + "github.com/lightninglabs/taproot-assets/tapdb" + "github.com/lightninglabs/taproot-assets/taprpc" + wrpc "github.com/lightninglabs/taproot-assets/taprpc/assetwalletrpc" + "github.com/lightningnetwork/lnd/lnrpc/walletrpc" + "github.com/lightningnetwork/lnd/lnwallet/chanfunding" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" +) + +const ( + // maxCommitRequestIDLen is the longest accepted request_id. It + // matches the primary key check on commit_virtual_psbt_idem. + maxCommitRequestIDLen = 64 + + // commitIdempotencyIOTimeout bounds store writes that must not + // follow the request context. A cancelled client still needs the + // outcome recorded or the claim released. + commitIdempotencyIOTimeout = 30 * time.Second + + // commitRecordVersion1 is the original record layout. It has no + // lease timestamps. Rows already stored in that layout still + // decode. + commitRecordVersion1 byte = 1 + + // commitRecordVersion is the layout that also stores when the + // pending row was created and when its lnd lease expires. + commitRecordVersion byte = 2 + + commitStatusPending uint8 = 1 + commitStatusCompleted uint8 = 2 + + // lndLockIDLen is the size of an lnd wallet lock ID. + lndLockIDLen = 32 + + maxCommitLockIDLen = 256 + maxCommitOutpoints = 4096 + maxCommitResponseLen = 32 << 20 + + // maxCommitLockSeconds is the largest lock duration that fits in + // a time.Duration. A larger request value would overflow and look + // like a lease that already expired. The UnixNano range is + // tighter than that and is applied when the deadline is + // computed. + maxCommitLockSeconds = uint64(math.MaxInt64 / int64(time.Second)) +) + +// maxUnixNanoTime is the latest instant time.Time.UnixNano can +// represent. A later deadline wraps to a past instant when stored. +var maxUnixNanoTime = time.Unix(0, math.MaxInt64).UTC() + +// minUnixNanoTime is the earliest instant time.Time.UnixNano can +// represent. +var minUnixNanoTime = time.Unix(0, math.MinInt64).UTC() + +var ( + // errLeasesUnavailable is returned when the daemon has no lnd + // wallet to ask which outputs are still leased. + errLeasesUnavailable = errors.New( + "wallet lease query is not configured", + ) + + // errCommitAttemptReplaced is returned when a retry has taken + // over the pending row this attempt was writing. + errCommitAttemptReplaced = errors.New( + "commit attempt was replaced", + ) +) + +// commitVirtualPsbtsHooks let the idempotency wrapper observe funding +// without owning the commit pipeline. The callbacks are optional. +type commitVirtualPsbtsHooks struct { + // onFunded is called after lnd returns leases and before later + // errors can drop those outpoints. expiry is the earliest + // absolute lease expiration, or the zero time when lnd did not + // report one. A non-nil error aborts the commit and releases + // the leases. + onFunded func(lockID []byte, utxos []*taprpc.OutPoint, + expiry time.Time) error + + // onResult is called with the finished response before lease + // cleanup is cancelled. A non-nil error aborts the commit and + // releases the leases. + onResult func(*wrpc.CommitVirtualPsbtsResponse) error + + // retainPending tells the caller not to delete the pending row + // when this attempt returns an error. It is set when releasing + // the lnd leases failed, so a later retry can see them. + retainPending bool + + // attemptReplaced is set when a newer attempt owns the row. + // Outpoints that attempt already recorded stay locked. onFunded + // releases every other outpoint this attempt acquired, under + // the same lock ID, before the funding defer sees this flag. + attemptReplaced bool +} + +// commitOnceFunc performs one CommitVirtualPsbts attempt. +type commitOnceFunc func(context.Context, *wrpc.CommitVirtualPsbtsRequest, + *commitVirtualPsbtsHooks) (*wrpc.CommitVirtualPsbtsResponse, error) + +// commitRecord is the persisted outcome of one request ID. +type commitRecord struct { + Status uint8 + RequestHash [32]byte + LockID []byte + Outpoints []*taprpc.OutPoint + Response []byte + + // CreatedAt is when this pending attempt claimed the key. + CreatedAt time.Time + + // LeaseExpiry is when the lnd leases for this attempt stop being + // held. Before funding returns it is the requested duration + // added to CreatedAt. After funding it is the earliest + // expiration lnd reported. + LeaseExpiry time.Time +} + +// CommitVirtualPsbts creates the output commitments and proofs for the given +// virtual transactions by committing them to the BTC level anchor transaction. +// In addition, the BTC level anchor transaction is funded and prepared up to +// the point where it is ready to be signed. +// +// When the request sets a request ID, a completed or failed outcome is +// returned as-is only inside the retention window. A repeat while that +// call is still running, or while lnd still leases its inputs, is +// rejected. After those leases expire, the pending row is deleted and +// the same request funds again. The same key with a different body is +// rejected. GetCommitVirtualPsbtsStatus reports an in-progress or +// completed call and the lnd leases it holds. +func (r *RPCServer) CommitVirtualPsbts(ctx context.Context, + req *wrpc.CommitVirtualPsbtsRequest) (*wrpc.CommitVirtualPsbtsResponse, + error) { + + return r.commitVirtualPsbts(ctx, req, r.fundAndCommitVirtualPsbts) +} + +// commitVirtualPsbts is CommitVirtualPsbts with the single-attempt work +// injected so tests can observe funding without a live lnd. +func (r *RPCServer) commitVirtualPsbts(ctx context.Context, + req *wrpc.CommitVirtualPsbtsRequest, once commitOnceFunc) ( + *wrpc.CommitVirtualPsbtsResponse, error) { + + if len(req.RequestId) == 0 { + return once(ctx, req, nil) + } + + if err := validateCommitRequestID(req.RequestId); err != nil { + return nil, err + } + + if _, err := r.commitStore(); err != nil { + return nil, err + } + + // Derive a stable lock ID before hashing so a retry that also + // leaves custom_lock_id empty matches this request. + ensureCommitLockID(req) + + hash, err := hashCommitRequest(req) + if err != nil { + return nil, err + } + + replay, claimed, attempt, err := r.claimCommit(ctx, req, hash) + if err != nil { + return nil, err + } + if !claimed { + return replay, nil + } + + hooks := r.commitHooks(req.RequestId, attempt) + finished := false + defer func() { + if finished || hooks.retainPending { + return + } + + r.abandonCommitRecord(req.RequestId, attempt) + }() + + // A cancelled caller must not fund. The defer releases the claim. + if err := ctx.Err(); err != nil { + return nil, err + } + + resp, err := once(ctx, req, hooks) + if err != nil { + return nil, err + } + + finished = true + + return resp, nil +} + +// GetCommitVirtualPsbtsStatus reports the recorded outcome of a +// CommitVirtualPsbts call. An unknown request ID is a successful response +// with status unknown. This call does not delete a pending row. A repeat +// of CommitVirtualPsbts deletes that row once its leases have expired +// and funds again. The outpoints in the response are the ones recorded +// for that commit. When funding has returned but the row lists no +// outpoints and lnd still holds the lock, those leases are recorded and +// returned. +func (r *RPCServer) GetCommitVirtualPsbtsStatus(ctx context.Context, + req *wrpc.GetCommitVirtualPsbtsStatusRequest) ( + *wrpc.GetCommitVirtualPsbtsStatusResponse, error) { + + if req == nil { + return nil, status.Error( + codes.InvalidArgument, "request is required", + ) + } + + if err := validateCommitRequestID(req.RequestId); err != nil { + return nil, err + } + + store, err := r.commitStore() + if err != nil { + return nil, err + } + + if err := r.purgeExpiredCommitRecords(); err != nil { + return nil, err + } + + raw, err := store.FetchCommitRecord(ctx, req.RequestId) + switch { + case errors.Is(err, tapdb.ErrNoCommitRecord): + return &wrpc.GetCommitVirtualPsbtsStatusResponse{ + Status: commitStatusUnknown, + }, nil + + case err != nil: + return nil, fmt.Errorf("fetch commit record: %w", err) + } + + rec, err := decodeCommitRecord(raw) + if err != nil { + return nil, status.Errorf( + codes.Internal, "stored commit record is invalid: %v", + err, + ) + } + + if rec.Status == commitStatusPending && len(rec.Outpoints) == 0 { + reconciled, err := r.backfillPendingLeases( + ctx, req.RequestId, rec, + ) + if err != nil { + rpcsLog.Errorf("Error reconciling commit leases "+ + "for %x: %v", req.RequestId, err) + } else if reconciled != nil { + rec = reconciled + } + } + + st, err := commitProtoStatus(rec.Status) + if err != nil { + return nil, status.Error(codes.Internal, err.Error()) + } + + return &wrpc.GetCommitVirtualPsbtsStatusResponse{ + Status: st, + LockId: rec.LockID, + LndLockedUtxos: rec.Outpoints, + }, nil +} + +// Proto status values. The generated names do not fit in 80 columns. +var ( + commitStatusUnknown = wrpc.CommitVirtualPsbtsStatus_COMMIT_VIRTUAL_PSBTS_STATUS_UNKNOWN //nolint:lll + + commitStatusPendingProto = wrpc.CommitVirtualPsbtsStatus_COMMIT_VIRTUAL_PSBTS_STATUS_PENDING //nolint:lll + + commitStatusCompletedProto = wrpc.CommitVirtualPsbtsStatus_COMMIT_VIRTUAL_PSBTS_STATUS_COMPLETED //nolint:lll +) + +func commitProtoStatus(recordStatus uint8) (wrpc.CommitVirtualPsbtsStatus, + error) { + + switch recordStatus { + case commitStatusPending: + return commitStatusPendingProto, nil + + case commitStatusCompleted: + return commitStatusCompletedProto, nil + + default: + return 0, fmt.Errorf( + "unknown commit record status %d", recordStatus, + ) + } +} + +func (r *RPCServer) commitHooks(requestID []byte, + attempt time.Time) *commitVirtualPsbtsHooks { + + hooks := &commitVirtualPsbtsHooks{} + hooks.onFunded = func(lockID []byte, utxos []*taprpc.OutPoint, + expiry time.Time) error { + + err := r.updateCommitRecord( + requestID, attempt, func(rec *commitRecord) error { + if len(lockID) > 0 { + rec.LockID = append( + []byte(nil), lockID..., + ) + } + rec.Outpoints = utxos + if !expiry.IsZero() { + rec.LeaseExpiry = clampUnixNanoTime( + expiry, + ) + } + + return nil + }, + ) + if errors.Is(err, errCommitAttemptReplaced) { + hooks.attemptReplaced = true + r.releaseReplacedAttemptOutputs( + requestID, lockID, utxos, + ) + } + + return err + } + hooks.onResult = func(resp *wrpc.CommitVirtualPsbtsResponse) error { + raw, err := proto.Marshal(resp) + if err != nil { + return fmt.Errorf( + "marshal commit response: %w", err, + ) + } + + err = r.updateCommitRecord( + requestID, attempt, func(rec *commitRecord) error { + rec.Status = commitStatusCompleted + rec.Response = raw + rec.Outpoints = resp.GetLndLockedUtxos() + + return nil + }, + ) + if errors.Is(err, errCommitAttemptReplaced) { + hooks.attemptReplaced = true + } + + return err + } + + return hooks +} + +func (r *RPCServer) claimCommit(ctx context.Context, + req *wrpc.CommitVirtualPsbtsRequest, hash [32]byte) ( + *wrpc.CommitVirtualPsbtsResponse, bool, time.Time, error) { + + // Drop outcomes that are past the retention window before this + // request is matched, so a replay outside the window funds again. + if err := r.purgeExpiredCommitRecords(); err != nil { + return nil, false, time.Time{}, err + } + + // Two passes cover a compare-and-swap that loses to another + // retry. A fresh insert that loses the unique-key race does not + // take over that winner. + for pass := 0; pass < 2; pass++ { + raw, err := r.cfg.CommitIdempotency.FetchCommitRecord( + ctx, req.RequestId, + ) + switch { + case errors.Is(err, tapdb.ErrNoCommitRecord): + return r.insertPendingCommit(ctx, req, hash) + + case err != nil: + return nil, false, time.Time{}, fmt.Errorf( + "fetch commit record: %w", err, + ) + } + + resp, claimed, attempt, again, err := r.claimExisting( + ctx, req, hash, raw, + ) + if err != nil || !again { + return resp, claimed, attempt, err + } + } + + return nil, false, time.Time{}, status.Error( + codes.Aborted, + "commit for this request_id is in progress or has "+ + "no recorded outcome; query "+ + "GetCommitVirtualPsbtsStatus", + ) +} + +// claimExisting handles a request ID that already has a row. again is +// set when the row changed under us and the caller should re-read it. +func (r *RPCServer) claimExisting(ctx context.Context, + req *wrpc.CommitVirtualPsbtsRequest, hash [32]byte, raw []byte) ( + *wrpc.CommitVirtualPsbtsResponse, bool, time.Time, bool, error) { + + rec, err := decodeCommitRecord(raw) + if err != nil { + return nil, false, time.Time{}, false, status.Errorf( + codes.Internal, "stored commit record is invalid: %v", + err, + ) + } + + if rec.RequestHash != hash { + return nil, false, time.Time{}, false, status.Error( + codes.InvalidArgument, + "request_id was already used with a different request", + ) + } + + switch rec.Status { + case commitStatusCompleted: + resp, err := completedCommitResponse(rec) + + return resp, false, time.Time{}, false, err + + case commitStatusPending: + // Handled below. + + default: + return nil, false, time.Time{}, false, status.Errorf( + codes.Internal, "unknown commit record status %d", + rec.Status, + ) + } + + state, err := r.inspectPending(ctx, req.RequestId, rec) + if err != nil { + return nil, false, time.Time{}, false, err + } + if !state.recoverable { + if len(rec.Outpoints) == 0 && len(state.live) > 0 { + if _, err := r.backfillPendingLeases( + ctx, req.RequestId, rec, + ); err != nil { + rpcsLog.Errorf("Error recording commit "+ + "leases for %x: %v", req.RequestId, + err) + } + } + + return nil, false, time.Time{}, false, pendingCommitAborted() + } + + err = r.cfg.CommitIdempotency.DeleteCommitRecordIf( + ctx, req.RequestId, raw, + ) + switch { + case err == nil: + resp, claimed, attempt, err := r.insertPendingCommit( + ctx, req, hash, + ) + + return resp, claimed, attempt, false, err + + case errors.Is(err, tapdb.ErrCommitRecordChanged), + errors.Is(err, tapdb.ErrNoCommitRecord): + + return nil, false, time.Time{}, true, nil + + default: + return nil, false, time.Time{}, false, fmt.Errorf( + "delete stale commit record: %w", err, + ) + } +} + +func (r *RPCServer) insertPendingCommit(ctx context.Context, + req *wrpc.CommitVirtualPsbtsRequest, hash [32]byte) ( + *wrpc.CommitVirtualPsbtsResponse, bool, time.Time, error) { + + now := time.Now() + rec := &commitRecord{ + Status: commitStatusPending, + RequestHash: hash, + LockID: append([]byte(nil), req.CustomLockId...), + CreatedAt: now, + LeaseExpiry: commitLeaseDeadline( + now, req.LockExpirationSeconds, + ), + } + encoded, err := encodeCommitRecord(rec) + if err != nil { + return nil, false, time.Time{}, err + } + + err = r.cfg.CommitIdempotency.InsertCommitRecord( + ctx, req.RequestId, encoded, + ) + if err == nil { + return nil, true, now, nil + } + + var unique *tapdb.ErrSqlUniqueConstraintViolation + if !errors.As(err, &unique) { + return nil, false, time.Time{}, fmt.Errorf( + "insert commit record: %w", err, + ) + } + + // The winner of the insert owns the key. Do not take that row + // over; the caller is told the commit is in progress unless the + // winner already finished. + raw, err := r.cfg.CommitIdempotency.FetchCommitRecord( + ctx, req.RequestId, + ) + if err != nil { + return nil, false, time.Time{}, fmt.Errorf( + "fetch commit record: %w", err, + ) + } + + resp, err := replayCommit(raw, hash) + + return resp, false, time.Time{}, err +} + +func replayCommit(raw []byte, hash [32]byte) ( + *wrpc.CommitVirtualPsbtsResponse, error) { + + rec, err := decodeCommitRecord(raw) + if err != nil { + return nil, status.Errorf( + codes.Internal, "stored commit record is invalid: %v", + err, + ) + } + + if rec.RequestHash != hash { + return nil, status.Error( + codes.InvalidArgument, + "request_id was already used with a different request", + ) + } + + switch rec.Status { + case commitStatusCompleted: + return completedCommitResponse(rec) + + case commitStatusPending: + return nil, pendingCommitAborted() + + default: + return nil, status.Errorf( + codes.Internal, "unknown commit record status %d", + rec.Status, + ) + } +} + +func completedCommitResponse(rec *commitRecord) ( + *wrpc.CommitVirtualPsbtsResponse, error) { + + if len(rec.Response) == 0 { + return nil, status.Error( + codes.Internal, "stored commit response is empty", + ) + } + + resp := &wrpc.CommitVirtualPsbtsResponse{} + err := proto.Unmarshal(rec.Response, resp) + if err != nil { + return nil, status.Errorf( + codes.Internal, + "stored commit response is invalid: %v", err, + ) + } + + return resp, nil +} + +func pendingCommitAborted() error { + return status.Error( + codes.Aborted, + "commit for this request_id is in progress or has "+ + "no recorded outcome; query "+ + "GetCommitVirtualPsbtsStatus", + ) +} + +func (r *RPCServer) updateCommitRecord(requestID []byte, attempt time.Time, + mutate func(*commitRecord) error) error { + + ctx, cancel := commitRecordContext() + defer cancel() + + raw, err := r.cfg.CommitIdempotency.FetchCommitRecord(ctx, requestID) + if err != nil { + return fmt.Errorf("fetch commit record: %w", err) + } + + rec, err := decodeCommitRecord(raw) + if err != nil { + return err + } + if !sameCommitAttempt(rec.CreatedAt, attempt) { + return errCommitAttemptReplaced + } + + if err := mutate(rec); err != nil { + return err + } + + encoded, err := encodeCommitRecord(rec) + if err != nil { + return err + } + + // Pending updates leave the finish time unset. Any other status + // is terminal (completed, or failed if one is stored) and starts + // the retention window. + var finishedAt *time.Time + if rec.Status != commitStatusPending { + stamped := r.commitClock() + finishedAt = &stamped + } + + err = r.cfg.CommitIdempotency.SwapCommitRecord( + ctx, requestID, raw, encoded, finishedAt, + ) + switch { + case err == nil: + return nil + + case errors.Is(err, tapdb.ErrCommitRecordChanged): + return errCommitAttemptReplaced + + default: + return fmt.Errorf("update commit record: %w", err) + } +} + +func (r *RPCServer) abandonCommitRecord(requestID []byte, + attempt time.Time) { + + ctx, cancel := commitRecordContext() + defer cancel() + + raw, err := r.cfg.CommitIdempotency.FetchCommitRecord(ctx, requestID) + switch { + case errors.Is(err, tapdb.ErrNoCommitRecord): + return + + case err != nil: + rpcsLog.Errorf("Error abandoning commit request %x: %v", + requestID, err) + + return + } + + rec, err := decodeCommitRecord(raw) + if err != nil { + rpcsLog.Errorf("Error abandoning commit request %x: %v", + requestID, err) + + return + } + if !sameCommitAttempt(rec.CreatedAt, attempt) { + return + } + + held, err := r.leasesRemain(ctx, rec) + if err != nil { + rpcsLog.Errorf("Error checking commit leases for %x: %v", + requestID, err) + + return + } + if held { + rpcsLog.Infof("Keeping commit request %x: lnd still "+ + "leases its outputs", requestID) + + return + } + + err = r.cfg.CommitIdempotency.DeleteCommitRecordIf( + ctx, requestID, raw, + ) + switch { + case err == nil, errors.Is(err, tapdb.ErrNoCommitRecord), + errors.Is(err, tapdb.ErrCommitRecordChanged): + + return + + default: + rpcsLog.Errorf("Error abandoning commit request %x: %v", + requestID, err) + } +} + +func (r *RPCServer) commitStore() (tapconfig.CommitIdempotencyStore, error) { + if r.cfg == nil || r.cfg.CommitIdempotency == nil { + return nil, status.Error( + codes.Internal, + "commit idempotency store is not configured", + ) + } + + return r.cfg.CommitIdempotency, nil +} + +func commitRecordContext() (context.Context, context.CancelFunc) { + return context.WithTimeout( + context.Background(), commitIdempotencyIOTimeout, + ) +} + +// commitClock is the clock used to stamp and expire commit outcomes. +func (r *RPCServer) commitClock() time.Time { + if r != nil && r.commitNow != nil { + return r.commitNow() + } + + return time.Now() +} + +// commitResponseRetention is how long a terminal commit outcome is +// kept. Zero or a missing config uses the 24h default. +func (r *RPCServer) commitResponseRetention() time.Duration { + if r == nil || r.cfg == nil || + r.cfg.CommitVirtualPsbtRetention <= 0 { + + return tapconfig.DefaultCommitVirtualPsbtRetention + } + + return r.cfg.CommitVirtualPsbtRetention +} + +// purgeExpiredCommitRecords deletes completed and failed commit +// records older than the retention window. Pending records are kept. +// A finished row whose recorded outpoints are still leased under its +// lock ID is kept until ListLeases no longer reports them, so a window +// shorter than the lease cannot drop the stored response while lnd +// holds the inputs. Once the lease is gone the next purge deletes the +// row. Rows written before finish times were stored are judged by the +// time the attempt was claimed, and a recent one is stamped so later +// purges do not read its response again. +func (r *RPCServer) purgeExpiredCommitRecords() error { + if r == nil || r.cfg == nil || r.cfg.CommitIdempotency == nil { + return nil + } + + ctx, cancel := commitRecordContext() + defer cancel() + + before := r.commitClock().Add(-r.commitResponseRetention()) + store := r.cfg.CommitIdempotency + + finished, err := store.ListFinishedCommitRecords(ctx, before) + if err != nil { + return fmt.Errorf("list finished commit records: %w", err) + } + + rows, err := store.ListUnstampedCommitRecords(ctx) + if err != nil { + return fmt.Errorf("list unstamped commit records: %w", err) + } + + type expiredCommit struct { + row tapdb.CommitRecordRow + rec *commitRecord + } + + expired := make([]expiredCommit, 0, len(finished)) + var deleted int64 + for _, row := range finished { + rec, decErr := decodeCommitRecord(row.Record) + if decErr != nil { + rpcsLog.Errorf("Error decoding commit record %x "+ + "during retention purge: %v", + row.RequestID, decErr) + + removed, delErr := deleteExpiredCommitRow( + ctx, store, row.RequestID, row.Record, + ) + if delErr != nil { + return delErr + } + if removed { + deleted++ + } + + continue + } + + expired = append(expired, expiredCommit{row: row, rec: rec}) + } + + for _, row := range rows { + rec, decErr := decodeCommitRecord(row.Record) + if decErr != nil { + rpcsLog.Errorf("Error decoding commit record %x "+ + "during retention purge: %v", + row.RequestID, decErr) + + continue + } + if rec.Status == commitStatusPending { + continue + } + + finishedAt := rec.CreatedAt + if !finishedAt.IsZero() && !finishedAt.Before(before) { + stamp := finishedAt.UTC() + err = store.SwapCommitRecord( + ctx, row.RequestID, row.Record, row.Record, + &stamp, + ) + if err != nil && + !errors.Is(err, tapdb.ErrNoCommitRecord) && + !errors.Is(err, tapdb.ErrCommitRecordChanged) { + + return fmt.Errorf( + "stamp commit record: %w", err, + ) + } + + continue + } + + expired = append(expired, expiredCommit{row: row, rec: rec}) + } + + var ( + leases []lndclient.LeaseDescriptor + leaseErr error + ) + if len(expired) > 0 { + leases, leaseErr = r.commitLeases(ctx) + if leaseErr != nil && + !errors.Is(leaseErr, errLeasesUnavailable) { + + rpcsLog.Errorf("Error listing wallet leases during "+ + "commit retention purge: %v", leaseErr) + } + } + + for _, item := range expired { + if r.finishedCommitStillLeased( + item.rec, leases, leaseErr, + ) { + + continue + } + + removed, delErr := deleteExpiredCommitRow( + ctx, store, item.row.RequestID, item.row.Record, + ) + if delErr != nil { + return delErr + } + if removed { + deleted++ + } + } + + if deleted > 0 { + rpcsLog.Infof("Purged %d expired commit records", deleted) + } + + return nil +} + +// deleteExpiredCommitRow removes one commit row when its bytes still +// match. A concurrent update or a missing row is not an error. removed +// is true only when this call deleted the row. +func deleteExpiredCommitRow(ctx context.Context, + store tapconfig.CommitIdempotencyStore, requestID, raw []byte) ( + bool, error) { + + err := store.DeleteCommitRecordIf(ctx, requestID, raw) + switch { + case err == nil: + return true, nil + + case errors.Is(err, tapdb.ErrNoCommitRecord), + errors.Is(err, tapdb.ErrCommitRecordChanged): + + return false, nil + + default: + return false, fmt.Errorf( + "delete expired commit record: %w", err, + ) + } +} + +// finishedCommitStillLeased reports whether this finished attempt's +// recorded outpoints are still leased under its lock ID. A daemon with +// no wallet keeps the time-based purge. A failed listing keeps the row +// only until the stored lease deadline, so a stuck wallet cannot +// retain finished rows without bound. +func (r *RPCServer) finishedCommitStillLeased(rec *commitRecord, + leases []lndclient.LeaseDescriptor, leaseErr error) bool { + + if rec == nil || len(rec.Outpoints) == 0 { + return false + } + if errors.Is(leaseErr, errLeasesUnavailable) { + return false + } + if leaseErr != nil { + if rec.LeaseExpiry.IsZero() { + return false + } + + return r.commitClock().Before(rec.LeaseExpiry) + } + + return outpointsStillLeased(rec, leases) +} + +// commitInputLock is the mutex for one lnd lock ID and the number of +// attempts that hold it or are waiting for it. The map drops the entry +// when that count hits zero. A request_id without custom_lock_id uses +// a fresh SHA-256 lock ID, so keeping every mutex would grow without +// bound. +type commitInputLock struct { + mu sync.Mutex + refs int +} + +// commitInputLocks keys a mutex by lnd lock ID. Funding and the +// release of a replaced attempt for that ID must not interleave. +// commitInputLockMu guards the map and each entry's refcount. It is +// not held while an entry mutex is locked, so unlock can take it +// after releasing the entry. +var ( + commitInputLockMu sync.Mutex + commitInputLocks = make(map[string]*commitInputLock) +) + +// lockCommitInputs serializes FundPsbt and onFunded for one lock ID +// with the release of outpoints a replaced attempt acquired under +// that same ID. The returned function unlocks. The caller holds the +// mutex from FundPsbt until that function runs, which is the end of +// the funded RPC. onFunded runs while the lock is held, so +// releaseReplacedAttemptOutputs must not lock again. +// +// A lock ID that is not 32 bytes does not take a mutex. Those calls +// do not share a caller-visible lock ID with a retry. +func lockCommitInputs(lockID []byte) func() { + if len(lockID) != lndLockIDLen { + return func() {} + } + + key := string(lockID) + + commitInputLockMu.Lock() + entry := commitInputLocks[key] + if entry == nil { + entry = &commitInputLock{} + commitInputLocks[key] = entry + } + entry.refs++ + commitInputLockMu.Unlock() + + entry.mu.Lock() + + return func() { + entry.mu.Unlock() + + commitInputLockMu.Lock() + entry.refs-- + if entry.refs == 0 && commitInputLocks[key] == entry { + delete(commitInputLocks, key) + } + commitInputLockMu.Unlock() + } +} + +func validateCommitRequestID(id []byte) error { + if len(id) == 0 { + return status.Error( + codes.InvalidArgument, "request_id is empty", + ) + } + if len(id) > maxCommitRequestIDLen { + return status.Errorf( + codes.InvalidArgument, + "request_id must be at most %d bytes", + maxCommitRequestIDLen, + ) + } + + return nil +} + +// ensureCommitLockID sets a stable lnd lock ID when the caller asked for +// idempotency but did not choose one. The ID is SHA-256(request_id). +func ensureCommitLockID(req *wrpc.CommitVirtualPsbtsRequest) { + if len(req.RequestId) == 0 || len(req.CustomLockId) > 0 { + return + } + + sum := sha256.Sum256(req.RequestId) + req.CustomLockId = append([]byte(nil), sum[:]...) +} + +func hashCommitRequest(req *wrpc.CommitVirtualPsbtsRequest) ([32]byte, error) { + raw, err := proto.Marshal(req) + if err != nil { + return [32]byte{}, fmt.Errorf("marshal commit request: %w", err) + } + + return sha256.Sum256(raw), nil +} + +func effectiveCommitLockID(leases []*walletrpc.UtxoLease, + fallback []byte) []byte { + + for _, lease := range leases { + if lease == nil || len(lease.Id) == 0 { + continue + } + + return append([]byte(nil), lease.Id...) + } + + return append([]byte(nil), fallback...) +} + +// releaseReplacedAttemptOutputs unlocks outpoints this attempt +// acquired after a retry took over the row. Outpoints the replacement +// has already recorded stay leased: ReleaseOutput is keyed by the +// shared lock ID plus the outpoint, so unlocking one of those would +// drop the replacement's lease. lockCommitInputs is held by the +// funding caller across FundPsbt and this release, so the replacement +// cannot be between its own FundPsbt and onFunded while we decide. +func (r *RPCServer) releaseReplacedAttemptOutputs(requestID, lockID []byte, + acquired []*taprpc.OutPoint) { + + ctx, cancel := commitRecordContext() + defer cancel() + + keep, err := r.replacementOutpoints(ctx, requestID) + if err != nil { + rpcsLog.Errorf("Error reading replacement commit %x: %v", + requestID, err) + + return + } + + for _, op := range acquired { + if op == nil || outpointRecorded(keep, op) { + continue + } + + wireOp, ok := commitOutpointWire(op) + if !ok { + continue + } + + err := r.releaseCommitOutput(ctx, lockID, wireOp) + if err != nil { + rpcsLog.Errorf("Error releasing replaced commit "+ + "output %v: %v", wireOp, err) + } + } +} + +// replacementOutpoints returns the outpoints on the row that now owns +// requestID. A missing row means nothing was transferred. +func (r *RPCServer) replacementOutpoints(ctx context.Context, + requestID []byte) ([]*taprpc.OutPoint, error) { + + if r.cfg == nil || r.cfg.CommitIdempotency == nil { + return nil, status.Error( + codes.Internal, + "commit idempotency store is not configured", + ) + } + + raw, err := r.cfg.CommitIdempotency.FetchCommitRecord(ctx, requestID) + if errors.Is(err, tapdb.ErrNoCommitRecord) { + return nil, nil + } + if err != nil { + return nil, err + } + + rec, err := decodeCommitRecord(raw) + if err != nil { + return nil, err + } + + return rec.Outpoints, nil +} + +func (r *RPCServer) releaseCommitOutput(ctx context.Context, lockID []byte, + op wire.OutPoint) error { + + if r.cfg == nil || r.cfg.Lnd == nil || r.cfg.Lnd.WalletKit == nil { + return errLeasesUnavailable + } + if len(lockID) != lndLockIDLen { + return fmt.Errorf("lock id is %d bytes", len(lockID)) + } + + var id wtxmgr.LockID + copy(id[:], lockID) + + return r.cfg.Lnd.WalletKit.ReleaseOutput(ctx, id, op) +} + +func outpointRecorded(recorded []*taprpc.OutPoint, op *taprpc.OutPoint) bool { + if op == nil { + return false + } + + for _, have := range recorded { + if have == nil { + continue + } + if have.OutputIndex == op.OutputIndex && + bytes.Equal(have.Txid, op.Txid) { + + return true + } + } + + return false +} + +func commitOutpointWire(op *taprpc.OutPoint) (wire.OutPoint, bool) { + if op == nil || len(op.Txid) != chainhash.HashSize { + return wire.OutPoint{}, false + } + + var hash chainhash.Hash + copy(hash[:], op.Txid) + + return wire.OutPoint{ + Hash: hash, + Index: op.OutputIndex, + }, true +} + +func outpointsFromWire(ops []wire.OutPoint) []*taprpc.OutPoint { + out := make([]*taprpc.OutPoint, len(ops)) + for i := range ops { + out[i] = &taprpc.OutPoint{ + Txid: append([]byte(nil), ops[i].Hash[:]...), + OutputIndex: ops[i].Index, + } + } + + return out +} + +func encodeCommitRecord(rec *commitRecord) ([]byte, error) { + if rec == nil { + return nil, fmt.Errorf("nil commit record") + } + if len(rec.LockID) > maxCommitLockIDLen { + return nil, fmt.Errorf( + "lock id longer than %d bytes", maxCommitLockIDLen, + ) + } + if len(rec.Outpoints) > maxCommitOutpoints { + return nil, fmt.Errorf("too many locked outpoints") + } + if len(rec.Response) > maxCommitResponseLen { + return nil, fmt.Errorf( + "commit response longer than %d bytes", + maxCommitResponseLen, + ) + } + + for _, op := range rec.Outpoints { + if op == nil || len(op.Txid) != chainhash.HashSize { + return nil, fmt.Errorf( + "locked outpoint txid must be %d bytes", + chainhash.HashSize, + ) + } + } + + var buf bytes.Buffer + buf.WriteByte(commitRecordVersion) + buf.WriteByte(rec.Status) + buf.Write(rec.RequestHash[:]) + + if err := binary.Write( + &buf, binary.BigEndian, uint16(len(rec.LockID)), + ); err != nil { + return nil, err + } + buf.Write(rec.LockID) + + if err := binary.Write( + &buf, binary.BigEndian, uint16(len(rec.Outpoints)), + ); err != nil { + return nil, err + } + for _, op := range rec.Outpoints { + buf.Write(op.Txid) + if err := binary.Write( + &buf, binary.BigEndian, op.OutputIndex, + ); err != nil { + return nil, err + } + } + + if err := binary.Write( + &buf, binary.BigEndian, uint32(len(rec.Response)), + ); err != nil { + return nil, err + } + buf.Write(rec.Response) + + createdNano, err := unixNano(rec.CreatedAt) + if err != nil { + return nil, fmt.Errorf("encode commit created time: %w", err) + } + expiryNano, err := unixNano(clampUnixNanoTime(rec.LeaseExpiry)) + if err != nil { + return nil, fmt.Errorf("encode commit lease expiry: %w", err) + } + if err := binary.Write( + &buf, binary.BigEndian, createdNano, + ); err != nil { + return nil, err + } + if err := binary.Write( + &buf, binary.BigEndian, expiryNano, + ); err != nil { + return nil, err + } + + return buf.Bytes(), nil +} + +func decodeCommitRecord(raw []byte) (*commitRecord, error) { + r := bytes.NewReader(raw) + + version, err := r.ReadByte() + if err != nil { + return nil, fmt.Errorf("read commit record version: %w", err) + } + if version != commitRecordVersion1 && version != commitRecordVersion { + return nil, fmt.Errorf( + "unsupported commit record version %d", version, + ) + } + + recStatus, err := r.ReadByte() + if err != nil { + return nil, fmt.Errorf("read commit record status: %w", err) + } + + var hash [32]byte + if _, err := io.ReadFull(r, hash[:]); err != nil { + return nil, fmt.Errorf("read commit request hash: %w", err) + } + + var lockLen uint16 + if err := binary.Read(r, binary.BigEndian, &lockLen); err != nil { + return nil, fmt.Errorf("read lock id length: %w", err) + } + if int(lockLen) > maxCommitLockIDLen { + return nil, fmt.Errorf( + "lock id longer than %d bytes", maxCommitLockIDLen, + ) + } + + lockID := make([]byte, lockLen) + if _, err := io.ReadFull(r, lockID); err != nil { + return nil, fmt.Errorf("read lock id: %w", err) + } + + var numOutpoints uint16 + if err := binary.Read( + r, binary.BigEndian, &numOutpoints, + ); err != nil { + return nil, fmt.Errorf("read outpoint count: %w", err) + } + if int(numOutpoints) > maxCommitOutpoints { + return nil, fmt.Errorf("too many locked outpoints") + } + + outpoints := make([]*taprpc.OutPoint, numOutpoints) + for i := range outpoints { + txid := make([]byte, chainhash.HashSize) + if _, err := io.ReadFull(r, txid); err != nil { + return nil, fmt.Errorf("read outpoint txid: %w", err) + } + + var index uint32 + if err := binary.Read( + r, binary.BigEndian, &index, + ); err != nil { + return nil, fmt.Errorf("read outpoint index: %w", err) + } + + outpoints[i] = &taprpc.OutPoint{ + Txid: txid, + OutputIndex: index, + } + } + + var respLen uint32 + if err := binary.Read(r, binary.BigEndian, &respLen); err != nil { + return nil, fmt.Errorf("read response length: %w", err) + } + if respLen > maxCommitResponseLen { + return nil, fmt.Errorf( + "commit response longer than %d bytes", + maxCommitResponseLen, + ) + } + + var response []byte + if respLen > 0 { + response = make([]byte, respLen) + if _, err := io.ReadFull(r, response); err != nil { + return nil, fmt.Errorf("read commit response: %w", err) + } + } + + var createdAt, leaseExpiry time.Time + if version == commitRecordVersion { + var createdNano, expiryNano int64 + if err := binary.Read( + r, binary.BigEndian, &createdNano, + ); err != nil { + return nil, fmt.Errorf("read commit created time: %w", + err) + } + if err := binary.Read( + r, binary.BigEndian, &expiryNano, + ); err != nil { + return nil, fmt.Errorf("read commit lease expiry: %w", + err) + } + var decErr error + createdAt, decErr = timeFromUnixNano(createdNano) + if decErr != nil { + return nil, fmt.Errorf( + "commit created time: %w", decErr, + ) + } + leaseExpiry, decErr = timeFromUnixNano(expiryNano) + if decErr != nil { + return nil, fmt.Errorf( + "commit lease expiry: %w", decErr, + ) + } + } + + return &commitRecord{ + Status: recStatus, + RequestHash: hash, + LockID: lockID, + Outpoints: outpoints, + Response: response, + CreatedAt: createdAt, + LeaseExpiry: leaseExpiry, + }, nil +} + +// pendingLeaseState is what lnd currently holds for one pending row. +type pendingLeaseState struct { + // recoverable is true when a retry of the same request may fund + // again. The recorded leases are gone, and a call that has not + // funded yet is old enough that it is no longer in flight. + recoverable bool + + // live are leases still held under the record's lock ID. + live []lndclient.LeaseDescriptor +} + +func (r *RPCServer) inspectPending(ctx context.Context, requestID []byte, + rec *commitRecord) (pendingLeaseState, error) { + + leases, err := r.commitLeases(ctx) + switch { + case errors.Is(err, errLeasesUnavailable): + return pendingLeaseState{}, nil + + case err != nil: + return pendingLeaseState{}, fmt.Errorf( + "list wallet leases: %w", err, + ) + } + + matched := leasesForLock(rec.LockID, leases) + if len(rec.Outpoints) > 0 { + if outpointsStillLeased(rec, leases) { + return pendingLeaseState{live: matched}, nil + } + + return pendingLeaseState{recoverable: true}, nil + } + + // No outpoints are stored yet, so a lock ID by itself does not + // say which request owns the leases. See unrecordedOwnedLeases. + owned, err := r.unrecordedOwnedLeases( + ctx, requestID, rec.LockID, matched, + ) + if err != nil { + return pendingLeaseState{}, err + } + if len(owned) > 0 { + return pendingLeaseState{live: owned}, nil + } + if rec.LeaseExpiry.IsZero() || time.Now().Before(rec.LeaseExpiry) { + return pendingLeaseState{}, nil + } + + return pendingLeaseState{recoverable: true}, nil +} + +// unrecordedOwnedLeases filters lock-ID leases down to ones this +// request can attribute to itself. The row has not stored outpoints +// yet, and a caller-chosen lock ID is not unique across request IDs. +// +// Another pending row with the same lock ID and no outpoints may +// still be inside FundPsbt. Every lease under that lock is then +// ambiguous, and this request adopts none of them. Outpoints already +// stored on any other row with the lock ID belong to that row and are +// excluded. Leases that remain are this request's, which is also the +// case when the lock ID was derived as SHA-256(request_id) and no +// other row uses it. +func (r *RPCServer) unrecordedOwnedLeases(ctx context.Context, + requestID, lockID []byte, matched []lndclient.LeaseDescriptor) ( + []lndclient.LeaseDescriptor, error) { + + if len(matched) == 0 || len(lockID) != lndLockIDLen { + return nil, nil + } + if r.cfg == nil || r.cfg.CommitIdempotency == nil { + return nil, status.Error( + codes.Internal, + "commit idempotency store is not configured", + ) + } + + rows, err := r.cfg.CommitIdempotency.ListCommitRecords(ctx) + if err != nil { + return nil, fmt.Errorf("list commit records: %w", err) + } + + var claimed []*taprpc.OutPoint + for _, row := range rows { + if bytes.Equal(row.RequestID, requestID) { + continue + } + + rec, err := decodeCommitRecord(row.Record) + if err != nil { + return nil, fmt.Errorf( + "decode commit record: %w", err, + ) + } + if !bytes.Equal(rec.LockID, lockID) { + continue + } + + // An in-flight neighbor has not published its outpoints. + // The leases under this lock cannot be split safely. + if rec.Status == commitStatusPending && + len(rec.Outpoints) == 0 { + + return nil, nil + } + + claimed = append(claimed, rec.Outpoints...) + } + + owned := make([]lndclient.LeaseDescriptor, 0, len(matched)) + for _, lease := range matched { + op := &taprpc.OutPoint{ + Txid: lease.Outpoint.Hash[:], + OutputIndex: lease.Outpoint.Index, + } + if outpointRecorded(claimed, op) { + continue + } + + owned = append(owned, lease) + } + + return owned, nil +} + +// leasesRemain reports whether this attempt's outputs are still leased. +// A missing wallet reports that they are not, so unit tests that do +// not configure lnd keep the previous delete-on-failure behaviour. A +// failed query after funding was recorded keeps the row. +func (r *RPCServer) leasesRemain(ctx context.Context, + rec *commitRecord) (bool, error) { + + leases, err := r.commitLeases(ctx) + switch { + case errors.Is(err, errLeasesUnavailable): + return false, nil + + case err != nil: + if len(rec.Outpoints) > 0 { + return true, nil + } + + return false, nil + } + + if len(rec.Outpoints) > 0 { + return outpointsStillLeased(rec, leases), nil + } + + return len(leasesForLock(rec.LockID, leases)) > 0, nil +} + +func (r *RPCServer) commitLeases(ctx context.Context) ( + []lndclient.LeaseDescriptor, error) { + + if r.cfg == nil || r.cfg.Lnd == nil || r.cfg.Lnd.WalletKit == nil { + return nil, errLeasesUnavailable + } + + return r.cfg.Lnd.WalletKit.ListLeases(ctx) +} + +// backfillPendingLeases stores outpoints discovered from lnd when +// funding returned but the pending row does not list them yet. Only +// leases unrecordedOwnedLeases can attribute to this request are +// written. Another request's leases under the same caller-chosen +// lock ID are left alone. +func (r *RPCServer) backfillPendingLeases(ctx context.Context, + requestID []byte, rec *commitRecord) (*commitRecord, error) { + + if rec == nil || len(rec.Outpoints) > 0 { + return rec, nil + } + + state, err := r.inspectPending(ctx, requestID, rec) + if err != nil || len(state.live) == 0 { + return rec, err + } + + err = r.updateCommitRecord( + requestID, rec.CreatedAt, func(cur *commitRecord) error { + if len(cur.Outpoints) > 0 { + return nil + } + + cur.Outpoints = outpointsFromLeases(state.live) + cur.LockID = append( + []byte(nil), state.live[0].LockID[:]..., + ) + if exp := earliestDescriptorExpiry( + state.live, + ); !exp.IsZero() { + cur.LeaseExpiry = clampUnixNanoTime(exp) + } + + return nil + }, + ) + if err != nil && !errors.Is(err, errCommitAttemptReplaced) { + return nil, err + } + + raw, err := r.cfg.CommitIdempotency.FetchCommitRecord(ctx, requestID) + if err != nil { + return nil, fmt.Errorf("fetch commit record: %w", err) + } + + return decodeCommitRecord(raw) +} + +func leasesForLock(lockID []byte, + leases []lndclient.LeaseDescriptor) []lndclient.LeaseDescriptor { + + if len(lockID) != lndLockIDLen { + return nil + } + + matched := make([]lndclient.LeaseDescriptor, 0, len(leases)) + for _, lease := range leases { + if bytes.Equal(lockID, lease.LockID[:]) { + matched = append(matched, lease) + } + } + + return matched +} + +func outpointsStillLeased(rec *commitRecord, + leases []lndclient.LeaseDescriptor) bool { + + matched := leasesForLock(rec.LockID, leases) + for _, op := range rec.Outpoints { + if op == nil { + continue + } + for _, lease := range matched { + if lease.Outpoint.Index == op.OutputIndex && + bytes.Equal(lease.Outpoint.Hash[:], op.Txid) { + + return true + } + } + } + + return false +} + +func outpointsFromLeases( + leases []lndclient.LeaseDescriptor) []*taprpc.OutPoint { + + out := make([]*taprpc.OutPoint, 0, len(leases)) + for _, lease := range leases { + out = append(out, &taprpc.OutPoint{ + Txid: append( + []byte(nil), lease.Outpoint.Hash[:]..., + ), + OutputIndex: lease.Outpoint.Index, + }) + } + + return out +} + +func earliestDescriptorExpiry( + leases []lndclient.LeaseDescriptor) time.Time { + + var earliest time.Time + for _, lease := range leases { + if lease.Expiration.IsZero() { + continue + } + if earliest.IsZero() || lease.Expiration.Before(earliest) { + earliest = lease.Expiration + } + } + + return earliest +} + +func earliestUtxoLeaseExpiry(leases []*walletrpc.UtxoLease) time.Time { + var earliest time.Time + for _, lease := range leases { + if lease == nil || lease.Expiration == 0 { + continue + } + + exp := timeFromUnixSeconds(lease.Expiration) + if earliest.IsZero() || exp.Before(earliest) { + earliest = exp + } + } + + return earliest +} + +func commitLockDuration(seconds uint64) time.Duration { + if seconds == 0 { + return chanfunding.DefaultLockDuration + } + if seconds > maxCommitLockSeconds { + seconds = maxCommitLockSeconds + } + + return time.Duration(seconds) * time.Second +} + +// commitLeaseDeadline is when a not-yet-funded attempt may be replaced. +// The duration is clamped so the stored UnixNano cannot wrap into the +// past and let recovery treat the attempt as already expired. +func commitLeaseDeadline(now time.Time, seconds uint64) time.Time { + if !now.Before(maxUnixNanoTime) { + return maxUnixNanoTime + } + + d := commitLockDuration(seconds) + if remain := maxUnixNanoTime.Sub(now); d > remain { + d = remain + } + + return now.Add(d) +} + +// clampUnixNanoTime saturates t at the UnixNano bounds. The zero time +// stays zero so a missing deadline is unchanged. +func clampUnixNanoTime(t time.Time) time.Time { + switch { + case t.IsZero(): + return t + + case t.After(maxUnixNanoTime): + return maxUnixNanoTime + + case t.Before(minUnixNanoTime): + return minUnixNanoTime + + default: + return t + } +} + +// timeFromUnixSeconds converts an lnd lease expiration. Values past the +// UnixNano range saturate at its end. A uint64 that does not fit in +// int64 must not be cast: that wrap is a time in the past. +func timeFromUnixSeconds(sec uint64) time.Time { + if sec == 0 { + return time.Time{} + } + + maxSec := uint64(maxUnixNanoTime.Unix()) + if sec > maxSec { + return maxUnixNanoTime + } + + return time.Unix(int64(sec), 0).UTC() +} + +func sameCommitAttempt(stored, attempt time.Time) bool { + return stored.Equal(attempt) +} + +// unixNano encodes t. It refuses a time UnixNano cannot represent, +// because that call wraps and decodes as a different instant. +func unixNano(t time.Time) (int64, error) { + if t.IsZero() { + return 0, nil + } + if t.Before(minUnixNanoTime) || t.After(maxUnixNanoTime) { + return 0, fmt.Errorf( + "time %s is outside the UnixNano range", t.UTC(), + ) + } + + n := t.UnixNano() + if !time.Unix(0, n).Equal(t) { + return 0, fmt.Errorf( + "time %s is outside the UnixNano range", t.UTC(), + ) + } + + return n, nil +} + +// timeFromUnixNano decodes a stored timestamp. A value that does not +// round-trip is rejected so it cannot be read as an earlier deadline. +func timeFromUnixNano(n int64) (time.Time, error) { + if n == 0 { + return time.Time{}, nil + } + + t := time.Unix(0, n) + if t.UnixNano() != n { + return time.Time{}, fmt.Errorf( + "commit timestamp %d is outside the UnixNano range", + n, + ) + } + + return t, nil +} diff --git a/rpcserver/commit_idempotency_test.go b/rpcserver/commit_idempotency_test.go new file mode 100644 index 0000000000..63dcf49807 --- /dev/null +++ b/rpcserver/commit_idempotency_test.go @@ -0,0 +1,1668 @@ +package rpcserver + +import ( + "bytes" + "context" + "crypto/sha256" + "errors" + "math" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/btcsuite/btcd/chaincfg/chainhash" + "github.com/btcsuite/btcd/wire" + "github.com/btcsuite/btcwallet/wtxmgr" + "github.com/lightninglabs/lndclient" + "github.com/lightninglabs/taproot-assets/address" + "github.com/lightninglabs/taproot-assets/tapconfig" + "github.com/lightninglabs/taproot-assets/tapdb" + "github.com/lightninglabs/taproot-assets/taprpc" + wrpc "github.com/lightninglabs/taproot-assets/taprpc/assetwalletrpc" + "github.com/lightningnetwork/lnd/lnrpc/walletrpc" + "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/protobuf/proto" +) + +var ( + testCustomLock = bytes.Repeat([]byte{0x11}, 32) + testLeaseLock = bytes.Repeat([]byte{0x22}, 32) + testLeaseTxid = bytes.Repeat([]byte{0x33}, 32) +) + +func testLeaseOutpoint() *taprpc.OutPoint { + return &taprpc.OutPoint{ + Txid: append([]byte(nil), testLeaseTxid...), + OutputIndex: 7, + } +} + +func cannedCommitResponse( + utxos []*taprpc.OutPoint) *wrpc.CommitVirtualPsbtsResponse { + + return &wrpc.CommitVirtualPsbtsResponse{ + AnchorPsbt: []byte("funded-anchor"), + VirtualPsbts: [][]byte{{0x0a}}, + ChangeOutputIndex: 3, + LndLockedUtxos: utxos, + } +} + +func commitIDRequest(id []byte) *wrpc.CommitVirtualPsbtsRequest { + return &wrpc.CommitVirtualPsbtsRequest{ + RequestId: append([]byte(nil), id...), + VirtualPsbts: [][]byte{{0x01}}, + AnchorPsbt: []byte("template"), + CustomLockId: append([]byte(nil), testCustomLock...), + } +} + +func newIdempotencyServer(store tapconfig.CommitIdempotencyStore) *RPCServer { + return &RPCServer{ + cfg: &tapconfig.Config{ + ChainParams: address.MainNetTap, + CommitIdempotency: store, + }, + } +} + +// leaseWallet is the subset of lnd's wallet the recovery path queries. +// ListLeases is the existing lease listing RPC. +type leaseWallet struct { + lndclient.WalletKitClient + + leases []lndclient.LeaseDescriptor + listErr error +} + +func (w *leaseWallet) ListLeases(context.Context) ( + []lndclient.LeaseDescriptor, error) { + + if w.listErr != nil { + return nil, w.listErr + } + + out := make([]lndclient.LeaseDescriptor, len(w.leases)) + copy(out, w.leases) + + return out, nil +} + +func newLeaseServer(store tapconfig.CommitIdempotencyStore, + wallet lndclient.WalletKitClient) *RPCServer { + + srv := newIdempotencyServer(store) + srv.cfg.Lnd = &lndclient.LndServices{WalletKit: wallet} + + return srv +} + +// releaseWallet records ReleaseOutput calls. ListLeases still comes +// from the embedded lease wallet. +type releaseWallet struct { + leaseWallet + + mu sync.Mutex + released []wire.OutPoint + lockIDs []wtxmgr.LockID +} + +func (w *releaseWallet) ReleaseOutput(_ context.Context, id wtxmgr.LockID, + op wire.OutPoint) error { + + w.mu.Lock() + defer w.mu.Unlock() + + w.released = append(w.released, op) + w.lockIDs = append(w.lockIDs, id) + + return nil +} + +func testLockID(raw []byte) wtxmgr.LockID { + var id wtxmgr.LockID + copy(id[:], raw) + + return id +} + +func describedLease(lock []byte, op *taprpc.OutPoint, + expiry time.Time) lndclient.LeaseDescriptor { + + var hash chainhash.Hash + copy(hash[:], op.Txid) + + return lndclient.LeaseDescriptor{ + LockID: testLockID(lock), + Outpoint: wire.OutPoint{ + Hash: hash, + Index: op.OutputIndex, + }, + Expiration: expiry, + } +} + +func insertPendingCommit(t *testing.T, store *memCommitStore, + req *wrpc.CommitVirtualPsbtsRequest, lock []byte, + utxos []*taprpc.OutPoint) { + + t.Helper() + + ensureCommitLockID(req) + hash, err := hashCommitRequest(req) + require.NoError(t, err) + + raw, err := encodeCommitRecord(&commitRecord{ + Status: commitStatusPending, + RequestHash: hash, + LockID: append([]byte(nil), lock...), + Outpoints: utxos, + }) + require.NoError(t, err) + require.NoError(t, store.InsertCommitRecord( + context.Background(), req.RequestId, raw, + )) +} + +// memCommitStore is an in-memory CommitIdempotencyStore. +type memCommitStore struct { + mu sync.Mutex + rows map[string][]byte + finished map[string]time.Time + inserts atomic.Int32 + deletes atomic.Int32 +} + +func newMemCommitStore() *memCommitStore { + return &memCommitStore{ + rows: make(map[string][]byte), + finished: make(map[string]time.Time), + } +} + +func (m *memCommitStore) InsertCommitRecord(_ context.Context, id, + record []byte) error { + + m.mu.Lock() + defer m.mu.Unlock() + + m.inserts.Add(1) + + key := string(id) + if _, ok := m.rows[key]; ok { + return &tapdb.ErrSqlUniqueConstraintViolation{} + } + + m.rows[key] = append([]byte(nil), record...) + + return nil +} + +func (m *memCommitStore) FetchCommitRecord(_ context.Context, + id []byte) ([]byte, error) { + + m.mu.Lock() + defer m.mu.Unlock() + + record, ok := m.rows[string(id)] + if !ok { + return nil, tapdb.ErrNoCommitRecord + } + + return append([]byte(nil), record...), nil +} + +func (m *memCommitStore) UpdateCommitRecord(_ context.Context, id, + record []byte) error { + + m.mu.Lock() + defer m.mu.Unlock() + + key := string(id) + if _, ok := m.rows[key]; !ok { + return tapdb.ErrNoCommitRecord + } + + m.rows[key] = append([]byte(nil), record...) + + return nil +} + +func (m *memCommitStore) DeleteCommitRecord(_ context.Context, + id []byte) error { + + m.mu.Lock() + defer m.mu.Unlock() + + m.deletes.Add(1) + delete(m.rows, string(id)) + delete(m.finished, string(id)) + + return nil +} + +func (m *memCommitStore) SwapCommitRecord(_ context.Context, id, expected, + next []byte, finishedAt *time.Time) error { + + m.mu.Lock() + defer m.mu.Unlock() + + key := string(id) + current, ok := m.rows[key] + if !ok { + return tapdb.ErrNoCommitRecord + } + if !bytes.Equal(current, expected) { + return tapdb.ErrCommitRecordChanged + } + + m.rows[key] = append([]byte(nil), next...) + if finishedAt != nil { + m.finished[key] = finishedAt.UTC() + } + + return nil +} + +func (m *memCommitStore) PurgeFinishedCommitRecords(_ context.Context, + before time.Time) (int64, error) { + + m.mu.Lock() + defer m.mu.Unlock() + + var deleted int64 + for id, at := range m.finished { + if !at.Before(before) { + continue + } + + delete(m.rows, id) + delete(m.finished, id) + m.deletes.Add(1) + deleted++ + } + + return deleted, nil +} + +func (m *memCommitStore) ListFinishedCommitRecords(_ context.Context, + before time.Time) ([]tapdb.CommitRecordRow, error) { + + m.mu.Lock() + defer m.mu.Unlock() + + rows := make([]tapdb.CommitRecordRow, 0) + for id, at := range m.finished { + if !at.Before(before) { + continue + } + + rows = append(rows, tapdb.CommitRecordRow{ + RequestID: append([]byte(nil), id...), + Record: append([]byte(nil), m.rows[id]...), + }) + } + + return rows, nil +} + +func (m *memCommitStore) ListUnstampedCommitRecords(context.Context) ( + []tapdb.CommitRecordRow, error) { + + m.mu.Lock() + defer m.mu.Unlock() + + rows := make([]tapdb.CommitRecordRow, 0, len(m.rows)) + for id, record := range m.rows { + if _, ok := m.finished[id]; ok { + continue + } + + rows = append(rows, tapdb.CommitRecordRow{ + RequestID: append([]byte(nil), id...), + Record: append([]byte(nil), record...), + }) + } + + return rows, nil +} + +func (m *memCommitStore) ListCommitRecords(context.Context) ( + []tapdb.CommitRecordRow, error) { + + m.mu.Lock() + defer m.mu.Unlock() + + rows := make([]tapdb.CommitRecordRow, 0, len(m.rows)) + for id, record := range m.rows { + rows = append(rows, tapdb.CommitRecordRow{ + RequestID: append([]byte(nil), id...), + Record: append([]byte(nil), record...), + }) + } + + return rows, nil +} + +func (m *memCommitStore) DeleteCommitRecordIf(_ context.Context, id, + expected []byte) error { + + m.mu.Lock() + defer m.mu.Unlock() + + current, ok := m.rows[string(id)] + if !ok { + return tapdb.ErrNoCommitRecord + } + if !bytes.Equal(current, expected) { + return tapdb.ErrCommitRecordChanged + } + + m.deletes.Add(1) + delete(m.rows, string(id)) + delete(m.finished, string(id)) + + return nil +} + +func successOnce(calls *atomic.Int32) commitOnceFunc { + utxos := []*taprpc.OutPoint{testLeaseOutpoint()} + + return func(_ context.Context, _ *wrpc.CommitVirtualPsbtsRequest, + hooks *commitVirtualPsbtsHooks) ( + *wrpc.CommitVirtualPsbtsResponse, error) { + + calls.Add(1) + + resp := cannedCommitResponse(utxos) + if hooks == nil { + return resp, nil + } + + err := hooks.onFunded( + append([]byte(nil), testLeaseLock...), utxos, + time.Time{}, + ) + if err != nil { + return nil, err + } + + err = hooks.onResult(resp) + if err != nil { + return nil, err + } + + return resp, nil + } +} + +// TestCommitVirtualPsbtsReplaySkipsSecondCommit tests that a repeated +// request ID returns the stored response and does not run the commit +// again. +func TestCommitVirtualPsbtsReplaySkipsSecondCommit(t *testing.T) { + t.Parallel() + + store := newMemCommitStore() + srv := newIdempotencyServer(store) + req := commitIDRequest([]byte("req-1")) + + var calls atomic.Int32 + once := successOnce(&calls) + + ctx := context.Background() + first, err := srv.commitVirtualPsbts(ctx, req, once) + require.NoError(t, err) + + second, err := srv.commitVirtualPsbts(ctx, req, once) + require.NoError(t, err) + require.EqualValues(t, 1, calls.Load()) + require.True(t, proto.Equal(first, second)) + + other := commitIDRequest([]byte("req-2")) + _, err = srv.commitVirtualPsbts(ctx, other, once) + require.NoError(t, err) + require.EqualValues(t, 2, calls.Load()) + + statusResp, err := srv.GetCommitVirtualPsbtsStatus( + ctx, &wrpc.GetCommitVirtualPsbtsStatusRequest{ + RequestId: req.RequestId, + }, + ) + require.NoError(t, err) + require.Equal(t, commitStatusCompletedProto, statusResp.Status) + require.Equal(t, testLeaseLock, statusResp.LockId) + require.True(t, proto.Equal( + testLeaseOutpoint(), statusResp.LndLockedUtxos[0], + )) +} + +// TestCommitVirtualPsbtsEmptyRequestIDIsNotStored tests that omitting the +// request ID keeps the historical stateless behaviour. +func TestCommitVirtualPsbtsEmptyRequestIDIsNotStored(t *testing.T) { + t.Parallel() + + store := newMemCommitStore() + srv := newIdempotencyServer(store) + req := commitIDRequest(nil) + req.CustomLockId = nil + + var calls atomic.Int32 + var sawHooks atomic.Bool + once := func(_ context.Context, got *wrpc.CommitVirtualPsbtsRequest, + hooks *commitVirtualPsbtsHooks) ( + *wrpc.CommitVirtualPsbtsResponse, error) { + + calls.Add(1) + if hooks != nil { + sawHooks.Store(true) + } + require.Empty(t, got.CustomLockId) + + return cannedCommitResponse(nil), nil + } + + ctx := context.Background() + _, err := srv.commitVirtualPsbts(ctx, req, once) + require.NoError(t, err) + _, err = srv.commitVirtualPsbts(ctx, req, once) + require.NoError(t, err) + + require.EqualValues(t, 2, calls.Load()) + require.False(t, sawHooks.Load()) + require.EqualValues(t, 0, store.inserts.Load()) +} + +// TestCommitVirtualPsbtsRequestMismatch tests that reusing a request ID +// with a different body does not fund and does not replace the stored +// result. +func TestCommitVirtualPsbtsRequestMismatch(t *testing.T) { + t.Parallel() + + store := newMemCommitStore() + srv := newIdempotencyServer(store) + req := commitIDRequest([]byte("req")) + + var calls atomic.Int32 + once := successOnce(&calls) + ctx := context.Background() + + first, err := srv.commitVirtualPsbts(ctx, req, once) + require.NoError(t, err) + + mismatch := commitIDRequest(req.RequestId) + mismatch.AnchorPsbt = []byte("other-template") + _, err = srv.commitVirtualPsbts(ctx, mismatch, once) + assertCode(t, err, codes.InvalidArgument) + require.EqualValues(t, 1, calls.Load()) + + again, err := srv.commitVirtualPsbts(ctx, req, once) + require.NoError(t, err) + require.True(t, proto.Equal(first, again)) + require.EqualValues(t, 1, calls.Load()) +} + +// TestCommitVirtualPsbtsPendingDoesNotFund tests that a request ID left +// pending (the process died after funding, or the call is in progress) +// is not funded again. The status RPC returns the recorded leases. +func TestCommitVirtualPsbtsPendingDoesNotFund(t *testing.T) { + t.Parallel() + + store := newMemCommitStore() + srv := newIdempotencyServer(store) + req := commitIDRequest([]byte("pending")) + ensureCommitLockID(req) + + hash, err := hashCommitRequest(req) + require.NoError(t, err) + + utxo := testLeaseOutpoint() + raw, err := encodeCommitRecord(&commitRecord{ + Status: commitStatusPending, + RequestHash: hash, + LockID: append([]byte(nil), testLeaseLock...), + Outpoints: []*taprpc.OutPoint{utxo}, + }) + require.NoError(t, err) + require.NoError(t, store.InsertCommitRecord( + context.Background(), req.RequestId, raw, + )) + + var calls atomic.Int32 + _, err = srv.commitVirtualPsbts( + context.Background(), req, successOnce(&calls), + ) + assertCode(t, err, codes.Aborted) + require.EqualValues(t, 0, calls.Load()) + + statusResp, err := srv.GetCommitVirtualPsbtsStatus( + context.Background(), + &wrpc.GetCommitVirtualPsbtsStatusRequest{ + RequestId: req.RequestId, + }, + ) + require.NoError(t, err) + require.Equal(t, commitStatusPendingProto, statusResp.Status) + require.Equal(t, testLeaseLock, statusResp.LockId) + require.True(t, proto.Equal(utxo, statusResp.LndLockedUtxos[0])) +} + +// TestCommitVirtualPsbtsFailureAfterFundingRetries tests that a failed +// attempt releases the request ID, so a later call funds again instead +// of sticking on the pending row. +func TestCommitVirtualPsbtsFailureAfterFundingRetries(t *testing.T) { + t.Parallel() + + store := newMemCommitStore() + srv := newIdempotencyServer(store) + req := commitIDRequest([]byte("retry")) + + var calls atomic.Int32 + utxos := []*taprpc.OutPoint{testLeaseOutpoint()} + once := func(_ context.Context, _ *wrpc.CommitVirtualPsbtsRequest, + hooks *commitVirtualPsbtsHooks) ( + *wrpc.CommitVirtualPsbtsResponse, error) { + + n := calls.Add(1) + require.NotNil(t, hooks) + err := hooks.onFunded( + append([]byte(nil), testLeaseLock...), utxos, + time.Time{}, + ) + require.NoError(t, err) + + if n == 1 { + return nil, context.DeadlineExceeded + } + + resp := cannedCommitResponse(utxos) + require.NoError(t, hooks.onResult(resp)) + + return resp, nil + } + + ctx := context.Background() + _, err := srv.commitVirtualPsbts(ctx, req, once) + require.ErrorIs(t, err, context.DeadlineExceeded) + + statusResp, err := srv.GetCommitVirtualPsbtsStatus( + ctx, &wrpc.GetCommitVirtualPsbtsStatusRequest{ + RequestId: req.RequestId, + }, + ) + require.NoError(t, err) + require.Equal(t, commitStatusUnknown, statusResp.Status) + require.EqualValues(t, 1, store.deletes.Load()) + + resp, err := srv.commitVirtualPsbts(ctx, req, once) + require.NoError(t, err) + require.EqualValues(t, 2, calls.Load()) + require.True(t, proto.Equal(cannedCommitResponse(utxos), resp)) +} + +// TestCommitVirtualPsbtsStatusDuringCommit tests the pending record +// before funding, the leased outpoints after funding, and the derived +// lock ID used when the caller does not set one. +func TestCommitVirtualPsbtsStatusDuringCommit(t *testing.T) { + t.Parallel() + + store := newMemCommitStore() + srv := newIdempotencyServer(store) + req := commitIDRequest([]byte("derive-me")) + req.CustomLockId = nil + + var calls atomic.Int32 + utxos := []*taprpc.OutPoint{testLeaseOutpoint()} + once := func(_ context.Context, got *wrpc.CommitVirtualPsbtsRequest, + hooks *commitVirtualPsbtsHooks) ( + *wrpc.CommitVirtualPsbtsResponse, error) { + + calls.Add(1) + + sum := sha256.Sum256(req.RequestId) + require.Equal(t, sum[:], got.CustomLockId) + + statusResp, err := srv.GetCommitVirtualPsbtsStatus( + context.Background(), + &wrpc.GetCommitVirtualPsbtsStatusRequest{ + RequestId: req.RequestId, + }, + ) + require.NoError(t, err) + require.Equal(t, commitStatusPendingProto, statusResp.Status) + require.Equal(t, sum[:], statusResp.LockId) + require.Empty(t, statusResp.LndLockedUtxos) + + err = hooks.onFunded( + append([]byte(nil), testLeaseLock...), utxos, + time.Time{}, + ) + require.NoError(t, err) + + statusResp, err = srv.GetCommitVirtualPsbtsStatus( + context.Background(), + &wrpc.GetCommitVirtualPsbtsStatusRequest{ + RequestId: req.RequestId, + }, + ) + require.NoError(t, err) + require.Equal(t, commitStatusPendingProto, statusResp.Status) + require.Equal(t, testLeaseLock, statusResp.LockId) + require.True(t, proto.Equal( + utxos[0], statusResp.LndLockedUtxos[0], + )) + + resp := cannedCommitResponse(utxos) + require.NoError(t, hooks.onResult(resp)) + + return resp, nil + } + + ctx := context.Background() + unknown, err := srv.GetCommitVirtualPsbtsStatus( + ctx, &wrpc.GetCommitVirtualPsbtsStatusRequest{ + RequestId: req.RequestId, + }, + ) + require.NoError(t, err) + require.Equal(t, commitStatusUnknown, unknown.Status) + + resp, err := srv.commitVirtualPsbts(ctx, req, once) + require.NoError(t, err) + require.EqualValues(t, 1, calls.Load()) + + again, err := srv.commitVirtualPsbts(ctx, req, once) + require.NoError(t, err) + require.EqualValues(t, 1, calls.Load()) + require.True(t, proto.Equal(resp, again)) +} + +// TestCommitVirtualPsbtsConcurrentRequestIDFundsOnce tests that two +// overlapping calls with the same request ID fund once. +func TestCommitVirtualPsbtsConcurrentRequestIDFundsOnce(t *testing.T) { + t.Parallel() + + store := newMemCommitStore() + srv := newIdempotencyServer(store) + req := commitIDRequest([]byte("race")) + + var calls atomic.Int32 + started := make(chan struct{}) + release := make(chan struct{}) + var onceStart sync.Once + + once := func(ctx context.Context, got *wrpc.CommitVirtualPsbtsRequest, + hooks *commitVirtualPsbtsHooks) ( + *wrpc.CommitVirtualPsbtsResponse, error) { + + calls.Add(1) + onceStart.Do(func() { close(started) }) + <-release + + return successOnce(&atomic.Int32{})(ctx, got, hooks) + } + + errCh := make(chan error, 2) + var wg sync.WaitGroup + wg.Add(2) + for i := 0; i < 2; i++ { + go func() { + defer wg.Done() + + raw := proto.Clone(req) + cloned, ok := raw.(*wrpc.CommitVirtualPsbtsRequest) + require.True(t, ok) + + _, err := srv.commitVirtualPsbts( + context.Background(), cloned, once, + ) + errCh <- err + }() + } + + select { + case <-started: + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for the first commit") + } + + select { + case err := <-errCh: + require.Error(t, err) + assertCode(t, err, codes.Aborted) + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for the duplicate commit") + } + + close(release) + wg.Wait() + + require.NoError(t, <-errCh) + require.EqualValues(t, 1, calls.Load()) +} + +// TestCommitVirtualPsbtsRequestIDValidation tests rejection of an empty +// status key, an overlong request ID, and a missing store. +func TestCommitVirtualPsbtsRequestIDValidation(t *testing.T) { + t.Parallel() + + store := newMemCommitStore() + srv := newIdempotencyServer(store) + ctx := context.Background() + + _, err := srv.GetCommitVirtualPsbtsStatus( + ctx, &wrpc.GetCommitVirtualPsbtsStatusRequest{}, + ) + assertCode(t, err, codes.InvalidArgument) + + _, err = srv.GetCommitVirtualPsbtsStatus(ctx, nil) + assertCode(t, err, codes.InvalidArgument) + + var calls atomic.Int32 + longID := bytes.Repeat([]byte{0x01}, maxCommitRequestIDLen+1) + req := commitIDRequest(longID) + _, err = srv.commitVirtualPsbts(ctx, req, successOnce(&calls)) + assertCode(t, err, codes.InvalidArgument) + require.EqualValues(t, 0, calls.Load()) + + unconfigured := &RPCServer{cfg: &tapconfig.Config{}} + _, err = unconfigured.commitVirtualPsbts( + ctx, commitIDRequest([]byte("x")), successOnce(&calls), + ) + assertCode(t, err, codes.Internal) + require.EqualValues(t, 0, calls.Load()) +} + +// TestCommitVirtualPsbtsFailureReleasesRequestID tests that a real +// CommitVirtualPsbts failure claims the request ID and then drops it, +// so the key is not stuck pending. +func TestCommitVirtualPsbtsFailureReleasesRequestID(t *testing.T) { + t.Parallel() + + store := newMemCommitStore() + srv := newIdempotencyServer(store) + req := &wrpc.CommitVirtualPsbtsRequest{ + RequestId: []byte("bad-proof"), + VirtualPsbts: [][]byte{ + {0x01}, + }, + TransitionProofVersion: wrpc.TransitionProofVersion(2), + } + + _, err := srv.CommitVirtualPsbts(context.Background(), req) + assertCode(t, err, codes.InvalidArgument) + require.EqualValues(t, 1, store.inserts.Load()) + require.EqualValues(t, 1, store.deletes.Load()) + + statusResp, err := srv.GetCommitVirtualPsbtsStatus( + context.Background(), + &wrpc.GetCommitVirtualPsbtsStatusRequest{ + RequestId: req.RequestId, + }, + ) + require.NoError(t, err) + require.Equal(t, commitStatusUnknown, statusResp.Status) +} + +// TestCommitVirtualPsbtsIdempotentSurvivesNewStore tests that a completed +// request ID is replayed from the database by a new store instance. +func TestCommitVirtualPsbtsIdempotentSurvivesNewStore(t *testing.T) { + t.Parallel() + + db := tapdb.NewTestDB(t) + srv := newIdempotencyServer(tapdb.NewCommitVirtualPsbtStoreFromDB(db)) + req := commitIDRequest([]byte("durable")) + + var calls atomic.Int32 + once := successOnce(&calls) + ctx := context.Background() + + first, err := srv.commitVirtualPsbts(ctx, req, once) + require.NoError(t, err) + + restarted := newIdempotencyServer( + tapdb.NewCommitVirtualPsbtStoreFromDB(db), + ) + second, err := restarted.commitVirtualPsbts(ctx, req, once) + require.NoError(t, err) + require.EqualValues(t, 1, calls.Load()) + require.True(t, proto.Equal(first, second)) + + statusResp, err := restarted.GetCommitVirtualPsbtsStatus( + ctx, &wrpc.GetCommitVirtualPsbtsStatusRequest{ + RequestId: req.RequestId, + }, + ) + require.NoError(t, err) + require.Equal(t, commitStatusCompletedProto, statusResp.Status) + require.Equal(t, testLeaseLock, statusResp.LockId) +} + +// TestCommitVirtualPsbtsStalePendingFundsAgain tests a crash after +// onFunded succeeds and before onResult stores the PSBT. onFunded has +// already written the leased outpoints onto the pending row, and the +// funded packet existed only in memory. Once lnd no longer leases +// those outpoints, a repeat of CommitVirtualPsbts takes the request +// over and funds again. It does not stay Aborted, and the request ID +// is not stranded for good. +func TestCommitVirtualPsbtsStalePendingFundsAgain(t *testing.T) { + t.Parallel() + + store := newMemCommitStore() + utxo := testLeaseOutpoint() + wallet := &leaseWallet{} + srv := newLeaseServer(store, wallet) + req := commitIDRequest([]byte("stale-funded")) + insertPendingCommit( + t, store, req, testLeaseLock, []*taprpc.OutPoint{utxo}, + ) + + ctx := context.Background() + statusResp, err := srv.GetCommitVirtualPsbtsStatus( + ctx, &wrpc.GetCommitVirtualPsbtsStatusRequest{ + RequestId: req.RequestId, + }, + ) + require.NoError(t, err) + require.Equal(t, commitStatusPendingProto, statusResp.Status) + require.Equal(t, testLeaseLock, statusResp.LockId) + require.True(t, proto.Equal(utxo, statusResp.LndLockedUtxos[0])) + + var calls atomic.Int32 + resp, err := srv.commitVirtualPsbts( + ctx, req, successOnce(&calls), + ) + require.NoError(t, err) + require.EqualValues(t, 1, calls.Load()) + require.True(t, proto.Equal(cannedCommitResponse( + []*taprpc.OutPoint{utxo}, + ), resp)) + + mismatch := commitIDRequest(req.RequestId) + mismatch.AnchorPsbt = []byte("other-template") + _, err = srv.commitVirtualPsbts(ctx, mismatch, successOnce(&calls)) + assertCode(t, err, codes.InvalidArgument) + require.EqualValues(t, 1, calls.Load()) +} + +// TestCommitVirtualPsbtsPendingLeaseStillHeld tests that a pending row +// whose outpoints are still leased is not funded again. +func TestCommitVirtualPsbtsPendingLeaseStillHeld(t *testing.T) { + t.Parallel() + + store := newMemCommitStore() + utxo := testLeaseOutpoint() + wallet := &leaseWallet{ + leases: []lndclient.LeaseDescriptor{ + describedLease( + testLeaseLock, utxo, time.Now().Add(time.Hour), + ), + }, + } + srv := newLeaseServer(store, wallet) + req := commitIDRequest([]byte("still-leased")) + insertPendingCommit( + t, store, req, testLeaseLock, []*taprpc.OutPoint{utxo}, + ) + + var calls atomic.Int32 + _, err := srv.commitVirtualPsbts( + context.Background(), req, successOnce(&calls), + ) + assertCode(t, err, codes.Aborted) + require.EqualValues(t, 0, calls.Load()) +} + +// TestCommitVirtualPsbtsFailedReleaseKeepsPending tests that a failed +// attempt whose leases are still held does not delete the request ID. +func TestCommitVirtualPsbtsFailedReleaseKeepsPending(t *testing.T) { + t.Parallel() + + store := newMemCommitStore() + utxo := testLeaseOutpoint() + wallet := &leaseWallet{ + leases: []lndclient.LeaseDescriptor{ + describedLease( + testLeaseLock, utxo, time.Now().Add(time.Hour), + ), + }, + } + srv := newLeaseServer(store, wallet) + req := commitIDRequest([]byte("release-failed")) + + var calls atomic.Int32 + once := func(_ context.Context, _ *wrpc.CommitVirtualPsbtsRequest, + hooks *commitVirtualPsbtsHooks) ( + *wrpc.CommitVirtualPsbtsResponse, error) { + + calls.Add(1) + err := hooks.onFunded( + append([]byte(nil), testLeaseLock...), + []*taprpc.OutPoint{utxo}, time.Time{}, + ) + require.NoError(t, err) + + return nil, errors.New("release would fail") + } + + ctx := context.Background() + _, err := srv.commitVirtualPsbts(ctx, req, once) + require.Error(t, err) + require.EqualValues(t, 1, calls.Load()) + require.EqualValues(t, 0, store.deletes.Load()) + + statusResp, err := srv.GetCommitVirtualPsbtsStatus( + ctx, &wrpc.GetCommitVirtualPsbtsStatusRequest{ + RequestId: req.RequestId, + }, + ) + require.NoError(t, err) + require.Equal(t, commitStatusPendingProto, statusResp.Status) + require.Equal(t, testLeaseLock, statusResp.LockId) + require.True(t, proto.Equal(utxo, statusResp.LndLockedUtxos[0])) + + _, err = srv.commitVirtualPsbts(ctx, req, once) + assertCode(t, err, codes.Aborted) + require.EqualValues(t, 1, calls.Load()) +} + +// TestCommitVirtualPsbtsUnrecordedLeaseBackfill tests that a crash +// after FundPsbt returns and before the pending row stores outpoints +// still reports those leases, and does not fund while they are held. +func TestCommitVirtualPsbtsUnrecordedLeaseBackfill(t *testing.T) { + t.Parallel() + + store := newMemCommitStore() + utxo := testLeaseOutpoint() + wallet := &leaseWallet{ + leases: []lndclient.LeaseDescriptor{ + describedLease( + testCustomLock, utxo, + time.Now().Add(time.Hour), + ), + }, + } + srv := newLeaseServer(store, wallet) + req := commitIDRequest([]byte("gap-funded")) + insertPendingCommit(t, store, req, testCustomLock, nil) + + ctx := context.Background() + statusResp, err := srv.GetCommitVirtualPsbtsStatus( + ctx, &wrpc.GetCommitVirtualPsbtsStatusRequest{ + RequestId: req.RequestId, + }, + ) + require.NoError(t, err) + require.Equal(t, commitStatusPendingProto, statusResp.Status) + require.Equal(t, testCustomLock, statusResp.LockId) + require.Len(t, statusResp.LndLockedUtxos, 1) + require.True(t, proto.Equal(utxo, statusResp.LndLockedUtxos[0])) + + var calls atomic.Int32 + _, err = srv.commitVirtualPsbts(ctx, req, successOnce(&calls)) + assertCode(t, err, codes.Aborted) + require.EqualValues(t, 0, calls.Load()) +} + +// TestCommitVirtualPsbtsFailedReleaseBeforeOnFunded tests that a +// funding error before outpoints are stored still keeps the request +// ID when lnd holds the lock ID. +func TestCommitVirtualPsbtsFailedReleaseBeforeOnFunded(t *testing.T) { + t.Parallel() + + store := newMemCommitStore() + utxo := testLeaseOutpoint() + wallet := &leaseWallet{ + leases: []lndclient.LeaseDescriptor{ + describedLease( + testCustomLock, utxo, time.Now().Add(time.Hour), + ), + }, + } + srv := newLeaseServer(store, wallet) + req := commitIDRequest([]byte("release-before-record")) + + var calls atomic.Int32 + once := func(_ context.Context, _ *wrpc.CommitVirtualPsbtsRequest, + _ *commitVirtualPsbtsHooks) ( + *wrpc.CommitVirtualPsbtsResponse, error) { + + calls.Add(1) + + return nil, errors.New("funding cleanup failed") + } + + ctx := context.Background() + _, err := srv.commitVirtualPsbts(ctx, req, once) + require.Error(t, err) + require.EqualValues(t, 0, store.deletes.Load()) + + _, err = srv.commitVirtualPsbts(ctx, req, once) + assertCode(t, err, codes.Aborted) + require.EqualValues(t, 1, calls.Load()) +} + +// TestCommitVirtualPsbtsLeaseQueryErrorKeepsFundedPending tests that a +// failed attempt which already recorded outpoints is not dropped when +// the lease query itself fails. +func TestCommitVirtualPsbtsLeaseQueryErrorKeepsFundedPending(t *testing.T) { + t.Parallel() + + store := newMemCommitStore() + wallet := &leaseWallet{listErr: errors.New("wallet unavailable")} + srv := newLeaseServer(store, wallet) + req := commitIDRequest([]byte("lease-query-down")) + utxo := testLeaseOutpoint() + + var calls atomic.Int32 + once := func(_ context.Context, _ *wrpc.CommitVirtualPsbtsRequest, + hooks *commitVirtualPsbtsHooks) ( + *wrpc.CommitVirtualPsbtsResponse, error) { + + calls.Add(1) + err := hooks.onFunded( + append([]byte(nil), testLeaseLock...), + []*taprpc.OutPoint{utxo}, time.Time{}, + ) + require.NoError(t, err) + + return nil, errors.New("later failure") + } + + _, err := srv.commitVirtualPsbts(context.Background(), req, once) + require.Error(t, err) + require.EqualValues(t, 0, store.deletes.Load()) + require.EqualValues(t, 1, calls.Load()) +} + +// TestCommitVirtualPsbtsReplacedAttemptDoesNotFinish tests that an +// attempt whose row was taken over by a retry cannot record its +// result on top of the replacement. +func TestCommitVirtualPsbtsReplacedAttemptDoesNotFinish(t *testing.T) { + t.Parallel() + + store := newMemCommitStore() + srv := newIdempotencyServer(store) + req := commitIDRequest([]byte("fence")) + utxo := testLeaseOutpoint() + + started := make(chan struct{}) + release := make(chan struct{}) + once := func(_ context.Context, _ *wrpc.CommitVirtualPsbtsRequest, + hooks *commitVirtualPsbtsHooks) ( + *wrpc.CommitVirtualPsbtsResponse, error) { + + err := hooks.onFunded( + append([]byte(nil), testLeaseLock...), + []*taprpc.OutPoint{utxo}, time.Time{}, + ) + require.NoError(t, err) + close(started) + <-release + + resp := cannedCommitResponse([]*taprpc.OutPoint{utxo}) + err = hooks.onResult(resp) + if err != nil { + return nil, err + } + + return resp, nil + } + + errCh := make(chan error, 1) + go func() { + _, err := srv.commitVirtualPsbts( + context.Background(), req, once, + ) + errCh <- err + }() + + select { + case <-started: + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for the commit attempt") + } + + ensureCommitLockID(req) + hash, err := hashCommitRequest(req) + require.NoError(t, err) + replacementLock := bytes.Repeat([]byte{0x44}, 32) + replacement, err := encodeCommitRecord(&commitRecord{ + Status: commitStatusPending, + RequestHash: hash, + LockID: replacementLock, + }) + require.NoError(t, err) + require.NoError(t, store.UpdateCommitRecord( + context.Background(), req.RequestId, replacement, + )) + close(release) + + require.Error(t, <-errCh) + + raw, err := store.FetchCommitRecord( + context.Background(), req.RequestId, + ) + require.NoError(t, err) + rec, err := decodeCommitRecord(raw) + require.NoError(t, err) + require.Equal(t, commitStatusPending, rec.Status) + require.Equal(t, replacementLock, rec.LockID) +} + +// TestCommitVirtualPsbtsReplacedAttemptReleasesOwnOutputs tests that a +// delayed attempt, whose row a retry has replaced, releases the +// outpoints it acquired and leaves the replacement's outpoints locked. +// Both attempts use the same lnd lock ID. +func TestCommitVirtualPsbtsReplacedAttemptReleasesOwnOutputs(t *testing.T) { + t.Parallel() + + store := newMemCommitStore() + wallet := &releaseWallet{} + srv := newLeaseServer(store, wallet) + req := commitIDRequest([]byte("replaced-release")) + own := testLeaseOutpoint() + shared := &taprpc.OutPoint{ + Txid: bytes.Repeat([]byte{0x55}, 32), + OutputIndex: 4, + } + + once := func(_ context.Context, _ *wrpc.CommitVirtualPsbtsRequest, + hooks *commitVirtualPsbtsHooks) ( + *wrpc.CommitVirtualPsbtsResponse, error) { + + ensureCommitLockID(req) + hash, err := hashCommitRequest(req) + require.NoError(t, err) + + replacement, err := encodeCommitRecord(&commitRecord{ + Status: commitStatusPending, + RequestHash: hash, + LockID: append([]byte(nil), req.CustomLockId...), + Outpoints: []*taprpc.OutPoint{shared}, + CreatedAt: time.Unix(1_700_000_000, 0), + }) + require.NoError(t, err) + require.NoError(t, store.UpdateCommitRecord( + context.Background(), req.RequestId, replacement, + )) + + err = hooks.onFunded( + append([]byte(nil), req.CustomLockId...), + []*taprpc.OutPoint{own, shared}, time.Time{}, + ) + require.ErrorIs(t, err, errCommitAttemptReplaced) + + return nil, err + } + + _, err := srv.commitVirtualPsbts(context.Background(), req, once) + require.ErrorIs(t, err, errCommitAttemptReplaced) + + wallet.mu.Lock() + released := append([]wire.OutPoint(nil), wallet.released...) + lockIDs := append([]wtxmgr.LockID(nil), wallet.lockIDs...) + wallet.mu.Unlock() + + require.Len(t, released, 1) + require.Equal(t, own.OutputIndex, released[0].Index) + require.Equal(t, own.Txid, released[0].Hash[:]) + require.Len(t, lockIDs, 1) + require.Equal(t, testLockID(req.CustomLockId), lockIDs[0]) + + raw, err := store.FetchCommitRecord( + context.Background(), req.RequestId, + ) + require.NoError(t, err) + rec, err := decodeCommitRecord(raw) + require.NoError(t, err) + require.Len(t, rec.Outpoints, 1) + require.True(t, proto.Equal(shared, rec.Outpoints[0])) +} + +// TestCommitVirtualPsbtsSharedLockDoesNotAdoptForeignLease tests that +// a pending row does not record or keep leases it cannot attribute to +// itself when another request uses the same caller-chosen lock ID. +func TestCommitVirtualPsbtsSharedLockDoesNotAdoptForeignLease( + t *testing.T) { + + t.Parallel() + + lock := append([]byte(nil), testCustomLock...) + foreign := &taprpc.OutPoint{ + Txid: bytes.Repeat([]byte{0x66}, 32), + OutputIndex: 2, + } + own := &taprpc.OutPoint{ + Txid: bytes.Repeat([]byte{0x77}, 32), + OutputIndex: 3, + } + + t.Run("recorded neighbor", func(t *testing.T) { + store := newMemCommitStore() + wallet := &leaseWallet{ + leases: []lndclient.LeaseDescriptor{ + describedLease( + lock, foreign, + time.Now().Add(time.Hour), + ), + describedLease( + lock, own, time.Now().Add(time.Hour), + ), + }, + } + srv := newLeaseServer(store, wallet) + + other := commitIDRequest([]byte("other-recorded")) + insertPendingCommit( + t, store, other, lock, + []*taprpc.OutPoint{foreign}, + ) + + req := commitIDRequest([]byte("this-recorded")) + insertPendingCommit(t, store, req, lock, nil) + + statusResp, err := srv.GetCommitVirtualPsbtsStatus( + context.Background(), + &wrpc.GetCommitVirtualPsbtsStatusRequest{ + RequestId: req.RequestId, + }, + ) + require.NoError(t, err) + require.Equal(t, commitStatusPendingProto, statusResp.Status) + require.Len(t, statusResp.LndLockedUtxos, 1) + require.True(t, proto.Equal(own, statusResp.LndLockedUtxos[0])) + }) + + t.Run("unrecorded neighbor", func(t *testing.T) { + store := newMemCommitStore() + wallet := &leaseWallet{ + leases: []lndclient.LeaseDescriptor{ + describedLease( + lock, foreign, + time.Now().Add(time.Hour), + ), + }, + } + srv := newLeaseServer(store, wallet) + + other := commitIDRequest([]byte("other-open")) + insertPendingCommit(t, store, other, lock, nil) + + req := commitIDRequest([]byte("this-open")) + ensureCommitLockID(req) + hash, err := hashCommitRequest(req) + require.NoError(t, err) + raw, err := encodeCommitRecord(&commitRecord{ + Status: commitStatusPending, + RequestHash: hash, + LockID: append([]byte(nil), lock...), + CreatedAt: time.Now().Add(-time.Hour), + LeaseExpiry: time.Now().Add(-time.Minute), + }) + require.NoError(t, err) + require.NoError(t, store.InsertCommitRecord( + context.Background(), req.RequestId, raw, + )) + + var calls atomic.Int32 + _, err = srv.commitVirtualPsbts( + context.Background(), req, successOnce(&calls), + ) + require.NoError(t, err) + require.EqualValues(t, 1, calls.Load()) + + raw, err = store.FetchCommitRecord( + context.Background(), other.RequestId, + ) + require.NoError(t, err) + otherRec, err := decodeCommitRecord(raw) + require.NoError(t, err) + require.Empty(t, otherRec.Outpoints) + }) +} + +// encodeCommitRecordV1 writes the original record layout, which has no +// lease timestamps. +func encodeCommitRecordV1(t *testing.T, rec *commitRecord) []byte { + t.Helper() + + savedCreated := rec.CreatedAt + savedExpiry := rec.LeaseExpiry + rec.CreatedAt = time.Time{} + rec.LeaseExpiry = time.Time{} + t.Cleanup(func() { + rec.CreatedAt = savedCreated + rec.LeaseExpiry = savedExpiry + }) + + raw, err := encodeCommitRecord(rec) + require.NoError(t, err) + require.GreaterOrEqual(t, len(raw), 17) + raw[0] = commitRecordVersion1 + + return raw[:len(raw)-16] +} + +// TestCommitVirtualPsbtsV1StalePendingFundsAgain tests that a pending +// row written before lease timestamps were stored is funded again once +// its outpoints are no longer leased. +func TestCommitVirtualPsbtsV1StalePendingFundsAgain(t *testing.T) { + t.Parallel() + + store := newMemCommitStore() + srv := newLeaseServer(store, &leaseWallet{}) + req := commitIDRequest([]byte("v1-stale")) + utxo := testLeaseOutpoint() + + ensureCommitLockID(req) + hash, err := hashCommitRequest(req) + require.NoError(t, err) + raw := encodeCommitRecordV1(t, &commitRecord{ + Status: commitStatusPending, + RequestHash: hash, + LockID: append([]byte(nil), testLeaseLock...), + Outpoints: []*taprpc.OutPoint{utxo}, + }) + require.NoError(t, store.InsertCommitRecord( + context.Background(), req.RequestId, raw, + )) + + var calls atomic.Int32 + _, err = srv.commitVirtualPsbts( + context.Background(), req, successOnce(&calls), + ) + require.NoError(t, err) + require.EqualValues(t, 1, calls.Load()) +} + +// TestCommitVirtualPsbtsUnrecordedLeaseExpiresFundsAgain tests that a +// crash between FundPsbt and the pending-row update can be retried +// once the lease deadline has passed and lnd holds no matching lease. +func TestCommitVirtualPsbtsUnrecordedLeaseExpiresFundsAgain(t *testing.T) { + t.Parallel() + + store := newMemCommitStore() + srv := newLeaseServer(store, &leaseWallet{}) + req := commitIDRequest([]byte("gap-expired")) + ensureCommitLockID(req) + hash, err := hashCommitRequest(req) + require.NoError(t, err) + + raw, err := encodeCommitRecord(&commitRecord{ + Status: commitStatusPending, + RequestHash: hash, + LockID: append([]byte(nil), req.CustomLockId...), + CreatedAt: time.Now().Add(-time.Hour), + LeaseExpiry: time.Now().Add(-time.Minute), + }) + require.NoError(t, err) + require.NoError(t, store.InsertCommitRecord( + context.Background(), req.RequestId, raw, + )) + + var calls atomic.Int32 + _, err = srv.commitVirtualPsbts( + context.Background(), req, successOnce(&calls), + ) + require.NoError(t, err) + require.EqualValues(t, 1, calls.Load()) +} + +// TestCommitVirtualPsbtsUnrecordedLeaseBeforeExpiryStaysAborted tests +// that a pending row with no outpoints is not taken over before its +// lease deadline while lnd also reports no lease. That is the window +// before FundPsbt returns. +func TestCommitVirtualPsbtsUnrecordedLeaseBeforeExpiryStaysAborted( + t *testing.T) { + + t.Parallel() + + store := newMemCommitStore() + srv := newLeaseServer(store, &leaseWallet{}) + req := commitIDRequest([]byte("gap-inflight")) + ensureCommitLockID(req) + hash, err := hashCommitRequest(req) + require.NoError(t, err) + + raw, err := encodeCommitRecord(&commitRecord{ + Status: commitStatusPending, + RequestHash: hash, + LockID: append([]byte(nil), req.CustomLockId...), + CreatedAt: time.Now(), + LeaseExpiry: time.Now().Add(time.Hour), + }) + require.NoError(t, err) + require.NoError(t, store.InsertCommitRecord( + context.Background(), req.RequestId, raw, + )) + + var calls atomic.Int32 + _, err = srv.commitVirtualPsbts( + context.Background(), req, successOnce(&calls), + ) + assertCode(t, err, codes.Aborted) + require.EqualValues(t, 0, calls.Load()) +} + +// TestCommitVirtualPsbtsStalePendingMismatch tests that an expired +// pending row is not replaced when the retry body differs. +func TestCommitVirtualPsbtsStalePendingMismatch(t *testing.T) { + t.Parallel() + + store := newMemCommitStore() + srv := newLeaseServer(store, &leaseWallet{}) + req := commitIDRequest([]byte("stale-mismatch")) + insertPendingCommit( + t, store, req, testLeaseLock, + []*taprpc.OutPoint{testLeaseOutpoint()}, + ) + + mismatch := commitIDRequest(req.RequestId) + mismatch.AnchorPsbt = []byte("other-template") + + var calls atomic.Int32 + _, err := srv.commitVirtualPsbts( + context.Background(), mismatch, successOnce(&calls), + ) + assertCode(t, err, codes.InvalidArgument) + require.EqualValues(t, 0, calls.Load()) + require.EqualValues(t, 0, store.deletes.Load()) +} + +// TestCommitVirtualPsbtsReleasedFailureRetries tests that a failed +// attempt whose leases are gone releases the request ID. +func TestCommitVirtualPsbtsReleasedFailureRetries(t *testing.T) { + t.Parallel() + + store := newMemCommitStore() + srv := newLeaseServer(store, &leaseWallet{}) + req := commitIDRequest([]byte("released")) + utxo := testLeaseOutpoint() + + var calls atomic.Int32 + once := func(_ context.Context, _ *wrpc.CommitVirtualPsbtsRequest, + hooks *commitVirtualPsbtsHooks) ( + *wrpc.CommitVirtualPsbtsResponse, error) { + + n := calls.Add(1) + err := hooks.onFunded( + append([]byte(nil), testLeaseLock...), + []*taprpc.OutPoint{utxo}, time.Time{}, + ) + require.NoError(t, err) + if n == 1 { + return nil, errors.New("commit failed after release") + } + + resp := cannedCommitResponse([]*taprpc.OutPoint{utxo}) + require.NoError(t, hooks.onResult(resp)) + + return resp, nil + } + + ctx := context.Background() + _, err := srv.commitVirtualPsbts(ctx, req, once) + require.Error(t, err) + require.EqualValues(t, 1, store.deletes.Load()) + + _, err = srv.commitVirtualPsbts(ctx, req, once) + require.NoError(t, err) + require.EqualValues(t, 2, calls.Load()) +} + +// TestCommitVirtualPsbtsRetainPendingSkipsAbandon tests that a failed +// release keeps the request ID even when the lease list is empty, and +// a later retry funds once the row is stale. +func TestCommitVirtualPsbtsRetainPendingSkipsAbandon(t *testing.T) { + t.Parallel() + + store := newMemCommitStore() + srv := newLeaseServer(store, &leaseWallet{}) + req := commitIDRequest([]byte("retain")) + utxo := testLeaseOutpoint() + + var calls atomic.Int32 + once := func(_ context.Context, _ *wrpc.CommitVirtualPsbtsRequest, + hooks *commitVirtualPsbtsHooks) ( + *wrpc.CommitVirtualPsbtsResponse, error) { + + n := calls.Add(1) + err := hooks.onFunded( + append([]byte(nil), testLeaseLock...), + []*taprpc.OutPoint{utxo}, time.Time{}, + ) + require.NoError(t, err) + if n == 1 { + hooks.retainPending = true + + return nil, errors.New("release output failed") + } + + resp := cannedCommitResponse([]*taprpc.OutPoint{utxo}) + require.NoError(t, hooks.onResult(resp)) + + return resp, nil + } + + ctx := context.Background() + _, err := srv.commitVirtualPsbts(ctx, req, once) + require.Error(t, err) + require.EqualValues(t, 0, store.deletes.Load()) + + _, err = srv.commitVirtualPsbts(ctx, req, once) + require.NoError(t, err) + require.EqualValues(t, 2, calls.Load()) +} + +// TestCommitVirtualPsbtsHugeLockStaysPending tests that a lock duration +// past the UnixNano range does not decode as an already-expired lease. +// Recovery must not replace that still-pending request. +func TestCommitVirtualPsbtsHugeLockStaysPending(t *testing.T) { + t.Parallel() + + store := newMemCommitStore() + srv := newLeaseServer(store, &leaseWallet{}) + req := commitIDRequest([]byte("huge-lock")) + req.LockExpirationSeconds = math.MaxUint64 + + release := make(chan struct{}) + var closed sync.Once + closeRelease := func() { + closed.Do(func() { close(release) }) + } + t.Cleanup(closeRelease) + + started := make(chan struct{}) + var calls atomic.Int32 + once := func(_ context.Context, _ *wrpc.CommitVirtualPsbtsRequest, + hooks *commitVirtualPsbtsHooks) ( + *wrpc.CommitVirtualPsbtsResponse, error) { + + calls.Add(1) + close(started) + <-release + + resp := cannedCommitResponse(nil) + if err := hooks.onResult(resp); err != nil { + return nil, err + } + + return resp, nil + } + + errCh := make(chan error, 1) + go func() { + _, err := srv.commitVirtualPsbts( + context.Background(), req, once, + ) + errCh <- err + }() + + select { + case <-started: + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for the commit attempt") + } + + raw, err := store.FetchCommitRecord( + context.Background(), req.RequestId, + ) + require.NoError(t, err) + rec, err := decodeCommitRecord(raw) + require.NoError(t, err) + + var retryCalls atomic.Int32 + _, err = srv.commitVirtualPsbts( + context.Background(), req, successOnce(&retryCalls), + ) + if err == nil { + t.Fatalf("retry funded a still-pending request; "+ + "decoded lease expiry %s", rec.LeaseExpiry.UTC()) + } + assertCode(t, err, codes.Aborted) + require.EqualValues(t, 0, retryCalls.Load()) + require.True(t, time.Now().Before(rec.LeaseExpiry), + "decoded lease expiry %s", rec.LeaseExpiry.UTC()) + + closeRelease() + require.NoError(t, <-errCh) + require.EqualValues(t, 1, calls.Load()) +} + +// TestUtxoLeaseExpiryBeyondUnixNanoStaysFuture tests that an lnd lease +// expiration that does not fit in UnixNano is not stored as a past +// deadline. MaxUint64 used to wrap through int64; MaxInt64 seconds is +// past the last representable nanosecond timestamp. +func TestUtxoLeaseExpiryBeyondUnixNanoStaysFuture(t *testing.T) { + t.Parallel() + + deadlines := []uint64{ + math.MaxUint64, + uint64(math.MaxInt64), + } + for _, sec := range deadlines { + exp := earliestUtxoLeaseExpiry([]*walletrpc.UtxoLease{ + {Expiration: sec}, + }) + raw, err := encodeCommitRecord(&commitRecord{ + Status: commitStatusPending, + CreatedAt: time.Now(), + LeaseExpiry: exp, + }) + require.NoError(t, err) + + rec, err := decodeCommitRecord(raw) + require.NoError(t, err) + require.True(t, time.Now().Before(rec.LeaseExpiry), + "seconds %d decoded as %s", sec, + rec.LeaseExpiry.UTC()) + } + + soon := time.Now().Add(time.Hour).Unix() + exp := earliestUtxoLeaseExpiry([]*walletrpc.UtxoLease{ + {Expiration: uint64(soon)}, + }) + require.Equal(t, soon, exp.Unix()) +} diff --git a/rpcserver/commit_input_lock_test.go b/rpcserver/commit_input_lock_test.go new file mode 100644 index 0000000000..93a202c76a --- /dev/null +++ b/rpcserver/commit_input_lock_test.go @@ -0,0 +1,94 @@ +package rpcserver + +import ( + "encoding/binary" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +var commitLockIDSeq atomic.Uint64 + +func testCommitLockID() []byte { + id := make([]byte, lndLockIDLen) + binary.BigEndian.PutUint64(id, commitLockIDSeq.Add(1)) + + return id +} + +func commitInputLockPresent(lockID []byte) bool { + if len(lockID) != lndLockIDLen { + return false + } + + commitInputLockMu.Lock() + defer commitInputLockMu.Unlock() + + _, ok := commitInputLocks[string(lockID)] + + return ok +} + +// TestLockCommitInputsDropsIdleEntries tests that a lock ID mutex is +// removed once nobody holds or waits on it. Derived request IDs would +// otherwise leave one mutex in the process-global map forever. +func TestLockCommitInputsDropsIdleEntries(t *testing.T) { + t.Parallel() + + id := testCommitLockID() + unlock := lockCommitInputs(id) + + started := make(chan struct{}) + released := make(chan struct{}) + go func() { + close(started) + second := lockCommitInputs(id) + second() + close(released) + }() + + <-started + select { + case <-released: + t.Fatal("second attempt acquired the lock before release") + case <-time.After(50 * time.Millisecond): + } + + // The entry stays while the first attempt holds it and the second + // waits. That is the FundPsbt-through-RPC exclusion. + require.True(t, commitInputLockPresent(id)) + + unlock() + + select { + case <-released: + case <-time.After(2 * time.Second): + t.Fatal("waiter did not acquire the lock") + } + + require.False(t, commitInputLockPresent(id)) + + // A lock ID that is not 32 bytes does not take a mutex. + shortID := []byte("short") + lockCommitInputs(shortID)() + require.False(t, commitInputLockPresent(shortID)) + + var wg sync.WaitGroup + ids := make([][]byte, 32) + for i := range ids { + ids[i] = testCommitLockID() + wg.Add(1) + go func(lockID []byte) { + defer wg.Done() + lockCommitInputs(lockID)() + }(ids[i]) + } + wg.Wait() + + for _, lockID := range ids { + require.False(t, commitInputLockPresent(lockID)) + } +} diff --git a/rpcserver/commit_retention_test.go b/rpcserver/commit_retention_test.go new file mode 100644 index 0000000000..6598a385a6 --- /dev/null +++ b/rpcserver/commit_retention_test.go @@ -0,0 +1,346 @@ +package rpcserver + +import ( + "bytes" + "context" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/lightninglabs/lndclient" + "github.com/lightninglabs/taproot-assets/tapdb" + "github.com/lightninglabs/taproot-assets/taprpc" + wrpc "github.com/lightninglabs/taproot-assets/taprpc/assetwalletrpc" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/proto" +) + +// stubClock is a mutex-guarded clock. Tests advance it without sleeping, +// and commit retention reads it through RPCServer.commitNow. +type stubClock struct { + mu sync.Mutex + now time.Time +} + +func (c *stubClock) Now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + + return c.now +} + +func (c *stubClock) Add(d time.Duration) { + c.mu.Lock() + defer c.mu.Unlock() + + c.now = c.now.Add(d) +} + +func newRetentionServer(store *memCommitStore, clock *stubClock, + window time.Duration) *RPCServer { + + srv := newIdempotencyServer(store) + srv.cfg.CommitVirtualPsbtRetention = window + srv.commitNow = clock.Now + + return srv +} + +// TestCommitVirtualPsbtsRetentionDropsCompleted tests that a completed +// response is replayed inside the retention window and funded again +// once that window has passed. A pending row is kept even when its +// claim time is older than the cutoff. An unstamped completed row from +// before finish times were stored is dropped when its claim is older +// than the window, and a recent one is replayed and then stamped. +func TestCommitVirtualPsbtsRetentionDropsCompleted(t *testing.T) { + t.Parallel() + + // The stub starts ahead of the wall clock. A pending row stamps + // CreatedAt with time.Now, which is then before the cutoff, so a + // purge that used that timestamp would delete it. + start := time.Now().UTC().Add(48 * time.Hour).Truncate(time.Second) + clock := &stubClock{now: start} + store := newMemCommitStore() + srv := newRetentionServer(store, clock, time.Hour) + + var calls atomic.Int32 + once := successOnce(&calls) + req := commitIDRequest([]byte("retain-done")) + ctx := context.Background() + + first, err := srv.commitVirtualPsbts(ctx, req, once) + require.NoError(t, err) + require.EqualValues(t, 1, calls.Load()) + + clock.Add(30 * time.Minute) + second, err := srv.commitVirtualPsbts(ctx, req, once) + require.NoError(t, err) + require.EqualValues(t, 1, calls.Load()) + require.True(t, proto.Equal(first, second)) + + clock.Add(31 * time.Minute) + statusResp, err := srv.GetCommitVirtualPsbtsStatus( + ctx, &wrpc.GetCommitVirtualPsbtsStatusRequest{ + RequestId: req.RequestId, + }, + ) + require.NoError(t, err) + require.Equal(t, commitStatusUnknown, statusResp.Status) + + third, err := srv.commitVirtualPsbts(ctx, req, once) + require.NoError(t, err) + require.EqualValues(t, 2, calls.Load()) + require.True(t, proto.Equal(first, third)) + + // A pending attempt stays pending across a jump past the window. + blocked := make(chan struct{}) + release := make(chan struct{}) + pendingReq := commitIDRequest([]byte("retain-pending")) + var pendingCalls atomic.Int32 + var pendingWG sync.WaitGroup + pendingWG.Add(1) + errCh := make(chan error, 1) + go func() { + defer pendingWG.Done() + + _, callErr := srv.commitVirtualPsbts( + ctx, pendingReq, blockingSuccess( + &pendingCalls, blocked, release, + ), + ) + errCh <- callErr + }() + + <-blocked + clock.Add(48 * time.Hour) + pendingStatus, err := srv.GetCommitVirtualPsbtsStatus( + ctx, &wrpc.GetCommitVirtualPsbtsStatusRequest{ + RequestId: pendingReq.RequestId, + }, + ) + require.NoError(t, err) + require.Equal(t, commitStatusPendingProto, pendingStatus.Status) + + close(release) + pendingWG.Wait() + require.NoError(t, <-errCh) + require.EqualValues(t, 1, pendingCalls.Load()) + + // Legacy completed rows have no finish stamp. An old one is + // removed and funded again. A recent one is replayed, then + // stamped so the next purge does not read the blob. + oldReq := commitIDRequest([]byte("retain-legacy-old")) + insertCompletedUnstamped( + t, store, oldReq, clock.Now().Add(-48*time.Hour), + ) + var oldCalls atomic.Int32 + _, err = srv.commitVirtualPsbts(ctx, oldReq, successOnce(&oldCalls)) + require.NoError(t, err) + require.EqualValues(t, 1, oldCalls.Load()) + + freshReq := commitIDRequest([]byte("retain-legacy-fresh")) + insertCompletedUnstamped( + t, store, freshReq, clock.Now().Add(-time.Minute), + ) + var freshCalls atomic.Int32 + replayed, err := srv.commitVirtualPsbts( + ctx, freshReq, successOnce(&freshCalls), + ) + require.NoError(t, err) + require.EqualValues(t, 0, freshCalls.Load()) + require.True(t, proto.Equal( + cannedCommitResponse([]*taprpc.OutPoint{testLeaseOutpoint()}), + replayed, + )) + + unstamped, err := store.ListUnstampedCommitRecords(ctx) + require.NoError(t, err) + for _, row := range unstamped { + require.NotEqual(t, freshReq.RequestId, row.RequestID) + } +} + +// TestCommitVirtualPsbtsShortRetentionKeepsLiveLease tests that a +// finished row older than a short retention window is kept while lnd +// still leases its recorded outpoints, and deleted once that lease is +// gone. A finished row with no live lease is removed on that same +// purge, so retention does not grow without bound. +func TestCommitVirtualPsbtsShortRetentionKeepsLiveLease(t *testing.T) { + t.Parallel() + + start := time.Now().UTC().Add(48 * time.Hour).Truncate(time.Second) + clock := &stubClock{now: start} + store := newMemCommitStore() + utxo := testLeaseOutpoint() + wallet := &leaseWallet{ + leases: []lndclient.LeaseDescriptor{ + describedLease( + testLeaseLock, utxo, start.Add(time.Hour), + ), + }, + } + srv := newRetentionServer(store, clock, time.Minute) + srv.cfg.Lnd = &lndclient.LndServices{WalletKit: wallet} + + var calls atomic.Int32 + once := successOnce(&calls) + req := commitIDRequest([]byte("short-leased")) + ctx := context.Background() + + first, err := srv.commitVirtualPsbts(ctx, req, once) + require.NoError(t, err) + require.EqualValues(t, 1, calls.Load()) + + // Stamped row with no live lease. The clock jump below puts it + // past the short window, so the purge removes it. + freeReq := commitIDRequest([]byte("short-free")) + freeUtxo := &taprpc.OutPoint{ + Txid: bytes.Repeat([]byte{0x44}, 32), + OutputIndex: 1, + } + freeLock := bytes.Repeat([]byte{0x55}, 32) + insertCompletedRecord( + t, store, freeReq, start, freeLock, freeUtxo, &start, + ) + + // Legacy completed row: no finish stamp, but the same live lease. + legacyReq := commitIDRequest([]byte("short-legacy")) + insertCompletedRecord( + t, store, legacyReq, start, testLeaseLock, utxo, nil, + ) + + clock.Add(2 * time.Minute) + + second, err := srv.commitVirtualPsbts(ctx, req, once) + require.NoError(t, err) + require.EqualValues(t, 1, calls.Load()) + require.True(t, proto.Equal(first, second)) + + _, err = store.FetchCommitRecord(ctx, freeReq.RequestId) + require.ErrorIs(t, err, tapdb.ErrNoCommitRecord) + + legacy, err := store.FetchCommitRecord(ctx, legacyReq.RequestId) + require.NoError(t, err) + require.NotEmpty(t, legacy) + + var freeCalls atomic.Int32 + _, err = srv.commitVirtualPsbts( + ctx, freeReq, successOnce(&freeCalls), + ) + require.NoError(t, err) + require.EqualValues(t, 1, freeCalls.Load()) + + wallet.leases = nil + + third, err := srv.commitVirtualPsbts(ctx, req, once) + require.NoError(t, err) + require.EqualValues(t, 2, calls.Load()) + require.True(t, proto.Equal(first, third)) + + _, err = store.FetchCommitRecord(ctx, legacyReq.RequestId) + require.ErrorIs(t, err, tapdb.ErrNoCommitRecord) +} + +func blockingSuccess(calls *atomic.Int32, blocked, + release chan struct{}) commitOnceFunc { + + utxos := []*taprpc.OutPoint{testLeaseOutpoint()} + + return func(_ context.Context, _ *wrpc.CommitVirtualPsbtsRequest, + hooks *commitVirtualPsbtsHooks) ( + *wrpc.CommitVirtualPsbtsResponse, error) { + + calls.Add(1) + close(blocked) + <-release + + resp := cannedCommitResponse(utxos) + if hooks == nil { + return resp, nil + } + + err := hooks.onFunded( + append([]byte(nil), testLeaseLock...), utxos, + time.Time{}, + ) + if err != nil { + return nil, err + } + + err = hooks.onResult(resp) + if err != nil { + return nil, err + } + + return resp, nil + } +} + +func insertCompletedUnstamped(t *testing.T, store *memCommitStore, + req *wrpc.CommitVirtualPsbtsRequest, created time.Time) { + + t.Helper() + + ensureCommitLockID(req) + hash, err := hashCommitRequest(req) + require.NoError(t, err) + + resp, err := proto.Marshal(cannedCommitResponse( + []*taprpc.OutPoint{testLeaseOutpoint()}, + )) + require.NoError(t, err) + + raw, err := encodeCommitRecord(&commitRecord{ + Status: commitStatusCompleted, + RequestHash: hash, + LockID: append([]byte(nil), req.CustomLockId...), + Outpoints: []*taprpc.OutPoint{testLeaseOutpoint()}, + Response: resp, + CreatedAt: created, + }) + require.NoError(t, err) + require.NoError(t, store.InsertCommitRecord( + context.Background(), req.RequestId, raw, + )) +} + +// insertCompletedRecord stores a completed outcome. A non-nil finished +// time stamps the row the way a normal completion does. A nil time +// leaves it unstamped, which is the legacy layout. +func insertCompletedRecord(t *testing.T, store *memCommitStore, + req *wrpc.CommitVirtualPsbtsRequest, created time.Time, + lock []byte, utxo *taprpc.OutPoint, finished *time.Time) { + + t.Helper() + + ensureCommitLockID(req) + hash, err := hashCommitRequest(req) + require.NoError(t, err) + + resp, err := proto.Marshal(cannedCommitResponse( + []*taprpc.OutPoint{utxo}, + )) + require.NoError(t, err) + + raw, err := encodeCommitRecord(&commitRecord{ + Status: commitStatusCompleted, + RequestHash: hash, + LockID: append([]byte(nil), lock...), + Outpoints: []*taprpc.OutPoint{utxo}, + Response: resp, + CreatedAt: created, + }) + require.NoError(t, err) + require.NoError(t, store.InsertCommitRecord( + context.Background(), req.RequestId, raw, + )) + if finished == nil { + return + } + + stamp := finished.UTC() + require.NoError(t, store.SwapCommitRecord( + context.Background(), req.RequestId, raw, raw, &stamp, + )) +} diff --git a/rpcserver/commit_virtual_psbts.go b/rpcserver/commit_virtual_psbts.go new file mode 100644 index 0000000000..b2115ffbfd --- /dev/null +++ b/rpcserver/commit_virtual_psbts.go @@ -0,0 +1,86 @@ +package rpcserver + +import ( + "bytes" + "errors" + "fmt" + + "github.com/btcsuite/btcd/btcutil/psbt" + wrpc "github.com/lightninglabs/taproot-assets/taprpc/assetwalletrpc" +) + +// ErrAnchorChangeAdded is returned by CommitVirtualPsbts if the caller asked +// for no new anchor change output but funding would add one. +var ErrAnchorChangeAdded = errors.New("unexpected anchor change output") + +// checkNoNewAnchorChange verifies that funding a BTC anchor template via lnd +// did not add a new change output, which is what a CommitVirtualPsbts caller +// asks for by setting anchor_change_output{add=false}. +// +// lnd's PsbtCoinSelect path matches on the type of the change output oneof and +// never evaluates the boolean, so add=false behaves like add=true and lnd +// appends a P2TR change output whenever the leftover exceeds the dust limit +// (https://github.com/lightninglabs/taproot-assets/issues/2209). Until lnd +// offers a real no-change mode, we fail closed instead of silently returning a +// different output topology than the one the caller requested. +// +// template is the anchor packet before funding. funded is the packet returned +// by lnd and changeIndex is the change output index lnd reported (-1 if none). +// +// Outputs are compared in index order. A pair matches only when the values +// are equal and the pk scripts are equal; nil and empty scripts compare +// equal. Any reordering, value change, or script change is a mismatch, as +// is a different output count or a reported change index. +func checkNoNewAnchorChange(template *psbt.Packet, funded *psbt.Packet, + changeIndex int32) error { + + templateOutputs := len(template.UnsignedTx.TxOut) + fundedOutputs := len(funded.UnsignedTx.TxOut) + + for idx := 0; idx < templateOutputs; idx++ { + if idx >= fundedOutputs { + break + } + + tplOut := template.UnsignedTx.TxOut[idx] + fndOut := funded.UnsignedTx.TxOut[idx] + if tplOut.Value != fndOut.Value || + !bytes.Equal(tplOut.PkScript, fndOut.PkScript) { + + return fmt.Errorf("%w: anchor_change_output add=false "+ + "cannot be honored, lnd changed the anchor "+ + "output set (change output index %d, outputs "+ + "%d -> %d); use skip_funding=true with "+ + "caller-supplied inputs or add=true (see "+ + "lightninglabs/taproot-assets#2209)", + ErrAnchorChangeAdded, changeIndex, + templateOutputs, fundedOutputs) + } + } + + if changeIndex == -1 && fundedOutputs == templateOutputs { + return nil + } + + return fmt.Errorf("%w: anchor_change_output add=false cannot be "+ + "honored, lnd changed the anchor output set (change output "+ + "index %d, outputs %d -> %d); use skip_funding=true with "+ + "caller-supplied inputs or add=true (see "+ + "lightninglabs/taproot-assets#2209)", ErrAnchorChangeAdded, + changeIndex, templateOutputs, fundedOutputs) +} + +// noNewAnchorChangeRequested reports whether CommitVirtualPsbts must reject +// funding that alters the anchor output set. skip_funding does not ask lnd +// to select coins, so the caller template is left as-is and this check does +// not apply. Selecting an existing output as change is also unchanged. +func noNewAnchorChangeRequested(req *wrpc.CommitVirtualPsbtsRequest) bool { + if req.SkipFunding { + return false + } + + change := req.AnchorChangeOutput + addOpt, ok := change.(*wrpc.CommitVirtualPsbtsRequest_Add) + + return ok && !addOpt.Add +} diff --git a/rpcserver/commit_virtual_psbts_lease_test.go b/rpcserver/commit_virtual_psbts_lease_test.go new file mode 100644 index 0000000000..e0adaba89d --- /dev/null +++ b/rpcserver/commit_virtual_psbts_lease_test.go @@ -0,0 +1,170 @@ +package rpcserver + +import ( + "context" + "testing" + "time" + + "github.com/btcsuite/btcd/chaincfg/chainhash" + "github.com/btcsuite/btcd/btcutil/psbt" + "github.com/btcsuite/btcd/wire" + "github.com/btcsuite/btcwallet/wtxmgr" + "github.com/lightninglabs/lndclient" + "github.com/lightninglabs/taproot-assets/address" + "github.com/lightninglabs/taproot-assets/fn" + "github.com/lightninglabs/taproot-assets/tapconfig" + "github.com/lightninglabs/taproot-assets/tappsbt" + wrpc "github.com/lightninglabs/taproot-assets/taprpc/assetwalletrpc" + "github.com/lightningnetwork/lnd/lnrpc" + "github.com/lightningnetwork/lnd/lnrpc/walletrpc" + "github.com/stretchr/testify/require" +) + +// driftFundWallet returns a funded anchor that drifts from the template and +// records each ReleaseOutput together with the context it was called on. +type driftFundWallet struct { + lndclient.WalletKitClient + + funded *psbt.Packet + change int32 + leases []*walletrpc.UtxoLease + + fundReq *walletrpc.FundPsbtRequest + releases *mockReleaser +} + +// FundPsbt returns the drifted packet and the leases lnd would have taken. +// The request context is ignored so a canceled RPC still observes a successful +// fund, which is the window the deferred release has to clean up. +func (w *driftFundWallet) FundPsbt(_ context.Context, + req *walletrpc.FundPsbtRequest) (*psbt.Packet, int32, + []*walletrpc.UtxoLease, error) { + + w.fundReq = req + + return w.funded, w.change, w.leases, nil +} + +// ReleaseOutput records the release context and fails when that context is +// already done, matching lnd. +func (w *driftFundWallet) ReleaseOutput(ctx context.Context, + lockID wtxmgr.LockID, op wire.OutPoint) error { + + return w.releases.ReleaseOutput(ctx, lockID, op) +} + +// driftedLeases builds n wallet leases with distinct ids and outpoints. +func driftedLeases(n int) []*walletrpc.UtxoLease { + leases := make([]*walletrpc.UtxoLease, n) + for i := 0; i < n; i++ { + leases[i] = &walletrpc.UtxoLease{ + Id: []byte{byte(i + 1)}, + Outpoint: &lnrpc.OutPoint{ + TxidBytes: []byte{byte(0xa0 + i)}, + OutputIndex: uint32(i), + }, + } + } + + return leases +} + +// leaseOutpoint is the outpoint CommitVirtualPsbts derives from a lease. +func leaseOutpoint(lease *walletrpc.UtxoLease) wire.OutPoint { + var hash chainhash.Hash + copy(hash[:], lease.Outpoint.TxidBytes) + + return wire.OutPoint{ + Hash: hash, + Index: lease.Outpoint.OutputIndex, + } +} + +// TestCommitVirtualPsbtsDriftReleasesCanceledCtx covers the #2209 fail-closed +// path together with the #2206 lease release. A drifted add=false response is +// returned while the request context is already canceled. Every lease must +// still be released, once, on a live context. +// +// Releasing on the canceled parent context makes ctx.Err() non-nil, so this +// test fails unless releaseLeasedOutputs detaches via context.WithoutCancel. +func TestCommitVirtualPsbtsDriftReleasesCanceledCtx(t *testing.T) { + t.Parallel() + + template := testPacket(t, 2) + funded := clonePacket(t, template) + funded.UnsignedTx.AddTxOut(&wire.TxOut{ + Value: 50000, + PkScript: []byte{0x51, 0xff}, + }) + + anchorBytes, err := fn.Serialize(template) + require.NoError(t, err) + + vPkt := &tappsbt.VPacket{ + ChainParams: &address.RegressionNetTap, + Version: tappsbt.V0, + } + virtualBytes, err := fn.Serialize(vPkt) + require.NoError(t, err) + + leases := driftedLeases(3) + wallet := &driftFundWallet{ + funded: funded, + change: 2, + leases: leases, + releases: &mockReleaser{}, + } + server := &RPCServer{ + cfg: &tapconfig.Config{ + Lnd: &lndclient.LndServices{ + WalletKit: wallet, + }, + }, + } + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + require.ErrorIs(t, ctx.Err(), context.Canceled) + + start := time.Now() + _, err = server.CommitVirtualPsbts( + ctx, &wrpc.CommitVirtualPsbtsRequest{ + AnchorPsbt: anchorBytes, + VirtualPsbts: [][]byte{virtualBytes}, + Fees: &wrpc.CommitVirtualPsbtsRequest_SatPerVbyte{ + SatPerVbyte: 1, + }, + AnchorChangeOutput: &wrpc.CommitVirtualPsbtsRequest_Add{ + Add: false, + }, + }, + ) + require.ErrorIs(t, err, ErrAnchorChangeAdded) + + coinSelect := wallet.fundReq.GetCoinSelect() + add, ok := coinSelect.ChangeOutput.(*walletrpc.PsbtCoinSelect_Add) + require.True(t, ok) + require.False(t, add.Add) + + require.Len(t, wallet.releases.calls, len(leases)) + + seen := make(map[wire.OutPoint]int, len(leases)) + for i, call := range wallet.releases.calls { + require.NoError(t, call.ctxErr) + require.True(t, call.hasDeadline) + require.LessOrEqual( + t, call.deadline.Sub(start), + leaseReleaseTimeout+time.Second, + ) + + var lockID wtxmgr.LockID + copy(lockID[:], leases[i].Id) + require.Equal(t, lockID, call.lockID) + + seen[call.op]++ + } + + for _, lease := range leases { + require.Equal(t, 1, seen[leaseOutpoint(lease)]) + } +} diff --git a/rpcserver/commit_virtual_psbts_test.go b/rpcserver/commit_virtual_psbts_test.go new file mode 100644 index 0000000000..c8dc1bc2ad --- /dev/null +++ b/rpcserver/commit_virtual_psbts_test.go @@ -0,0 +1,253 @@ +package rpcserver + +import ( + "bytes" + "fmt" + "testing" + + "github.com/btcsuite/btcd/btcutil/psbt" + "github.com/btcsuite/btcd/wire" + wrpc "github.com/lightninglabs/taproot-assets/taprpc/assetwalletrpc" + "github.com/stretchr/testify/require" +) + +// testPacket returns a PSBT whose outputs differ in both value and script, +// so a reorder or a script-only edit is visible to the comparison. +func testPacket(t *testing.T, numOutputs int) *psbt.Packet { + t.Helper() + + tx := wire.NewMsgTx(2) + tx.AddTxIn(&wire.TxIn{}) + for i := 0; i < numOutputs; i++ { + tx.AddTxOut(&wire.TxOut{ + Value: int64(1000 + i), + PkScript: []byte{0x51, byte(i)}, + }) + } + + pkt, err := psbt.NewFromUnsignedTx(tx) + require.NoError(t, err) + + return pkt +} + +func clonePacket(t *testing.T, pkt *psbt.Packet) *psbt.Packet { + t.Helper() + + raw, err := pkt.B64Encode() + require.NoError(t, err) + + clone, err := psbt.NewFromRawBytes(bytes.NewReader([]byte(raw)), true) + require.NoError(t, err) + + return clone +} + +// anchorChangeCase is one CommitVirtualPsbts add=false comparison. +type anchorChangeCase struct { + name string + template int + funded int + changeIndex int32 + alterValue int + alterScript int + reorder bool + expectErr bool +} + +// TestCheckNoNewAnchorChange makes sure the add=false guard for +// CommitVirtualPsbts (taproot-assets#2209) fails closed whenever lnd changed +// the output set of the anchor template and only passes if it is untouched. +// Comparison is positional: values and pk scripts must match in order. +func TestCheckNoNewAnchorChange(t *testing.T) { + t.Parallel() + + testCases := []anchorChangeCase{{ + name: "unchanged outputs, no change index", + template: 2, + funded: 2, + changeIndex: -1, + alterValue: -1, + alterScript: -1, + }, { + name: "change output appended", + template: 2, + funded: 3, + changeIndex: 2, + alterValue: -1, + alterScript: -1, + expectErr: true, + }, { + name: "change index reported without new output", + template: 2, + funded: 2, + changeIndex: 1, + alterValue: -1, + alterScript: -1, + expectErr: true, + }, { + name: "output appended without change index", + template: 1, + funded: 2, + changeIndex: -1, + alterValue: -1, + alterScript: -1, + expectErr: true, + }, { + name: "output removed", + template: 2, + funded: 1, + changeIndex: -1, + alterValue: -1, + alterScript: -1, + expectErr: true, + }, { + name: "template output value altered in place", + template: 2, + funded: 2, + changeIndex: -1, + alterValue: 1, + alterScript: -1, + expectErr: true, + }, { + name: "template output script altered in place", + template: 2, + funded: 2, + changeIndex: -1, + alterValue: -1, + alterScript: 0, + expectErr: true, + }, { + name: "outputs reordered", + template: 2, + funded: 2, + changeIndex: -1, + alterValue: -1, + alterScript: -1, + reorder: true, + expectErr: true, + }} + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + template := testPacket(t, tc.template) + funded := fundedPacket(t, template, tc) + + err := checkNoNewAnchorChange( + template, funded, tc.changeIndex, + ) + if !tc.expectErr { + require.NoError(t, err) + return + } + + require.ErrorIs(t, err, ErrAnchorChangeAdded) + require.ErrorContains(t, err, "#2209") + require.EqualError(t, err, fmt.Sprintf( + "unexpected anchor change output: "+ + "anchor_change_output add=false "+ + "cannot be honored, lnd changed "+ + "the anchor output set (change "+ + "output index %d, outputs %d -> "+ + "%d); use skip_funding=true with "+ + "caller-supplied inputs or "+ + "add=true (see lightninglabs/"+ + "taproot-assets#2209)", + tc.changeIndex, tc.template, tc.funded, + )) + }) + } +} + +// fundedPacket builds the funded side of an anchor-change comparison. +func fundedPacket(t *testing.T, template *psbt.Packet, + tc anchorChangeCase) *psbt.Packet { + + t.Helper() + + switch { + case tc.reorder: + funded := clonePacket(t, template) + outs := funded.UnsignedTx.TxOut + outs[0], outs[1] = outs[1], outs[0] + + return funded + + case tc.alterValue >= 0: + funded := clonePacket(t, template) + funded.UnsignedTx.TxOut[tc.alterValue].Value = 999 + + return funded + + case tc.alterScript >= 0: + funded := clonePacket(t, template) + out := funded.UnsignedTx.TxOut[tc.alterScript] + out.PkScript = []byte{0xff} + + return funded + + case tc.funded == tc.template: + return template + + default: + funded := testPacket(t, tc.funded) + limit := tc.template + if tc.funded < limit { + limit = tc.funded + } + for idx := 0; idx < limit; idx++ { + funded.UnsignedTx.TxOut[idx] = + template.UnsignedTx.TxOut[idx] + } + + return funded + } +} + +// TestCheckNoNewAnchorChangeNilScript locks the script comparison: +// bytes.Equal treats a nil pk script and an empty one as the same output. +func TestCheckNoNewAnchorChangeNilScript(t *testing.T) { + t.Parallel() + + template := testPacket(t, 1) + template.UnsignedTx.TxOut[0].PkScript = nil + + funded := clonePacket(t, template) + funded.UnsignedTx.TxOut[0].PkScript = []byte{} + + err := checkNoNewAnchorChange(template, funded, -1) + require.NoError(t, err) +} + +// TestNoNewAnchorChangeRequested locks the gate around the funding check. +// skip_funding, add=true, and an existing change output must not run it. +func TestNoNewAnchorChangeRequested(t *testing.T) { + t.Parallel() + + add := func(v bool) *wrpc.CommitVirtualPsbtsRequest { + return &wrpc.CommitVirtualPsbtsRequest{ + AnchorChangeOutput: &wrpc.CommitVirtualPsbtsRequest_Add{ + Add: v, + }, + } + } + + existingIdx := &wrpc.CommitVirtualPsbtsRequest_ExistingOutputIndex{ + ExistingOutputIndex: 0, + } + existing := &wrpc.CommitVirtualPsbtsRequest{ + AnchorChangeOutput: existingIdx, + } + skipped := add(false) + skipped.SkipFunding = true + + require.True(t, noNewAnchorChangeRequested(add(false))) + require.False(t, noNewAnchorChangeRequested(add(true))) + require.False(t, noNewAnchorChangeRequested(skipped)) + require.False(t, noNewAnchorChangeRequested(existing)) + require.False(t, noNewAnchorChangeRequested( + &wrpc.CommitVirtualPsbtsRequest{}, + )) +} diff --git a/rpcserver/lease_release.go b/rpcserver/lease_release.go new file mode 100644 index 0000000000..24cd9c2a44 --- /dev/null +++ b/rpcserver/lease_release.go @@ -0,0 +1,49 @@ +package rpcserver + +import ( + "context" + "time" + + "github.com/btcsuite/btcd/wire" + "github.com/btcsuite/btcwallet/wtxmgr" + "github.com/lightningnetwork/lnd/lnrpc/walletrpc" +) + +const leaseReleaseTimeout = 30 * time.Second + +// outputReleaser is the subset of the lnd wallet kit used to release leased +// outputs. +type outputReleaser interface { + // ReleaseOutput unlocks an output, allowing it to be available for coin + // selection if it remains unspent. + ReleaseOutput(ctx context.Context, lockID wtxmgr.LockID, + op wire.OutPoint) error +} + +// releaseLeasedOutputs releases the given lnd wallet leases. It is meant to be +// called from deferred cleanup paths, which commonly run because the request +// context was canceled (client deadline, disconnect). Releasing on that +// context would fail immediately and leak the leases until they expire, so the +// release runs on a context that keeps the values of the parent but not its +// cancellation, bounded by leaseReleaseTimeout. See +// lightninglabs/taproot-assets#2206. +func releaseLeasedOutputs(parent context.Context, wallet outputReleaser, + leases []*walletrpc.UtxoLease, outpoints []wire.OutPoint) { + + ctx, cancel := context.WithTimeout( + context.WithoutCancel(parent), leaseReleaseTimeout, + ) + defer cancel() + + for idx, lease := range leases { + var lockID wtxmgr.LockID + copy(lockID[:], lease.Id) + + op := outpoints[idx] + err := wallet.ReleaseOutput(ctx, lockID, op) + if err != nil { + rpcsLog.Errorf("Error unlocking lnd UTXO %v: %v", op, + err) + } + } +} diff --git a/rpcserver/lease_release_test.go b/rpcserver/lease_release_test.go new file mode 100644 index 0000000000..efdf3b62a6 --- /dev/null +++ b/rpcserver/lease_release_test.go @@ -0,0 +1,132 @@ +package rpcserver + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/btcsuite/btcd/wire" + "github.com/btcsuite/btcwallet/wtxmgr" + "github.com/lightningnetwork/lnd/lnrpc/walletrpc" + "github.com/stretchr/testify/require" +) + +type releaseCall struct { + lockID wtxmgr.LockID + op wire.OutPoint + ctxErr error + hasDeadline bool + deadline time.Time +} + +// mockReleaser records the state of the context each release is issued on and +// fails like lnd does when that context is already canceled. +type mockReleaser struct { + calls []releaseCall + failFor map[wire.OutPoint]error +} + +func (m *mockReleaser) ReleaseOutput(ctx context.Context, + lockID wtxmgr.LockID, op wire.OutPoint) error { + + dl, ok := ctx.Deadline() + m.calls = append(m.calls, releaseCall{ + lockID: lockID, op: op, ctxErr: ctx.Err(), + hasDeadline: ok, deadline: dl, + }) + + if err := ctx.Err(); err != nil { + return err + } + + return m.failFor[op] +} + +func testLeases(n int) ([]*walletrpc.UtxoLease, []wire.OutPoint) { + leases := make([]*walletrpc.UtxoLease, n) + ops := make([]wire.OutPoint, n) + for i := 0; i < n; i++ { + leases[i] = &walletrpc.UtxoLease{Id: []byte{byte(i + 1)}} + ops[i] = wire.OutPoint{Index: uint32(i)} + } + + return leases, ops +} + +// TestReleaseLeasedOutputsCanceledContext makes sure leases are still released +// when the request context is already canceled (taproot-assets#2206). +func TestReleaseLeasedOutputsCanceledContext(t *testing.T) { + t.Parallel() + + leases, ops := testLeases(3) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + m := &mockReleaser{} + start := time.Now() + releaseLeasedOutputs(ctx, m, leases, ops) + + require.Len(t, m.calls, 3) + for i, c := range m.calls { + require.NoError(t, c.ctxErr, "release %d ran on dead ctx", i) + require.Equal(t, ops[i], c.op) + require.Equal(t, wtxmgr.LockID{byte(i + 1)}, c.lockID) + + // The release context must be bounded. + require.True(t, c.hasDeadline) + require.LessOrEqual( + t, c.deadline.Sub(start), + leaseReleaseTimeout+time.Second, + ) + } + + // Sanity check the test itself: releasing on the canceled request + // context directly (the old behaviour) fails. + old := &mockReleaser{} + err := old.ReleaseOutput(ctx, wtxmgr.LockID{}, wire.OutPoint{}) + require.ErrorIs(t, err, context.Canceled) +} + +// TestReleaseLeasedOutputsKeepsValues makes sure context values of the request +// context are preserved. +func TestReleaseLeasedOutputsKeepsValues(t *testing.T) { + t.Parallel() + + type key struct{} + parent := context.WithValue(context.Background(), key{}, "v") + + var got any + w := &valueReleaser{key: key{}, out: &got} + leases, ops := testLeases(1) + releaseLeasedOutputs(parent, w, leases, ops) + require.Equal(t, "v", got) +} + +type valueReleaser struct { + key any + out *any +} + +func (v *valueReleaser) ReleaseOutput(ctx context.Context, _ wtxmgr.LockID, + _ wire.OutPoint) error { + + *v.out = ctx.Value(v.key) + return nil +} + +// TestReleaseLeasedOutputsContinuesOnError makes sure one failing release +// doesn't prevent the remaining leases from being released. +func TestReleaseLeasedOutputsContinuesOnError(t *testing.T) { + t.Parallel() + + leases, ops := testLeases(3) + m := &mockReleaser{ + failFor: map[wire.OutPoint]error{ + ops[0]: errors.New("boom"), + }, + } + releaseLeasedOutputs(context.Background(), m, leases, ops) + require.Len(t, m.calls, 3) +} diff --git a/rpcserver/publish_log_test.go b/rpcserver/publish_log_test.go new file mode 100644 index 0000000000..38024ca47e --- /dev/null +++ b/rpcserver/publish_log_test.go @@ -0,0 +1,177 @@ +package rpcserver + +import ( + "bytes" + "context" + "sync/atomic" + "testing" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/chaincfg/chainhash" + "github.com/btcsuite/btcd/btcutil/psbt" + "github.com/btcsuite/btcd/wire" + "github.com/lightninglabs/taproot-assets/address" + "github.com/lightninglabs/taproot-assets/asset" + "github.com/lightninglabs/taproot-assets/fn" + "github.com/lightninglabs/taproot-assets/tapconfig" + "github.com/lightninglabs/taproot-assets/tapfreighter" + "github.com/lightninglabs/taproot-assets/tappsbt" + wrpc "github.com/lightninglabs/taproot-assets/taprpc/assetwalletrpc" + "github.com/stretchr/testify/require" +) + +// loggedPublishPorter serves one already-logged transfer and counts +// shipment requests. It embeds Porter so only the methods this RPC +// calls need to be implemented. +type loggedPublishPorter struct { + tapfreighter.Porter + + logged *tapfreighter.OutboundParcel + shipments atomic.Int32 +} + +func (p *loggedPublishPorter) QueryParcels(_ context.Context, + anchorTxHash fn.Option[chainhash.Hash], _ bool) ( + []*tapfreighter.OutboundParcel, error) { + + if p.logged == nil || p.logged.AnchorTx == nil { + return nil, nil + } + + var matched []*tapfreighter.OutboundParcel + anchorTxHash.WhenSome(func(hash chainhash.Hash) { + if p.logged.AnchorTx.TxHash() == hash { + matched = append(matched, p.logged) + } + }) + + return matched, nil +} + +func (p *loggedPublishPorter) RequestShipment( + tapfreighter.Parcel) (*tapfreighter.OutboundParcel, error) { + + p.shipments.Add(1) + + return p.logged, nil +} + +// finalizedAnchorPSBT returns a PSBT Extract can finalize, plus that +// final transaction. The witness is an empty stack; the txid does not +// cover it. +func finalizedAnchorPSBT(t *testing.T) (*psbt.Packet, *wire.MsgTx) { + t.Helper() + + tx := wire.NewMsgTx(2) + tx.AddTxIn(&wire.TxIn{}) + tx.AddTxOut(&wire.TxOut{ + Value: 1_000, + PkScript: []byte{0x51}, + }) + + pkt, err := psbt.NewFromUnsignedTx(tx) + require.NoError(t, err) + + pkt.Inputs[0].WitnessUtxo = &wire.TxOut{ + Value: 2_000, + PkScript: []byte{0x51}, + } + pkt.Inputs[0].FinalScriptWitness = []byte{0x00} + + finalTx, err := psbt.Extract(pkt) + require.NoError(t, err) + + return pkt, finalTx +} + +// incompleteVirtualPacket encodes a virtual packet whose output has no +// asset. Input validation dereferences that asset, so a call that still +// validates this packet panics. +func incompleteVirtualPacket(t *testing.T) []byte { + t.Helper() + + key, err := btcec.NewPrivateKey() + require.NoError(t, err) + + raw, err := tappsbt.Encode(&tappsbt.VPacket{ + ChainParams: &address.RegressionNetTap, + Outputs: []*tappsbt.VOutput{{ + ScriptKey: asset.ScriptKey{ + PubKey: key.PubKey(), + }, + }}, + }) + require.NoError(t, err) + + return raw +} + +func publishAndLogRequest(t *testing.T, pkt *psbt.Packet, + rawVirtual []byte) *wrpc.PublishAndLogRequest { + + t.Helper() + + var buf bytes.Buffer + require.NoError(t, pkt.Serialize(&buf)) + + return &wrpc.PublishAndLogRequest{ + AnchorPsbt: buf.Bytes(), + VirtualPsbts: [][]byte{rawVirtual}, + RequestId: []byte("req-1"), + Label: "retry", + } +} + +// TestPublishAndLogTransferSkipsValidationWhenLogged checks that a +// repeat publish of an already-logged anchor returns that transfer. +// The virtual packet would panic in input validation, so success means +// validation was skipped. +func TestPublishAndLogTransferSkipsValidationWhenLogged(t *testing.T) { + t.Parallel() + + pkt, finalTx := finalizedAnchorPSBT(t) + porter := &loggedPublishPorter{ + logged: &tapfreighter.OutboundParcel{ + AnchorTx: finalTx, + Label: "logged-transfer", + }, + } + server := &RPCServer{cfg: &tapconfig.Config{ + ChainPorter: porter, + DatabaseConfig: &tapconfig.DatabaseConfig{}, + }} + + resp, err := server.PublishAndLogTransfer( + context.Background(), + publishAndLogRequest(t, pkt, incompleteVirtualPacket(t)), + ) + require.NoError(t, err) + anchorHash := finalTx.TxHash() + require.Equal(t, anchorHash[:], resp.Transfer.AnchorTxHash) + require.Equal(t, "logged-transfer", resp.Transfer.Label) + require.Equal(t, int32(1), porter.shipments.Load()) +} + +// TestPublishAndLogTransferValidatesWhenUnlogged checks that a first +// publish still validates. The incomplete packet panics there, and the +// porter is not asked to ship it. +func TestPublishAndLogTransferValidatesWhenUnlogged(t *testing.T) { + t.Parallel() + + pkt, _ := finalizedAnchorPSBT(t) + porter := &loggedPublishPorter{} + server := &RPCServer{cfg: &tapconfig.Config{ + ChainPorter: porter, + DatabaseConfig: &tapconfig.DatabaseConfig{}, + }} + + require.Panics(t, func() { + _, _ = server.PublishAndLogTransfer( + context.Background(), + publishAndLogRequest( + t, pkt, incompleteVirtualPacket(t), + ), + ) + }) + require.Zero(t, porter.shipments.Load()) +} diff --git a/rpcserver/rpcserver.go b/rpcserver/rpcserver.go index 5e8ac74b3b..39c3152241 100644 --- a/rpcserver/rpcserver.go +++ b/rpcserver/rpcserver.go @@ -28,7 +28,6 @@ import ( "github.com/btcsuite/btcd/chaincfg" "github.com/btcsuite/btcd/chaincfg/chainhash" "github.com/btcsuite/btcd/wire" - "github.com/btcsuite/btcwallet/wtxmgr" "github.com/davecgh/go-spew/spew" proxy "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" "github.com/lightninglabs/lndclient" @@ -140,6 +139,10 @@ const ( // return feedback when importing an address into the wallet. The import // may continue in the background after the timeout expires. addrImportTimeout = 20 * time.Second + + // maxCustomAnchorPsbtSize bounds caller-controlled PSBT work performed + // synchronously by the mint gardener. + maxCustomAnchorPsbtSize = 4 * 1024 * 1024 ) type ( @@ -220,6 +223,10 @@ type RPCServer struct { quit chan struct{} wg sync.WaitGroup + + // commitNow, when set, is the clock for CommitVirtualPsbts retention. + // Production leaves it nil and uses time.Now. + commitNow func() time.Time } // NewRPCServer creates a new RPC sever. @@ -247,6 +254,10 @@ func (r *RPCServer) Start(cfg *tapconfig.Config) error { r.cfg.UniverseQueriesPerSecond, r.cfg.UniverseQueriesBurst, ) + if err := r.purgeExpiredCommitRecords(); err != nil { + rpcsLog.Errorf("Error purging expired commit records: %v", err) + } + // All of our dependencies are now wired up, so we can flip the ready // flag. This must happen last: the atomic store also acts as the // release barrier that publishes the writes above (config, rate @@ -944,13 +955,53 @@ func checkFeeRateSanity(ctx context.Context, rpcFeeRate chainfee.SatPerKWeight, func (r *RPCServer) FundBatch(ctx context.Context, req *mintrpc.FundBatchRequest) (*mintrpc.FundBatchResponse, error) { - feeRate, err := checkFeeRateSanity( - ctx, chainfee.SatPerKWeight(req.FeeRate), r.cfg.Lnd.WalletKit, - ) - if err != nil { - return nil, err + if len(req.AnchorPsbt) != 0 && req.FeeRate != 0 { + return nil, fmt.Errorf("fee rate cannot be combined with a " + + "caller-funded anchor PSBT") + } + if len(req.AnchorPsbt) == 0 && (req.AssetAnchorOutputIndex != 0 || + req.ChangeOutputIndex != 0 || req.NoChangeOutput || + req.PreCommitOutputIndex != nil) { + + return nil, fmt.Errorf( + "custom anchor output controls require anchor_psbt", + ) + } + if req.NoChangeOutput && req.ChangeOutputIndex != 0 { + return nil, fmt.Errorf("no_change_output conflicts with " + + "change_output_index") + } + + var anchorPsbt *psbt.Packet + if len(req.AnchorPsbt) != 0 { + if len(req.AnchorPsbt) > maxCustomAnchorPsbtSize { + return nil, fmt.Errorf( + "anchor PSBT exceeds maximum size of %d bytes", + maxCustomAnchorPsbtSize, + ) + } + var err error + anchorPsbt, err = psbt.NewFromRawBytes( + bytes.NewReader(req.AnchorPsbt), false, + ) + if err != nil { + return nil, fmt.Errorf( + "unable to parse anchor PSBT: %w", err, + ) + } + } + + var feeRateOpt fn.Option[chainfee.SatPerKWeight] + if anchorPsbt == nil { + feeRate, err := checkFeeRateSanity( + ctx, chainfee.SatPerKWeight(req.FeeRate), + r.cfg.Lnd.WalletKit, + ) + if err != nil { + return nil, err + } + feeRateOpt = fn.MaybeSome(feeRate) } - feeRateOpt := fn.MaybeSome(feeRate) tapTreeOpt, err := rpcutils.UnmarshalTapscriptSibling( req.GetFullTree(), req.GetBranch(), @@ -959,9 +1010,22 @@ func (r *RPCServer) FundBatch(ctx context.Context, return nil, err } + changeOutputIndex := req.ChangeOutputIndex + if req.NoChangeOutput { + changeOutputIndex = -1 + } + preCommitIdx := fn.None[uint32]() + if req.PreCommitOutputIndex != nil { + preCommitIdx = fn.Some(req.GetPreCommitOutputIndex()) + } + fundBatchResp, err := r.cfg.AssetMinter.FundBatch(tapgarden.FundParams{ - FeeRate: feeRateOpt, - SiblingTapTree: tapTreeOpt, + FeeRate: feeRateOpt, + SiblingTapTree: tapTreeOpt, + AnchorPsbt: anchorPsbt, + AssetAnchorOutIdx: req.AssetAnchorOutputIndex, + ChangeOutputIndex: changeOutputIndex, + PreCommitOutputIndex: preCommitIdx, }) if err != nil { return nil, fmt.Errorf("unable to fund batch: %w", err) @@ -1065,30 +1129,78 @@ func (r *RPCServer) SealBatch(ctx context.Context, }, nil } +// PrepareBatch commits the current caller-authored batch into its selected +// anchor output and returns the packet for external signing. +func (r *RPCServer) PrepareBatch(_ context.Context, + req *mintrpc.PrepareBatchRequest) (*mintrpc.PrepareBatchResponse, error) { + + batch, err := r.cfg.AssetMinter.PrepareBatch() + if err != nil { + return nil, fmt.Errorf("unable to prepare batch: %w", err) + } + rpcBatch, err := marshalMintingBatch(batch, req.ShortResponse) + if err != nil { + return nil, err + } + + return &mintrpc.PrepareBatchResponse{ + Batch: rpcBatch, + }, nil +} + // FinalizeBatch attempts to finalize the current pending batch. func (r *RPCServer) FinalizeBatch(ctx context.Context, req *mintrpc.FinalizeBatchRequest) (*mintrpc.FinalizeBatchResponse, error) { - feeRate, err := checkFeeRateSanity( - ctx, chainfee.SatPerKWeight(req.FeeRate), r.cfg.Lnd.WalletKit, - ) - if err != nil { - return nil, err + var signedPsbt *psbt.Packet + if len(req.SignedPsbt) != 0 { + if len(req.SignedPsbt) > maxCustomAnchorPsbtSize { + return nil, fmt.Errorf( + "signed PSBT exceeds maximum size of %d bytes", + maxCustomAnchorPsbtSize, + ) + } + if req.FeeRate != 0 || req.GetFullTree() != nil || + req.GetBranch() != nil { + + return nil, fmt.Errorf("signed PSBT cannot be combined " + + "with fee rate or tapscript sibling") + } + var err error + signedPsbt, err = psbt.NewFromRawBytes( + bytes.NewReader(req.SignedPsbt), false, + ) + if err != nil { + return nil, fmt.Errorf("unable to parse signed PSBT: %w", + err) + } } - feeRateOpt := fn.MaybeSome(feeRate) - tapTreeOpt, err := rpcutils.UnmarshalTapscriptSibling( - req.GetFullTree(), req.GetBranch(), - ) - if err != nil { - return nil, err + var feeRateOpt fn.Option[chainfee.SatPerKWeight] + var tapTreeOpt fn.Option[asset.TapscriptTreeNodes] + if signedPsbt == nil { + feeRate, err := checkFeeRateSanity( + ctx, chainfee.SatPerKWeight(req.FeeRate), r.cfg.Lnd.WalletKit, + ) + if err != nil { + return nil, err + } + feeRateOpt = fn.MaybeSome(feeRate) + + tapTreeOpt, err = rpcutils.UnmarshalTapscriptSibling( + req.GetFullTree(), req.GetBranch(), + ) + if err != nil { + return nil, err + } } batch, err := r.cfg.AssetMinter.FinalizeBatch( tapgarden.FinalizeParams{ FeeRate: feeRateOpt, SiblingTapTree: tapTreeOpt, + SignedPsbt: signedPsbt, }, ) if err != nil { @@ -3043,237 +3155,6 @@ func transitionProofOptions( } } -// CommitVirtualPsbts creates the output commitments and proofs for the given -// virtual transactions by committing them to the BTC level anchor transaction. -// In addition, the BTC level anchor transaction is funded and prepared up to -// the point where it is ready to be signed. -func (r *RPCServer) CommitVirtualPsbts(ctx context.Context, - req *wrpc.CommitVirtualPsbtsRequest) (*wrpc.CommitVirtualPsbtsResponse, - error) { - - proofOpts, err := transitionProofOptions(req.TransitionProofVersion) - if err != nil { - return nil, err - } - - if len(req.VirtualPsbts) == 0 { - return nil, fmt.Errorf("no virtual PSBTs specified") - } - - pkt, err := psbt.NewFromRawBytes(bytes.NewReader(req.AnchorPsbt), false) - if err != nil { - return nil, fmt.Errorf("error decoding packet: %w", err) - } - - activePackets, err := decodeVirtualPackets(req.VirtualPsbts) - if err != nil { - return nil, fmt.Errorf("error decoding active packets: %w", err) - } - - passivePackets, err := decodeVirtualPackets(req.PassiveAssetPsbts) - if err != nil { - return nil, fmt.Errorf("error decoding passive packets: %w", - err) - } - - // Make sure the assets given fully satisfy the input commitments. - allPackets := append([]*tappsbt.VPacket{}, activePackets...) - allPackets = append(allPackets, passivePackets...) - err = r.validateInputAssets(ctx, pkt, allPackets) - if err != nil { - return nil, fmt.Errorf("error validating input assets: %w", err) - } - - // We're ready to attempt to fund the transaction now. For that we first - // need to re-serialize our packet. - packetBytes, err := fn.Serialize(pkt) - if err != nil { - return nil, fmt.Errorf("error serializing packet: %w", err) - } - - var ( - lockedUTXO []*walletrpc.UtxoLease - lockedOutpoints []wire.OutPoint - fundedPacket *psbt.Packet = pkt - changeIndex int32 = -1 - success bool - ) - - if !req.SkipFunding { - // The change output and fee parameters of this RPC are - // identical to the walletrpc.FundPsbt, so we just map them 1:1 - // and let lnd do the validation. - coinSelect := &walletrpc.PsbtCoinSelect{ - Psbt: packetBytes, - } - fundRequest := &walletrpc.FundPsbtRequest{ - Template: &walletrpc.FundPsbtRequest_CoinSelect{ - CoinSelect: coinSelect, - }, - MinConfs: 1, - ChangeType: P2TRChangeType, - CustomLockId: req.CustomLockId, - LockExpirationSeconds: req.LockExpirationSeconds, - } - - // Unfortunately we can't use the same RPC types, so we have to - // do a 1:1 mapping to the walletrpc types for the anchor change - // output and fee "oneof" fields. - switch change := req.AnchorChangeOutput.(type) { - case *wrpc.CommitVirtualPsbtsRequest_ExistingOutputIndex: - coinSelect.ChangeOutput = &coinSelectExistingIndex{ - ExistingOutputIndex: change.ExistingOutputIndex, - } - - case *wrpc.CommitVirtualPsbtsRequest_Add: - coinSelect.ChangeOutput = &walletrpc.PsbtCoinSelect_Add{ - Add: change.Add, - } - - default: - return nil, fmt.Errorf("unknown change output type") - } - - switch fee := req.Fees.(type) { - case *wrpc.CommitVirtualPsbtsRequest_TargetConf: - fundRequest.Fees = - &walletrpc.FundPsbtRequest_TargetConf{ - TargetConf: fee.TargetConf, - } - - case *wrpc.CommitVirtualPsbtsRequest_SatPerVbyte: - fundRequest.Fees = - &walletrpc.FundPsbtRequest_SatPerVbyte{ - SatPerVbyte: fee.SatPerVbyte, - } - - default: - return nil, fmt.Errorf("unknown fee type") - } - - lndWallet := r.cfg.Lnd.WalletKit - fundedPacket, changeIndex, lockedUTXO, err = lndWallet.FundPsbt( - ctx, fundRequest, - ) - if err != nil { - return nil, fmt.Errorf("error funding packet: %w", err) - } - - lockedOutpoints = fn.Map(lockedUTXO, - func(utxo *walletrpc.UtxoLease) wire.OutPoint { - var hash chainhash.Hash - copy(hash[:], utxo.Outpoint.TxidBytes) - return wire.OutPoint{ - Hash: hash, - Index: utxo.Outpoint.OutputIndex, - } - }, - ) - - // From now on, if we error out, we need to make sure we unlock - // the UTXOs that lnd just locked for us. - defer func() { - if success { - return - } - - for idx, utxo := range lockedUTXO { - var lockID wtxmgr.LockID - copy(lockID[:], utxo.Id) - - op := lockedOutpoints[idx] - err := lndWallet.ReleaseOutput(ctx, lockID, op) - if err != nil { - rpcsLog.Errorf("Error unlocking lnd "+ - "UTXO %v: %v", op, err) - } - } - }() - } - - // We can now update the anchor outputs as we have the final - // commitments. - outputCommitments, err := tapsend.CreateOutputCommitments( - allPackets, tapsend.WithSpenderLeaves(), - ) - if err != nil { - return nil, fmt.Errorf("unable to create new output "+ - "commitments: %w", err) - } - - for _, vPkt := range allPackets { - err = tapsend.UpdateTaprootOutputKeys( - fundedPacket, vPkt, outputCommitments, - ) - if err != nil { - return nil, fmt.Errorf("error updating taproot output "+ - "keys: %w", err) - } - } - - // We're done creating the output commitments, we can now create the - // transition proof suffixes. - for idx := range allPackets { - vPkt := allPackets[idx] - - for vOutIdx := range vPkt.Outputs { - proofSuffix, err := tapsend.CreateProofSuffix( - fundedPacket.UnsignedTx, fundedPacket.Outputs, - vPkt, outputCommitments, vOutIdx, allPackets, - proofOpts..., - ) - if err != nil { - return nil, fmt.Errorf("unable to create "+ - "proof suffix for output %d of vPSBT "+ - "%d: %w", vOutIdx, idx, err) - } - - vPkt.Outputs[vOutIdx].ProofSuffix = proofSuffix - } - } - - // We can now prepare the full answer, beginning with the serialized - // final packet. - response := &wrpc.CommitVirtualPsbtsResponse{ - ChangeOutputIndex: changeIndex, - } - - response.AnchorPsbt, err = fn.Serialize(fundedPacket) - if err != nil { - return nil, fmt.Errorf("error serializing packet: %w", err) - } - - // Serialize the final active and passive virtual packets. - response.VirtualPsbts, err = encodeVirtualPackets(activePackets) - if err != nil { - return nil, fmt.Errorf("error encoding active packets: %w", err) - } - response.PassiveAssetPsbts, err = encodeVirtualPackets(passivePackets) - if err != nil { - return nil, fmt.Errorf("error encoding passive packets: %w", - err) - } - - // And finally, we need to also return the locked UTXOs. We just return - // the outpoint, as any additional information can be fetched from the - // lnd wallet directly (we don't want to create pass-through RPCs for - // all those methods). - response.LndLockedUtxos = make([]*taprpc.OutPoint, len(lockedOutpoints)) - for idx := range lockedOutpoints { - response.LndLockedUtxos[idx] = &taprpc.OutPoint{ - Txid: lockedOutpoints[idx].Hash[:], - OutputIndex: lockedOutpoints[idx].Index, - } - } - - // We were successful, let's cancel the UTXO release in the defer. - success = true - - return response, nil -} - -// validateInputAssets makes sure that the input assets are correct and their -// combined commitments match the inputs of the BTC level anchor transaction. func (r *RPCServer) validateInputAssets(ctx context.Context, btcPkt *psbt.Packet, vPackets []*tappsbt.VPacket) error { @@ -3471,21 +3352,8 @@ func (r *RPCServer) PublishAndLogTransfer(ctx context.Context, err) } - // Before we commit the transaction to the database, we want to make - // sure everything is in order. We start by validating the inputs. allPackets := append([]*tappsbt.VPacket{}, activePackets...) allPackets = append(allPackets, passivePackets...) - err = r.validateInputAssets(ctx, pkt, allPackets) - if err != nil { - return nil, fmt.Errorf("error validating input assets: %w", err) - } - - // And then the outputs as well. - err = tapsend.ValidateAnchorOutputs(pkt, allPackets, true) - if err != nil { - return nil, fmt.Errorf("error validating anchor outputs: %w", - err) - } chainFees, err := pkt.GetTxFee() if err != nil { @@ -3493,14 +3361,40 @@ func (r *RPCServer) PublishAndLogTransfer(ctx context.Context, err) } - // The BTC level transaction must be fully complete, and we must be able - // to extract the final transaction from it. + // Extract the final transaction before input validation. A retry of + // an already-logged anchor must be reconciled even when those inputs + // are now leased or spent, which would fail validation. finalTx, err := psbt.Extract(pkt) if err != nil { return nil, fmt.Errorf("error extracting final anchor "+ "transaction: %w", err) } + anchorHash := finalTx.TxHash() + logged, err := r.cfg.ChainPorter.QueryParcels( + ctx, fn.Some(anchorHash), false, + ) + if err != nil { + return nil, fmt.Errorf("error querying logged transfer: %w", + err) + } + + // Nothing is logged yet, so this is the first publish. Validate + // before the porter writes the transfer. + if len(logged) == 0 { + err = r.validateInputAssets(ctx, pkt, allPackets) + if err != nil { + return nil, fmt.Errorf("error validating input "+ + "assets: %w", err) + } + + err = tapsend.ValidateAnchorOutputs(pkt, allPackets, true) + if err != nil { + return nil, fmt.Errorf("error validating anchor "+ + "outputs: %w", err) + } + } + anchorTx := &tapsend.AnchorTransaction{ FundedPsbt: &tapsend.FundedPsbt{ Pkt: pkt, @@ -3530,18 +3424,17 @@ func (r *RPCServer) PublishAndLogTransfer(ctx context.Context, parcelLabel = req.Label } - // We now have everything to ship the pre-anchored parcel using the - // freighter. This will publish the TX, create the transfer database - // entries and ship the proofs to the counterparties. It'll also wait - // for a confirmation and then update the proofs with the block header - // information. - resp, err := r.cfg.ChainPorter.RequestShipment( - tapfreighter.NewPreAnchoredParcel( - activePackets, passivePackets, anchorTx, - req.SkipAnchorTxBroadcast, parcelLabel, - fn.None[uint32](), - ), + // Ship the pre-anchored parcel. When this anchor is already logged, + // the porter returns that transfer and does not publish it again. + // Otherwise it logs the transfer, publishes, and ships proofs. + preAnchored := tapfreighter.NewPreAnchoredParcel( + activePackets, passivePackets, anchorTx, + req.SkipAnchorTxBroadcast, parcelLabel, + fn.None[uint32](), ) + preAnchored.SetRequestID(req.GetRequestId()) + + resp, err := r.cfg.ChainPorter.RequestShipment(preAnchored) if err != nil { return nil, fmt.Errorf("error requesting delivery: %w", err) } diff --git a/rpcserver/supplysync_rpc.go b/rpcserver/supplysync_rpc.go index 9d721732ab..4becf7f960 100644 --- a/rpcserver/supplysync_rpc.go +++ b/rpcserver/supplysync_rpc.go @@ -3,6 +3,7 @@ package rpcserver import ( "bytes" "context" + "errors" "fmt" "github.com/btcsuite/btcd/wire" @@ -15,6 +16,8 @@ import ( "github.com/lightninglabs/taproot-assets/universe" "github.com/lightninglabs/taproot-assets/universe/supplycommit" "github.com/lightninglabs/taproot-assets/universe/supplyverifier" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) // RpcSupplySync is an implementation of the universe.SupplySyncer interface @@ -102,7 +105,7 @@ func (r *RpcSupplySync) InsertSupplyCommit(ctx context.Context, _, err = r.conn.InsertSupplyCommit(ctx, req) if err != nil { - return fmt.Errorf("unable to insert supply commitment: %w", err) + return mapSupplyInsertErr(err) } srvrLog.Infof("[RpcSupplySync.InsertSupplyCommit]: succeeded in "+ @@ -159,8 +162,7 @@ func (r *RpcSupplySync) FetchSupplyCommit(ctx context.Context, resp, err := r.conn.FetchSupplyCommit(ctx, req) if err != nil { - return zero, fmt.Errorf("unable to fetch supply commitment: %w", - err) + return zero, mapSupplyFetchErr(err) } // Unmarshal the chain data to get the root commitment. @@ -260,6 +262,54 @@ func (r *RpcSupplySync) Close() error { return nil } +// insertSupplyCommitStatus maps a supply-commit insert error onto a +// gRPC status. FailedPrecondition is reserved for a missing predecessor +// (ErrPrevCommitmentNotFound) and is not used for any other outcome of +// this RPC. The sync client maps that code back to the sentinel. +func insertSupplyCommitStatus(err error) error { + if errors.Is(err, supplyverifier.ErrPrevCommitmentNotFound) { + return status.Errorf(codes.FailedPrecondition, + "failed to insert supply commitment: %v", err) + } + + return fmt.Errorf("failed to insert supply commitment: %w", err) +} + +// fetchSupplyCommitStatus maps a supply-commit fetch error onto a gRPC +// status. NotFound is reserved for an absent commitment +// (ErrCommitmentNotFound). The sync client maps that code back to the +// sentinel so a miss is not retried as a transient failure. +func fetchSupplyCommitStatus(err error) error { + if errors.Is(err, supplyverifier.ErrCommitmentNotFound) { + return status.Errorf(codes.NotFound, + "failed to fetch supply commit: %v", err) + } + + return fmt.Errorf("failed to fetch supply commit: %w", err) +} + +// mapSupplyInsertErr converts the InsertSupplyCommit RPC error into a +// local error. Detection uses the status code, not the message text. +func mapSupplyInsertErr(err error) error { + if status.Code(err) == codes.FailedPrecondition { + return fmt.Errorf("unable to insert supply commitment: %w", + supplyverifier.ErrPrevCommitmentNotFound) + } + + return fmt.Errorf("unable to insert supply commitment: %w", err) +} + +// mapSupplyFetchErr converts the FetchSupplyCommit RPC error into a +// local error. Detection uses the status code, not the message text. +func mapSupplyFetchErr(err error) error { + if status.Code(err) == codes.NotFound { + return fmt.Errorf("unable to fetch supply commitment: %w", + supplyverifier.ErrCommitmentNotFound) + } + + return fmt.Errorf("unable to fetch supply commitment: %w", err) +} + // marshalSupplyCommitChainData converts a supplycommit.RootCommitment and // supplycommit.ChainProof into a combined RPC SupplyCommitChainData. func marshalSupplyCommitChainData( diff --git a/rpcserver/supplysync_rpc_test.go b/rpcserver/supplysync_rpc_test.go new file mode 100644 index 0000000000..178c040a8d --- /dev/null +++ b/rpcserver/supplysync_rpc_test.go @@ -0,0 +1,63 @@ +package rpcserver + +import ( + "errors" + "fmt" + "testing" + + "github.com/lightninglabs/taproot-assets/universe/supplyverifier" + "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// TestSupplyCommitStatusMapping pins the RPC boundary the syncer uses +// to recognize a missing predecessor and a missing commitment. The +// status code is the signal. A message that only looks like the +// sentinel, under a different code, must not be rewritten into it. +func TestSupplyCommitStatusMapping(t *testing.T) { + t.Parallel() + + prev := fmt.Errorf("supply commitment verification failed: %w", + supplyverifier.ErrPrevCommitmentNotFound) + got := insertSupplyCommitStatus(prev) + require.Equal(t, codes.FailedPrecondition, status.Code(got)) + + mapped := mapSupplyInsertErr(got) + require.ErrorIs(t, mapped, supplyverifier.ErrPrevCommitmentNotFound) + + lookalike := status.Error(codes.Unknown, + "previous supply commitment not found") + mapped = mapSupplyInsertErr(lookalike) + require.NotErrorIs( + t, mapped, supplyverifier.ErrPrevCommitmentNotFound, + ) + + other := insertSupplyCommitStatus(errors.New("boom")) + require.Equal(t, codes.Unknown, status.Code(other)) + require.NotErrorIs( + t, mapSupplyInsertErr(other), + supplyverifier.ErrPrevCommitmentNotFound, + ) + + missing := fmt.Errorf("unable to fetch commitment: %w", + supplyverifier.ErrCommitmentNotFound) + got = fetchSupplyCommitStatus(missing) + require.Equal(t, codes.NotFound, status.Code(got)) + require.ErrorIs( + t, mapSupplyFetchErr(got), supplyverifier.ErrCommitmentNotFound, + ) + + // NotFound is not the missing-predecessor signal, even when the + // text names that sentinel. + notPrev := status.Error(codes.NotFound, + "previous supply commitment not found") + require.NotErrorIs( + t, mapSupplyInsertErr(notPrev), + supplyverifier.ErrPrevCommitmentNotFound, + ) + require.ErrorIs( + t, mapSupplyFetchErr(notPrev), + supplyverifier.ErrCommitmentNotFound, + ) +} diff --git a/sample-tapd.conf b/sample-tapd.conf index bb3abef038..33a480fd5b 100644 --- a/sample-tapd.conf +++ b/sample-tapd.conf @@ -392,6 +392,17 @@ ; LRU cache. ; universe.supply-ignore-cache-size=10000 +; The number of blocks after which tapd automatically publishes an +; ancestry-linked successor supply commitment for a locally controlled asset +; group whose latest supply commitment has confirmed, even if there were no new +; supply updates. Set to 0 to disable. When enabled, must be at least 1 block. +; universe.supply-idle-commit-interval=0 + +; If set, tapd automatically publishes pending supply updates (for example +; ignored outpoints) when the next block arrives, instead of waiting for a +; manual UpdateSupplyCommit call. +; universe.supply-auto-publish-pending=false + ; Disable chain outpoint watching in supply verifier. If true, the supply ; verifier will not start state machines to watch on-chain outputs for spends. ; This option is intended for universe servers, where supply verification should diff --git a/scripts/itest_parallel.sh b/scripts/itest_parallel.sh index ab1b3efa28..99694775b4 100755 --- a/scripts/itest_parallel.sh +++ b/scripts/itest_parallel.sh @@ -11,28 +11,29 @@ shift 3 # Create a variable to hold the final exit code. exit_code=0 -# Run commands using xargs in parallel and capture their PIDs -pids=() -for ((i=0; i 0 { + log.Infof("Anchor transaction %v already logged as "+ + "transfer id=%d; not inserting another row", + newAnchorTXID, existing[0].ID) + + return nil + } + + anchorTxBytes, err := fn.Serialize(spend.AnchorTx) + if err != nil { + return err + } + + // First, we'll insert the new transaction that anchors the new + // anchor point (commits to the set of new outputs). + txnID, err := q.UpsertChainTx(ctx, ChainTxParams{ + Txid: newAnchorTXID[:], + RawTx: anchorTxBytes, + ChainFees: spend.ChainFees, + }) + if err != nil { + return fmt.Errorf("unable to insert new chain tx: %w", err) + } + + // The transfer itself is just a shell which the inputs and + // outputs will reference. We'll insert this next, so we can use + // its ID. + transferID, err := q.InsertAssetTransfer(ctx, NewAssetTransfer{ + HeightHint: int32(spend.AnchorTxHeightHint), + AnchorTxid: newAnchorTXID[:], + TransferTimeUnix: spend.TransferTime, + Label: sqlStr(spend.Label), + SkipAnchorTxBroadcast: spend.SkipAnchorTxBroadcast, + }) + if err != nil { + return fmt.Errorf("unable to insert asset transfer: %w", err) + } + + // Next, we'll insert the inputs to this transfer. + for idx := range spend.Inputs { + err := insertAssetTransferInput( + ctx, q, transferID, spend.Inputs[idx], + finalLeaseOwner, finalLeaseExpiry, + ) + if err != nil { + return fmt.Errorf("unable to insert asset transfer "+ + "input: %w", err) + } + } + + // Also extend leases for any zero-value UTXOs being swept. + for _, zeroValueInput := range spend.ZeroValueInputs { + outpointBytes, err := encodeOutpoint(zeroValueInput.OutPoint) + if err != nil { + return fmt.Errorf("unable to encode zero-value "+ + "outpoint: %w", err) + } + + err = q.UpdateUTXOLease(ctx, UpdateUTXOLease{ + LeaseOwner: finalLeaseOwner[:], + LeaseExpiry: sqlTime(finalLeaseExpiry.UTC()), + Outpoint: outpointBytes, + }) + if err != nil { + return fmt.Errorf("unable to extend zero-value "+ + "UTXO lease: %w", err) + } + } + + // Then the passive assets. + if len(spend.PassiveAssets) > 0 { + if spend.PassiveAssetsAnchor == nil { + return fmt.Errorf("passive assets anchor is required") + } + + err = insertPassiveAssets( + ctx, q, transferID, txnID, spend.PassiveAssetsAnchor, + spend.PassiveAssets, + ) + if err != nil { + return fmt.Errorf("unable to insert passive "+ + "assets: %w", err) + } + } + + // And then finally the outputs. + for idx := range spend.Outputs { + err = insertAssetTransferOutput( + ctx, q, transferID, txnID, spend.Outputs[idx], + ) + if err != nil { + return fmt.Errorf("unable to insert asset transfer "+ + "output: %w", err) + } + } + + return nil +} + +func (a *AssetStore) rebuildAnchorConfirm(ctx context.Context, + q ActiveAssetsStore, anchorTx *wire.MsgTx, blockHash chainhash.Hash, + blockHeight, txIndex uint32, header wire.BlockHeader, + merkle proof.TxMerkleProof, + burnNote string) (*tapfreighter.AssetConfirmEvent, + []*tapfreighter.AssetBurn, error) { + + anchorTxid := anchorTx.TxHash() + + assetTransfers, err := q.QueryAssetTransfers(ctx, TransferQuery{ + AnchorTxHash: anchorTxid[:], + }) + if err != nil { + return nil, nil, fmt.Errorf("unable to query asset "+ + "transfers: %w", err) + } + if len(assetTransfers) == 0 { + return nil, nil, fmt.Errorf("no transfer found for anchor "+ + "tx %v", anchorTxid) + } + assetTransfer := assetTransfers[0] + + inputs, err := q.FetchTransferInputs(ctx, assetTransfer.ID) + if err != nil { + return nil, nil, fmt.Errorf("unable to fetch transfer "+ + "inputs: %w", err) + } + outputs, err := q.FetchTransferOutputs(ctx, assetTransfer.ID) + if err != nil { + return nil, nil, fmt.Errorf("unable to fetch transfer "+ + "outputs: %w", err) + } + + // Decode the transfer's inputs into their previous IDs. Each + // output picks out its own inputs from these below, by witness + // reference: an anchor transaction can carry several independent + // same-asset transitions (aggregated sweeps), so grouping by + // asset ID alone would staple a suffix onto an unrelated input's + // file. + inputPrevIDs := make([]asset.PrevID, 0, len(inputs)) + for idx := range inputs { + in := inputs[idx] + + var op wire.OutPoint + err := readOutPoint( + bytes.NewReader(in.AnchorPoint), 0, 0, &op, + ) + if err != nil { + return nil, nil, fmt.Errorf("unable to decode "+ + "input anchor point: %w", err) + } + + var assetID asset.ID + copy(assetID[:], in.AssetID) + + var scriptKey asset.SerializedKey + copy(scriptKey[:], in.ScriptKey) + + inputPrevIDs = append(inputPrevIDs, asset.PrevID{ + OutPoint: op, + ID: assetID, + ScriptKey: scriptKey, + }) + } + + // Rebuild the zero-value sweep set. The live confirmation event + // carries the funding step's selection out of porter memory; the + // rebuilt event must derive the same set, or the confirmation + // application never marks the swept anchors and coin selection + // can fund a later transfer with an outpoint this transaction + // already spent, once the sweep lease expires. The set is + // recoverable from stored state: a zero-value sweep is an + // anchor-transaction input that carries a managed-UTXO row but + // is not one of the transfer's asset inputs (wallet-funded fee + // inputs have no managed row). Only the outpoint is rebuilt — + // it is all the confirmation application consumes; the remaining + // fields serve funding-time signing. + inputAnchors := make(map[wire.OutPoint]struct{}, len(inputPrevIDs)) + for _, prevID := range inputPrevIDs { + inputAnchors[prevID.OutPoint] = struct{}{} + } + + var zeroValueInputs []*tapfreighter.ZeroValueInput + for _, txIn := range anchorTx.TxIn { + op := txIn.PreviousOutPoint + if _, ok := inputAnchors[op]; ok { + continue + } + + outpointBytes, err := encodeOutpoint(op) + if err != nil { + return nil, nil, fmt.Errorf("unable to encode "+ + "anchor input outpoint: %w", err) + } + + _, err = q.FetchManagedUTXO(ctx, UtxoQuery{ + Outpoint: outpointBytes, + }) + switch { + case errors.Is(err, sql.ErrNoRows): + continue + + case err != nil: + return nil, nil, fmt.Errorf("unable to look up "+ + "managed UTXO for anchor input %v: %w", op, + err) + } + + zeroValueInputs = append( + zeroValueInputs, &tapfreighter.ZeroValueInput{ + OutPoint: op, + }, + ) + } + + // fetchInputFile loads an input's full proof file from the + // database by its previous ID. + fetchInputFile := func(prevID asset.PrevID) (*proof.File, error) { + outpointBytes, err := encodeOutpoint(prevID.OutPoint) + if err != nil { + return nil, err + } + + rows, err := q.FetchAssetProof( + ctx, sqlc.FetchAssetProofParams{ + TweakedScriptKey: prevID.ScriptKey[:], + Outpoint: outpointBytes, + AssetID: prevID.ID[:], + }, + ) + if err != nil { + return nil, fmt.Errorf("unable to fetch input "+ + "proof: %w", err) + } + if len(rows) == 0 { + return nil, fmt.Errorf("no input proof for %v", + prevID.OutPoint) + } + + file := &proof.File{} + err = file.Decode(bytes.NewReader(rows[0].ProofFile)) + if err != nil { + return nil, fmt.Errorf("unable to decode input "+ + "proof file: %w", err) + } + + return file, nil + } + + var ( + finalProofs = make( + map[tapfreighter.OutputIdentifier]*proof.AnnotatedProof, + len(outputs), + ) + burns []*tapfreighter.AssetBurn + ) + for idx := range outputs { + out := outputs[idx] + if len(out.ProofSuffix) == 0 { + continue + } + + suffix := &proof.Proof{} + err := suffix.Decode(bytes.NewReader(out.ProofSuffix)) + if err != nil { + return nil, nil, fmt.Errorf("unable to decode "+ + "proof suffix: %w", err) + } + + // Stamp the witness's block context onto the suffix; this + // is exactly what confirmation adds to the pre-broadcast + // suffix. + suffix.AnchorTx = *anchorTx + suffix.BlockHeader = header + suffix.BlockHeight = blockHeight + suffix.TxMerkleProof = merkle + + // The output's full proof file is its primary input's + // file with the suffix appended, and any additional + // inputs' files attached to the suffix. Which inputs + // those are is determined by the suffix's own witnesses + // (resolved through the split commitment root where + // applicable), exactly as at pre-broadcast verification. + assetID := suffix.Asset.ID() + witnesses := suffix.Asset.Witnesses() + var prevIDs []asset.PrevID + for _, in := range inputPrevIDs { + for _, witness := range witnesses { + if witness.PrevID != nil && + in == *witness.PrevID { + + prevIDs = append(prevIDs, in) + } + } + } + if len(prevIDs) == 0 { + return nil, nil, fmt.Errorf("no inputs found for "+ + "output asset %v", assetID) + } + + // Burn leaves are verified without a prior snapshot, so + // they need every input file, including the primary. + // Collected here, before the primary file is extended + // with this suffix, and not written onto the suffix the + // transfer proof file stores. + var burnInputs map[asset.PrevID]*proof.File + if suffix.Asset.IsBurn() { + burnInputs = make( + map[asset.PrevID]*proof.File, len(prevIDs), + ) + } + + for extra := 1; extra < len(prevIDs); extra++ { + extraFile, err := fetchInputFile(prevIDs[extra]) + if err != nil { + return nil, nil, err + } + if burnInputs != nil { + _, seen := burnInputs[prevIDs[extra]] + if !seen { + burnInputs[prevIDs[extra]] = extraFile + } + } + suffix.AdditionalInputs = append( + suffix.AdditionalInputs, *extraFile, + ) + } + + file, err := fetchInputFile(prevIDs[0]) + if err != nil { + return nil, nil, err + } + if burnInputs != nil { + cloned, err := tapfreighter.CloneProofFile(file) + if err != nil { + return nil, nil, fmt.Errorf("unable to copy "+ + "burn input proof: %w", err) + } + burnInputs[prevIDs[0]] = cloned + } + if err := file.AppendProof(*suffix); err != nil { + return nil, nil, fmt.Errorf("unable to append "+ + "proof: %w", err) + } + var blob bytes.Buffer + if err := file.Encode(&blob); err != nil { + return nil, nil, fmt.Errorf("unable to encode "+ + "proof file: %w", err) + } + + fullScriptKey, err := parseScriptKey( + out.InternalKey, out.ScriptKey, + ) + if err != nil { + return nil, nil, fmt.Errorf("unable to decode "+ + "script key: %w", err) + } + scriptPubKey := fullScriptKey.PubKey + + outKey := tapfreighter.NewOutputIdentifier( + assetID, suffix.InclusionProof.OutputIndex, + *scriptPubKey, + ) + finalProofs[outKey] = &proof.AnnotatedProof{ + Locator: proof.Locator{ + AssetID: &assetID, + ScriptKey: *scriptPubKey, + OutPoint: fn.Ptr(suffix.OutPoint()), + }, + Blob: blob.Bytes(), + } + + // Burns are recognizable from the suffix itself. The + // leaf proof is a copy that embeds input provenance; + // the suffix stored in the transfer proof file is left + // as the chain built above. + if suffix.Asset.IsBurn() { + burnProof, err := tapfreighter.BurnLeafProof(suffix, burnInputs) + if err != nil { + return nil, nil, fmt.Errorf("unable to "+ + "build burn proof: %w", err) + } + + burn := &tapfreighter.AssetBurn{ + Note: burnNote, + AssetID: assetID[:], + AssetType: suffix.Asset.Type, + Amount: uint64(out.Amount), + //nolint:lll + AnchorTxid: anchorTxid, + ScriptKey: &suffix.Asset.ScriptKey, + Proof: burnProof, + OutPoint: wire.OutPoint{ + Hash: anchorTxid, + //nolint:lll + Index: suffix.InclusionProof.OutputIndex, + }, + } + if suffix.Asset.GroupKey != nil { + groupKey := suffix.Asset.GroupKey.GroupPubKey + burn.GroupKey = groupKey. + SerializeCompressed() + } + + burns = append(burns, burn) + } + } + + passiveFiles := make(map[asset.ID][]*proof.AnnotatedProof) + + conf := &tapfreighter.AssetConfirmEvent{ + AnchorTXID: anchorTxid, + BlockHash: blockHash, + BlockHeight: int32(blockHeight), + TxIndex: int32(txIndex), + FinalProofs: finalProofs, + PassiveAssetProofFiles: passiveFiles, + ZeroValueInputs: zeroValueInputs, + } + + return conf, burns, nil +} + +// RebuildConfirmEvent is RebuildAnchorConfirm inside a read +// transaction of its own, for callers outside the watcher's delivery +// path (the porter's proof-file mirroring and burn-event dispatch). +func (a *AssetStore) RebuildConfirmEvent(ctx context.Context, + anchorTx *wire.MsgTx, blockHash chainhash.Hash, + blockHeight, txIndex uint32, header wire.BlockHeader, + merkle proof.TxMerkleProof, + burnNote string) (*tapfreighter.AssetConfirmEvent, + []*tapfreighter.AssetBurn, error) { + + var ( + conf *tapfreighter.AssetConfirmEvent + burns []*tapfreighter.AssetBurn + ) + readOpts := NewAssetStoreReadTx() + dbErr := a.db.ExecTx(ctx, &readOpts, func(q ActiveAssetsStore) error { + var err error + conf, burns, err = a.rebuildAnchorConfirm( + ctx, q, anchorTx, blockHash, blockHeight, txIndex, + header, merkle, burnNote, + ) + + return err + }) + if dbErr != nil { + return nil, nil, dbErr + } + + return conf, burns, nil +} diff --git a/tapdb/assets_store.go b/tapdb/assets_store.go index d8cd6edeaa..ad49d0d7ae 100644 --- a/tapdb/assets_store.go +++ b/tapdb/assets_store.go @@ -2921,6 +2921,25 @@ func (a *AssetStore) LogPendingParcel(ctx context.Context, var writeTxOpts AssetStoreTxOptions return a.db.ExecTx(ctx, &writeTxOpts, func(q ActiveAssetsStore) error { + // A retry of the same anchor (a lost PublishAndLogTransfer + // response, or a second porter entry for that anchor) must not + // insert another asset_transfers row. chain_txns.txid is unique, + // but asset_transfers.anchor_txn_id is not. + existing, err := q.QueryAssetTransfers(ctx, TransferQuery{ + AnchorTxHash: newAnchorTXID[:], + }) + if err != nil { + return fmt.Errorf("unable to query existing transfer: %w", + err) + } + if len(existing) > 0 { + log.Infof("Anchor transaction %v already logged as "+ + "transfer id=%d; not inserting another row", + newAnchorTXID, existing[0].ID) + + return nil + } + // First, we'll insert the new transaction that anchors the new // anchor point (commits to the set of new outputs). txnID, err := q.UpsertChainTx(ctx, ChainTxParams{ diff --git a/tapdb/assets_store_test.go b/tapdb/assets_store_test.go index be25c11607..1314133f45 100644 --- a/tapdb/assets_store_test.go +++ b/tapdb/assets_store_test.go @@ -2305,6 +2305,18 @@ func TestAssetExportLog(t *testing.T) { ctx, spendDelta, leaseOwner, leaseExpiry, )) + // A second log of the same anchor is how a lost + // PublishAndLogTransfer response is retried. It must not insert + // another asset_transfers row. + require.NoError(t, assetsStore.LogPendingParcel( + ctx, spendDelta, leaseOwner, leaseExpiry, + )) + loggedTwice, err := db.QueryAssetTransfers(ctx, TransferQuery{ + AnchorTxHash: anchorTxHash[:], + }) + require.NoError(t, err) + require.Len(t, loggedTwice, 1) + assetID := inputAsset.ID() receiverIdentifier := tapfreighter.NewOutputIdentifier( assetID, 0, *newScriptKey.PubKey, @@ -2626,6 +2638,61 @@ func TestAssetGroupComplexWitness(t *testing.T) { require.True(t, groupKey.IsEqual(storedGroup.GroupKey)) } +// TestGroupKeyUpsertAfterPlaceholderImport verifies the default proof and +// universe import order: a raw-key-only placeholder can be inserted first, +// then a grouped mint can resolve the same stable key ID without granting the +// generic upsert path authority to change its locator. +func TestGroupKeyUpsertAfterPlaceholderImport(t *testing.T) { + t.Parallel() + + _, assetStore, db := newAssetStore(t) + ctx := context.Background() + internalKey := test.RandPubKey(t) + rawKey := internalKey.SerializeCompressed() + + placeholderID, err := db.UpsertInternalKey(ctx, InternalKey{ + RawKey: rawKey, + }) + require.NoError(t, err) + + groupAnchorGen := asset.RandGenesis(t, asset.Normal) + groupAnchorGen.MetaHash = [32]byte{} + genesisPointID, err := upsertGenesisPoint( + ctx, db, groupAnchorGen.FirstPrevOut, + ) + require.NoError(t, err) + genAssetID, err := upsertGenesis( + ctx, db, genesisPointID, groupAnchorGen, + ) + require.NoError(t, err) + + groupKey := asset.GroupKey{ + RawKey: keychain.KeyDescriptor{ + KeyLocator: keychain.KeyLocator{ + Family: 212, + Index: 721, + }, + PubKey: internalKey, + }, + GroupPubKey: *internalKey, + } + _, err = upsertGroupKey( + ctx, &groupKey, assetStore.db, genesisPointID, genAssetID, + ) + require.NoError(t, err) + + resolvedID, err := db.UpsertInternalKey(ctx, InternalKey{ + RawKey: rawKey, KeyFamily: int32(groupKey.RawKey.Family), + KeyIndex: int32(groupKey.RawKey.Index), + }) + require.NoError(t, err) + require.Equal(t, placeholderID, resolvedID) + locator, err := db.FetchInternalKeyLocator(ctx, rawKey) + require.NoError(t, err) + require.Zero(t, locator.KeyFamily) + require.Zero(t, locator.KeyIndex) +} + // TestStoreFetchAssetGroupV1 tests that we can store and fetch an asset group // version 1. func TestStoreFetchAssetGroupV1(t *testing.T) { diff --git a/tapdb/burn_leaf_proof_test.go b/tapdb/burn_leaf_proof_test.go new file mode 100644 index 0000000000..9e86dbb444 --- /dev/null +++ b/tapdb/burn_leaf_proof_test.go @@ -0,0 +1,526 @@ +package tapdb + +import ( + "bytes" + "context" + "database/sql" + "math/rand" + "testing" + "time" + + "github.com/btcsuite/btcd/chaincfg/chainhash" + "github.com/btcsuite/btcd/wire" + "github.com/lightninglabs/taproot-assets/asset" + "github.com/lightninglabs/taproot-assets/fn" + "github.com/lightninglabs/taproot-assets/internal/test" + "github.com/lightninglabs/taproot-assets/mssmt" + "github.com/lightninglabs/taproot-assets/proof" + "github.com/lightninglabs/taproot-assets/tapdb/sqlc" + "github.com/lightninglabs/taproot-assets/tapfreighter" + "github.com/lightningnetwork/lnd/keychain" + "github.com/stretchr/testify/require" +) + +// prevProofFile builds a one-proof file and the prev ID its tip +// satisfies. +func prevProofFile(t *testing.T) (*proof.File, asset.PrevID) { + t.Helper() + + a := asset.RandAsset(t, asset.Normal) + p := randProof(t, a) + file, err := proof.NewFile(proof.V0, *p) + require.NoError(t, err) + + prevID := asset.PrevID{ + OutPoint: p.OutPoint(), + ID: a.ID(), + ScriptKey: asset.ToSerialized( + a.ScriptKey.PubKey, + ), + } + + return file, prevID +} + +// suffixSpending builds a transition proof whose witnesses spend the +// given inputs. split places those witnesses on the split root, which +// is where a split burn records them. +func suffixSpending(t *testing.T, prevIDs []asset.PrevID, + split bool) *proof.Proof { + + t.Helper() + + witnesses := make([]asset.Witness, len(prevIDs)) + for i := range prevIDs { + id := prevIDs[i] + witnesses[i] = asset.Witness{PrevID: &id} + } + + gen := asset.RandGenesis(t, asset.Normal) + burnAsset := asset.RandAssetWithValues( + t, gen, nil, asset.RandScriptKey(t), + ) + if split { + root := burnAsset.Copy() + root.PrevWitnesses = witnesses + + emptyNodes := make([]mssmt.Node, mssmt.MaxTreeLevels) + for i := range emptyNodes { + emptyNodes[i] = mssmt.EmptyTree[mssmt.MaxTreeLevels-i] + } + + burnAsset.PrevWitnesses = []asset.Witness{{ + PrevID: &asset.PrevID{}, + SplitCommitment: &asset.SplitCommitment{ + Proof: *mssmt.NewProof(emptyNodes), + RootAsset: *root, + }, + }} + } else { + burnAsset.PrevWitnesses = witnesses + } + + suffix := randProof(t, burnAsset) + suffix.BlockHeight = 1234 + // A timestamp that fits in the header's uint32 field, so an + // encode/decode round trip preserves it. + suffix.BlockHeader = wire.BlockHeader{ + Nonce: 7, + Timestamp: time.Unix(1_700_000_000, 0), + } + suffix.AdditionalInputs = nil + + return suffix +} + +// TestBurnLeafProof checks that the burn leaf embeds every spent input +// and leaves the suffix it was built from alone. +func TestBurnLeafProof(t *testing.T) { + t.Parallel() + + for _, tc := range []struct { + name string + numInputs int + split bool + }{ + {name: "single input", numInputs: 1}, + {name: "multiple inputs", numInputs: 3}, + {name: "split burn", numInputs: 2, split: true}, + } { + t.Run(tc.name, func(t *testing.T) { + files := make(map[asset.PrevID]*proof.File) + prevIDs := make([]asset.PrevID, 0, tc.numInputs) + for i := 0; i < tc.numInputs; i++ { + file, prevID := prevProofFile(t) + files[prevID] = file + prevIDs = append(prevIDs, prevID) + } + + // An unspent input must not be embedded. + extra, extraID := prevProofFile(t) + files[extraID] = extra + + suffix := suffixSpending(t, prevIDs, tc.split) + var before bytes.Buffer + require.NoError(t, suffix.Encode(&before)) + + burnProof, err := tapfreighter.BurnLeafProof(suffix, files) + require.NoError(t, err) + + require.EqualValues(t, 1234, burnProof.BlockHeight) + require.Equal( + t, suffix.BlockHeader.Nonce, + burnProof.BlockHeader.Nonce, + ) + require.Equal( + t, suffix.BlockHeader.Timestamp.Unix(), + burnProof.BlockHeader.Timestamp.Unix(), + ) + require.Len( + t, burnProof.AdditionalInputs, tc.numInputs, + ) + for _, in := range burnProof.AdditionalInputs { + require.Equal(t, 1, in.NumProofs()) + } + + var encoded bytes.Buffer + require.NoError(t, burnProof.Encode(&encoded)) + require.Less( + t, encoded.Len(), proof.FileMaxProofSizeBytes, + ) + + var decoded proof.Proof + require.NoError(t, decoded.Decode( + bytes.NewReader(encoded.Bytes()), + )) + require.Len( + t, decoded.AdditionalInputs, tc.numInputs, + ) + + var after bytes.Buffer + require.NoError(t, suffix.Encode(&after)) + require.Equal(t, before.Bytes(), after.Bytes()) + require.Empty(t, suffix.AdditionalInputs) + }) + } +} + +// TestBurnLeafProofSize records encoded leaf sizes and keeps them +// under the single-proof limit. Embedding the primary input grows the +// leaf by about one input file, not by a second copy of the leaf. +func TestBurnLeafProofSize(t *testing.T) { + t.Parallel() + + for _, numInputs := range []int{1, 3, 5} { + files := make(map[asset.PrevID]*proof.File) + prevIDs := make([]asset.PrevID, 0, numInputs) + for i := 0; i < numInputs; i++ { + file, prevID := prevProofFile(t) + files[prevID] = file + prevIDs = append(prevIDs, prevID) + } + + suffix := suffixSpending(t, prevIDs, false) + var bare bytes.Buffer + require.NoError(t, suffix.Encode(&bare)) + + burnProof, err := tapfreighter.BurnLeafProof(suffix, files) + require.NoError(t, err) + + var encoded bytes.Buffer + require.NoError(t, burnProof.Encode(&encoded)) + t.Logf("burn leaf size num_inputs=%d bare=%d leaf=%d", + numInputs, bare.Len(), encoded.Len()) + + require.Greater(t, encoded.Len(), bare.Len()) + require.Less(t, encoded.Len(), proof.FileMaxProofSizeBytes) + } +} + +// TestBurnLeafProofErrors tests the closed failure modes. +func TestBurnLeafProofErrors(t *testing.T) { + t.Parallel() + + file, prevID := prevProofFile(t) + files := map[asset.PrevID]*proof.File{prevID: file} + suffix := suffixSpending(t, []asset.PrevID{prevID}, false) + + t.Run("nil suffix", func(t *testing.T) { + _, err := tapfreighter.BurnLeafProof(nil, files) + require.ErrorContains(t, err, "suffix is nil") + }) + + t.Run("duplicate witness", func(t *testing.T) { + dup := suffixSpending( + t, []asset.PrevID{prevID, prevID}, false, + ) + _, err := tapfreighter.BurnLeafProof(dup, files) + require.ErrorContains(t, err, "duplicate burn input") + }) + + t.Run("missing input", func(t *testing.T) { + _, err := tapfreighter.BurnLeafProof(suffix, map[asset.PrevID]*proof.File{}) + require.ErrorContains(t, err, "missing proof") + }) + + t.Run("empty input", func(t *testing.T) { + empty := map[asset.PrevID]*proof.File{ + prevID: proof.NewEmptyFile(proof.V0), + } + _, err := tapfreighter.BurnLeafProof(suffix, empty) + require.ErrorContains(t, err, "empty proof") + }) + + t.Run("mismatched input", func(t *testing.T) { + other, _ := prevProofFile(t) + _, err := tapfreighter.BurnLeafProof(suffix, map[asset.PrevID]*proof.File{ + prevID: other, + }) + require.ErrorContains(t, err, "proof mismatch") + }) +} + +// TestRebuildBurnLeafEmbedsInputProvenance drives a burn transfer +// through the porter rebuild. The burn leaf must carry the spent +// input, and the stored proof file must still keep that input as its +// prefix rather than an additional input. +func TestRebuildBurnLeafEmbedsInputProvenance(t *testing.T) { + t.Parallel() + + db := NewTestDB(t) + _, assetsStore := newAssetStoreFromDB(db.BaseDB) + ctx := context.Background() + + executor := NewTransactionExecutor( + db, func(tx *sql.Tx) *sqlc.Queries { + return db.WithTx(tx) + }, + ) + + targetScriptKey := asset.NewScriptKeyBip86(keychain.KeyDescriptor{ + PubKey: test.RandPubKey(t), + KeyLocator: keychain.KeyLocator{ + Family: test.RandInt[keychain.KeyFamily](), + Index: uint32(test.RandInt[int32]()), + }, + }) + + assetGen := newAssetGenerator(t, 1, 1) + assetGen.genAssets(t, assetsStore, []assetDesc{{ + assetGen: assetGen.assetGens[0], + anchorPoint: assetGen.anchorPoints[0], + scriptKey: &targetScriptKey, + amt: 16, + }}) + + allAssets, err := assetsStore.FetchAllAssets(ctx, true, false, nil) + require.NoError(t, err) + require.Len(t, allAssets, 1) + inputAsset := allAssets[0] + assetID := inputAsset.ID() + + inputAnchorPoint := wire.OutPoint{ + Hash: assetGen.anchorTxs[0].TxHash(), + Index: 0, + } + inputPrevID := asset.PrevID{ + OutPoint: inputAnchorPoint, + ID: assetID, + ScriptKey: asset.ToSerialized( + inputAsset.ScriptKey.PubKey, + ), + } + + // The file the rebuild fetches. Its tip must be the spent + // input, or the leaf is rejected as mismatched provenance. + inputProof := randProof(t, inputAsset.Asset) + inputProof.AnchorTx = *assetGen.anchorTxs[0] + inputProof.InclusionProof.OutputIndex = 0 + inputFile, err := proof.NewFile(proof.V0, *inputProof) + require.NoError(t, err) + var inputFileBuf bytes.Buffer + require.NoError(t, inputFile.Encode(&inputFileBuf)) + + var inputAssetDBID int64 + err = db.DB.QueryRowContext( + ctx, "SELECT assets.asset_id FROM assets "+ + "JOIN script_keys ON assets.script_key_id = "+ + "script_keys.script_key_id "+ + "WHERE script_keys.tweaked_script_key = $1", + inputAsset.ScriptKey.PubKey.SerializeCompressed(), + ).Scan(&inputAssetDBID) + require.NoError(t, err) + require.NoError(t, db.UpsertAssetProofByID(ctx, ProofUpdateByID{ + AssetID: inputAssetDBID, + ProofFile: inputFileBuf.Bytes(), + })) + + newAnchorTx := wire.NewMsgTx(2) + newAnchorTx.AddTxIn(&wire.TxIn{PreviousOutPoint: inputAnchorPoint}) + newAnchorTx.AddTxOut(&wire.TxOut{ + PkScript: bytes.Repeat([]byte{0x01}, 34), + Value: 1000, + }) + newAnchorTx.AddTxOut(&wire.TxOut{ + PkScript: bytes.Repeat([]byte{0x02}, 34), + Value: 1000, + }) + anchorTxHash := newAnchorTx.TxHash() + + const burnAmt = 6 + burnKey := asset.NewScriptKey(asset.DeriveBurnKey(inputPrevID)) + burnAsset := inputAsset.Copy() + burnAsset.ScriptKey = burnKey + burnAsset.Amount = burnAmt + burnAsset.PrevWitnesses = []asset.Witness{{ + PrevID: &inputPrevID, + TxWitness: [][]byte{{0x01}}, + }} + require.True(t, burnAsset.IsBurn()) + burnSuffix := randProof(t, burnAsset) + burnSuffixBytes, err := burnSuffix.Bytes() + require.NoError(t, err) + + changeKey := asset.NewScriptKeyBip86(keychain.KeyDescriptor{ + PubKey: test.RandPubKey(t), + KeyLocator: keychain.KeyLocator{ + Index: uint32(rand.Int31()), + Family: keychain.KeyFamily(rand.Int31()), + }, + }) + changeAsset := inputAsset.Copy() + changeAsset.ScriptKey = changeKey + changeAsset.Amount = inputAsset.Amount - burnAmt + changeAsset.PrevWitnesses = []asset.Witness{{ + PrevID: &inputPrevID, + TxWitness: [][]byte{{0x01}}, + }} + require.False(t, changeAsset.IsBurn()) + changeSuffix := randProof(t, changeAsset) + changeSuffixBytes, err := changeSuffix.Bytes() + require.NoError(t, err) + + rootHash := [32]byte{0x10} + makeAnchor := func(index uint32, script byte) tapfreighter.Anchor { + return tapfreighter.Anchor{ + Value: 1000, + OutPoint: wire.OutPoint{ + Hash: anchorTxHash, + Index: index, + }, + InternalKey: keychain.KeyDescriptor{ + PubKey: test.RandPubKey(t), + KeyLocator: keychain.KeyLocator{ + Family: keychain.KeyFamily( + rand.Int31(), + ), + Index: uint32(test.RandInt[int32]()), + }, + }, + TaprootAssetRoot: bytes.Repeat([]byte{0x1}, 32), + MerkleRoot: bytes.Repeat([]byte{0x1}, 32), + PkScript: bytes.Repeat([]byte{script}, 34), + } + } + + parcel := &tapfreighter.OutboundParcel{ + AnchorTx: newAnchorTx, + AnchorTxHeightHint: 1450, + TransferTime: time.Now(), + ChainFees: 100, + Inputs: []tapfreighter.TransferInput{{ + PrevID: inputPrevID, + Amount: inputAsset.Amount, + }}, + Outputs: []tapfreighter.TransferOutput{{ + Anchor: makeAnchor(0, 0x01), + ScriptKey: burnKey, + ScriptKeyLocal: true, + Amount: burnAmt, + WitnessData: burnAsset.PrevWitnesses, + SplitCommitmentRoot: mssmt.NewComputedNode( + rootHash, 100, + ), + ProofSuffix: burnSuffixBytes, + Position: 0, + }, { + Anchor: makeAnchor(1, 0x02), + ScriptKey: changeKey, + ScriptKeyLocal: true, + Amount: inputAsset.Amount - burnAmt, + WitnessData: changeAsset.PrevWitnesses, + SplitCommitmentRoot: mssmt.NewComputedNode( + rootHash, 100, + ), + ProofSuffix: changeSuffixBytes, + Position: 1, + }}, + } + + leaseOwner := fn.ToArray[[32]byte](test.RandBytes(32)) + err = executor.ExecTx( + ctx, WriteTxOption(), func(q *sqlc.Queries) error { + return assetsStore.ApplyPendingParcel( + ctx, q, parcel, leaseOwner, + time.Now().Add(time.Hour), + ) + }, + ) + require.NoError(t, err) + + rebuild := func(nonce, height, txIndex uint32) ( + *tapfreighter.AssetConfirmEvent, []*tapfreighter.AssetBurn) { + + blockHash, header, merkle := blockContextFor( + t, newAnchorTx, nonce, + ) + conf, burns, err := assetsStore.RebuildConfirmEvent( + ctx, newAnchorTx, blockHash, height, txIndex, header, + merkle, "burn note", + ) + require.NoError(t, err) + + return conf, burns + } + + assertBurn := func(conf *tapfreighter.AssetConfirmEvent, + burns []*tapfreighter.AssetBurn, height uint32, + header wire.BlockHeader) { + + require.Len(t, burns, 1) + require.Equal(t, "burn note", burns[0].Note) + require.EqualValues(t, burnAmt, burns[0].Amount) + require.Equal( + t, header.Nonce, burns[0].Proof.BlockHeader.Nonce, + ) + require.Equal( + t, header.Version, burns[0].Proof.BlockHeader.Version, + ) + require.Equal( + t, header.MerkleRoot, + burns[0].Proof.BlockHeader.MerkleRoot, + ) + require.EqualValues(t, height, burns[0].Proof.BlockHeight) + require.Equal( + t, newAnchorTx.TxHash(), + burns[0].Proof.AnchorTx.TxHash(), + ) + + // Exactly the spent input, once. A second copy would + // both bloat the leaf and fail the duplicate check. + require.Len(t, burns[0].Proof.AdditionalInputs, 1) + require.Equal( + t, 1, burns[0].Proof.AdditionalInputs[0].NumProofs(), + ) + var leafBuf bytes.Buffer + require.NoError(t, burns[0].Proof.Encode(&leafBuf)) + require.Less(t, leafBuf.Len(), proof.FileMaxProofSizeBytes) + + // The transfer proof file keeps the input as its + // prefix. Embedding it again would grow every stored + // burn proof by a full extra copy of the history. + require.Len(t, conf.FinalProofs, 2) + for _, annotated := range conf.FinalProofs { + file := &proof.File{} + err := file.Decode(bytes.NewReader(annotated.Blob)) + require.NoError(t, err) + require.Equal(t, 2, file.NumProofs()) + + last, err := file.ProofAt(1) + require.NoError(t, err) + require.Empty(t, last.AdditionalInputs) + require.EqualValues(t, height, last.BlockHeight) + } + } + + conf, burns := rebuild(1, 600, 0) + _, headerA, _ := blockContextFor(t, newAnchorTx, 1) + assertBurn(conf, burns, 600, headerA) + + // A later witness context (re-org, or the buried delivery) + // rebuilds the same provenance against the new block. + confB, burnsB := rebuild(9, 700, 1) + _, headerB, _ := blockContextFor(t, newAnchorTx, 9) + assertBurn(confB, burnsB, 700, headerB) + require.NotEqual(t, headerA, headerB) +} + +// blockContextFor builds a block hash, header, and merkle proof for a +// confirmed anchor transaction. +func blockContextFor(t *testing.T, anchorTx *wire.MsgTx, + nonce uint32) (chainhash.Hash, wire.BlockHeader, proof.TxMerkleProof) { + + t.Helper() + + header := wire.BlockHeader{ + Version: 1, + Nonce: nonce, + Timestamp: time.Unix(1_700_000_000+int64(nonce), 0), + } + blockHash := header.BlockHash() + + merkle, err := proof.NewTxMerkleProof([]*wire.MsgTx{anchorTx}, 0) + require.NoError(t, err) + + return blockHash, header, *merkle +} diff --git a/tapdb/commit_virtual_psbt.go b/tapdb/commit_virtual_psbt.go new file mode 100644 index 0000000000..3390ab80ad --- /dev/null +++ b/tapdb/commit_virtual_psbt.go @@ -0,0 +1,433 @@ +package tapdb + +import ( + "context" + "database/sql" + "errors" + "fmt" + "time" + + "github.com/lightninglabs/taproot-assets/tapdb/sqlc" +) + +// ErrNoCommitRecord is returned when no CommitVirtualPsbts idempotency +// record exists for the requested key. +var ErrNoCommitRecord = errors.New("commit idempotency record not found") + +// ErrCommitRecordChanged is returned when a compare-and-swap does not +// find the expected record bytes. The caller must re-read the row. +var ErrCommitRecordChanged = errors.New( + "commit idempotency record changed", +) + +// CommitRecordRow is one stored CommitVirtualPsbts idempotency record. +type CommitRecordRow struct { + RequestID []byte + Record []byte +} + +// CommitVirtualPsbtQueries is the subset of sqlc methods that manage the +// commit_virtual_psbt_idem table. +type CommitVirtualPsbtQueries interface { + InsertCommitVirtualPsbt(ctx context.Context, + arg sqlc.InsertCommitVirtualPsbtParams) error + + FetchCommitVirtualPsbt(ctx context.Context, + requestID []byte) ([]byte, error) + + UpdateCommitVirtualPsbt(ctx context.Context, + arg sqlc.UpdateCommitVirtualPsbtParams) (int64, error) + + DeleteCommitVirtualPsbt(ctx context.Context, requestID []byte) error + + SwapCommitVirtualPsbt(ctx context.Context, + arg sqlc.SwapCommitVirtualPsbtParams) (int64, error) + + DeleteCommitVirtualPsbtIf(ctx context.Context, + arg sqlc.DeleteCommitVirtualPsbtIfParams) (int64, error) + + ListCommitVirtualPsbts(ctx context.Context) ( + []sqlc.ListCommitVirtualPsbtsRow, error) + + // PurgeFinishedCommitVirtualPsbts deletes terminal rows whose + // finish time is strictly before the cutoff. Pending rows have + // a null finish time and are left in place. + PurgeFinishedCommitVirtualPsbts(ctx context.Context, + finishedBefore sql.NullTime) (int64, error) + + // ListFinishedCommitVirtualPsbtsBefore returns terminal rows + // whose finish time is strictly before the cutoff. + ListFinishedCommitVirtualPsbtsBefore(ctx context.Context, + finishedBefore sql.NullTime) ( + []sqlc.ListFinishedCommitVirtualPsbtsBeforeRow, error) + + // ListUnstampedCommitVirtualPsbts returns rows with no finish + // time. Pending rows are in this set, as are terminal rows + // written before finish times were stored. + ListUnstampedCommitVirtualPsbts(ctx context.Context) ( + []sqlc.ListUnstampedCommitVirtualPsbtsRow, error) +} + +// BatchedCommitVirtualPsbtStore is the transactional surface for commit +// idempotency records. +type BatchedCommitVirtualPsbtStore interface { + BatchedTx[CommitVirtualPsbtQueries] +} + +// CommitVirtualPsbtStore persists opaque CommitVirtualPsbts idempotency +// records keyed by the caller-supplied request ID. The RPC server owns the +// encoding of the blob. +type CommitVirtualPsbtStore struct { + db BatchedCommitVirtualPsbtStore +} + +// NewCommitVirtualPsbtStore returns a store backed by the given queries. +func NewCommitVirtualPsbtStore( + db BatchedCommitVirtualPsbtStore) *CommitVirtualPsbtStore { + + return &CommitVirtualPsbtStore{db: db} +} + +// NewCommitVirtualPsbtStoreFromDB builds a store on the daemon database. +func NewCommitVirtualPsbtStoreFromDB( + db DatabaseBackend) *CommitVirtualPsbtStore { + + exec := NewTransactionExecutor( + db, func(tx *sql.Tx) CommitVirtualPsbtQueries { + return db.WithTx(tx) + }, + ) + + return NewCommitVirtualPsbtStore(exec) +} + +// InsertCommitRecord inserts a record for a new request ID. A duplicate +// key returns *ErrSqlUniqueConstraintViolation. +func (s *CommitVirtualPsbtStore) InsertCommitRecord(ctx context.Context, + requestID, record []byte) error { + + err := s.db.ExecTx( + ctx, WriteTxOption(), func(q CommitVirtualPsbtQueries) error { + err := q.InsertCommitVirtualPsbt( + ctx, sqlc.InsertCommitVirtualPsbtParams{ + RequestID: requestID, + Record: record, + }, + ) + if err != nil { + return MapSQLError(err) + } + + return nil + }, + ) + if err != nil { + return MapSQLError(err) + } + + return nil +} + +// FetchCommitRecord returns the stored record, or ErrNoCommitRecord when +// the key is absent. +func (s *CommitVirtualPsbtStore) FetchCommitRecord(ctx context.Context, + requestID []byte) ([]byte, error) { + + var record []byte + err := s.db.ExecTx( + ctx, ReadTxOption(), func(q CommitVirtualPsbtQueries) error { + out, err := q.FetchCommitVirtualPsbt(ctx, requestID) + switch { + case errors.Is(err, sql.ErrNoRows): + return ErrNoCommitRecord + + case err != nil: + return fmt.Errorf("fetch commit record: %w", + err) + } + + record = out + + return nil + }, + ) + if err != nil { + return nil, err + } + + return record, nil +} + +// UpdateCommitRecord replaces the record for an existing key. +// ErrNoCommitRecord is returned when the key is absent. +func (s *CommitVirtualPsbtStore) UpdateCommitRecord(ctx context.Context, + requestID, record []byte) error { + + var rows int64 + err := s.db.ExecTx( + ctx, WriteTxOption(), func(q CommitVirtualPsbtQueries) error { + affected, err := q.UpdateCommitVirtualPsbt( + ctx, sqlc.UpdateCommitVirtualPsbtParams{ + RequestID: requestID, + Record: record, + }, + ) + if err != nil { + return fmt.Errorf("update commit record: %w", + err) + } + + rows = affected + + return nil + }, + ) + if err != nil { + return err + } + if rows == 0 { + return ErrNoCommitRecord + } + + return nil +} + +// ListCommitRecords returns every stored request ID and record. Order +// is undefined. +func (s *CommitVirtualPsbtStore) ListCommitRecords(ctx context.Context) ( + []CommitRecordRow, error) { + + var rows []CommitRecordRow + err := s.db.ExecTx( + ctx, ReadTxOption(), func(q CommitVirtualPsbtQueries) error { + listed, err := q.ListCommitVirtualPsbts(ctx) + if err != nil { + return fmt.Errorf( + "list commit records: %w", err, + ) + } + + rows = make([]CommitRecordRow, 0, len(listed)) + for _, row := range listed { + rows = append(rows, CommitRecordRow{ + RequestID: append( + []byte(nil), row.RequestID..., + ), + Record: append( + []byte(nil), row.Record..., + ), + }) + } + + return nil + }, + ) + if err != nil { + return nil, err + } + + return rows, nil +} + +// DeleteCommitRecord removes the record for the key. Deleting a missing +// key is a no-op. +func (s *CommitVirtualPsbtStore) DeleteCommitRecord(ctx context.Context, + requestID []byte) error { + + return s.db.ExecTx( + ctx, WriteTxOption(), func(q CommitVirtualPsbtQueries) error { + return q.DeleteCommitVirtualPsbt(ctx, requestID) + }, + ) +} + +// SwapCommitRecord replaces the stored record when it still equals +// expected. ErrCommitRecordChanged is returned when it does not, and +// ErrNoCommitRecord when the key is absent. A non-nil finishedAt stamps +// the row as a terminal outcome. Nil leaves the stored finish time +// unchanged, which keeps a pending row unstamped. +func (s *CommitVirtualPsbtStore) SwapCommitRecord(ctx context.Context, + requestID, expected, next []byte, finishedAt *time.Time) error { + + var finished sql.NullTime + if finishedAt != nil { + finished = sqlTime(finishedAt.UTC()) + } + + return s.db.ExecTx( + ctx, WriteTxOption(), func(q CommitVirtualPsbtQueries) error { + n, err := q.SwapCommitVirtualPsbt( + ctx, sqlc.SwapCommitVirtualPsbtParams{ + NextRecord: next, + FinishedAt: finished, + RequestID: requestID, + ExpectedRecord: expected, + }, + ) + if err != nil { + return fmt.Errorf("swap commit record: %w", + err) + } + if n == 1 { + return nil + } + + return commitRecordMiss(ctx, q, requestID) + }, + ) +} + +// DeleteCommitRecordIf removes the row when it still equals expected. +// ErrCommitRecordChanged is returned when it does not, and +// ErrNoCommitRecord when the key is absent. +func (s *CommitVirtualPsbtStore) DeleteCommitRecordIf(ctx context.Context, + requestID, expected []byte) error { + + return s.db.ExecTx( + ctx, WriteTxOption(), func(q CommitVirtualPsbtQueries) error { + n, err := q.DeleteCommitVirtualPsbtIf( + ctx, sqlc.DeleteCommitVirtualPsbtIfParams{ + RequestID: requestID, + ExpectedRecord: expected, + }, + ) + if err != nil { + return fmt.Errorf("delete commit record: %w", + err) + } + if n == 1 { + return nil + } + + return commitRecordMiss(ctx, q, requestID) + }, + ) +} + +// PurgeFinishedCommitRecords deletes completed and failed records +// whose finish time is strictly before before. It does not look at +// lnd leases. The retention sweep skips rows that are still leased. +// Pending records are kept. It returns how many rows were deleted. +func (s *CommitVirtualPsbtStore) PurgeFinishedCommitRecords( + ctx context.Context, before time.Time) (int64, error) { + + var deleted int64 + err := s.db.ExecTx( + ctx, WriteTxOption(), func(q CommitVirtualPsbtQueries) error { + n, err := q.PurgeFinishedCommitVirtualPsbts( + ctx, sqlTime(before.UTC()), + ) + if err != nil { + return fmt.Errorf( + "purge finished commit records: %w", + err, + ) + } + + deleted = n + + return nil + }, + ) + if err != nil { + return 0, err + } + + return deleted, nil +} + +// ListFinishedCommitRecords returns completed and failed records whose +// finish time is strictly before before. Pending records are omitted. +// Order is undefined. +func (s *CommitVirtualPsbtStore) ListFinishedCommitRecords( + ctx context.Context, before time.Time) ([]CommitRecordRow, error) { + + var rows []CommitRecordRow + err := s.db.ExecTx( + ctx, ReadTxOption(), func(q CommitVirtualPsbtQueries) error { + listed, err := q.ListFinishedCommitVirtualPsbtsBefore( + ctx, sqlTime(before.UTC()), + ) + if err != nil { + return fmt.Errorf( + "list finished commit records: %w", + err, + ) + } + + rows = make([]CommitRecordRow, 0, len(listed)) + for _, row := range listed { + rows = append(rows, CommitRecordRow{ + RequestID: append( + []byte(nil), row.RequestID..., + ), + Record: append( + []byte(nil), row.Record..., + ), + }) + } + + return nil + }, + ) + if err != nil { + return nil, err + } + + return rows, nil +} + +// ListUnstampedCommitRecords returns rows that have no finish time. +// Order is undefined. +func (s *CommitVirtualPsbtStore) ListUnstampedCommitRecords( + ctx context.Context) ([]CommitRecordRow, error) { + + var rows []CommitRecordRow + err := s.db.ExecTx( + ctx, ReadTxOption(), func(q CommitVirtualPsbtQueries) error { + listed, err := q.ListUnstampedCommitVirtualPsbts(ctx) + if err != nil { + return fmt.Errorf( + "list unstamped commit records: %w", + err, + ) + } + + rows = make([]CommitRecordRow, 0, len(listed)) + for _, row := range listed { + rows = append(rows, CommitRecordRow{ + RequestID: append( + []byte(nil), row.RequestID..., + ), + Record: append( + []byte(nil), row.Record..., + ), + }) + } + + return nil + }, + ) + if err != nil { + return nil, err + } + + return rows, nil +} + +// commitRecordMiss explains a compare-and-swap that matched no row. +func commitRecordMiss(ctx context.Context, q CommitVirtualPsbtQueries, + requestID []byte) error { + + _, err := q.FetchCommitVirtualPsbt(ctx, requestID) + switch { + case errors.Is(err, sql.ErrNoRows): + return ErrNoCommitRecord + + case err != nil: + return fmt.Errorf("fetch commit record: %w", err) + + default: + return ErrCommitRecordChanged + } +} diff --git a/tapdb/commit_virtual_psbt_test.go b/tapdb/commit_virtual_psbt_test.go new file mode 100644 index 0000000000..d29af54421 --- /dev/null +++ b/tapdb/commit_virtual_psbt_test.go @@ -0,0 +1,174 @@ +package tapdb + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +// TestCommitVirtualPsbtStoreRoundTrip tests insert, duplicate-key +// rejection, update, and delete of an idempotency record. +func TestCommitVirtualPsbtStoreRoundTrip(t *testing.T) { + t.Parallel() + + ctx := context.Background() + store := NewCommitVirtualPsbtStoreFromDB(NewTestDB(t)) + requestID := []byte("request-id") + first := []byte("pending") + + _, err := store.FetchCommitRecord(ctx, requestID) + require.ErrorIs(t, err, ErrNoCommitRecord) + + require.NoError(t, store.InsertCommitRecord(ctx, requestID, first)) + + err = store.InsertCommitRecord(ctx, requestID, []byte("other")) + var unique *ErrSqlUniqueConstraintViolation + require.ErrorAs(t, err, &unique) + + got, err := store.FetchCommitRecord(ctx, requestID) + require.NoError(t, err) + require.Equal(t, first, got) + + listed, err := store.ListCommitRecords(ctx) + require.NoError(t, err) + require.Len(t, listed, 1) + require.Equal(t, requestID, listed[0].RequestID) + require.Equal(t, first, listed[0].Record) + + updated := []byte("completed") + require.NoError(t, store.UpdateCommitRecord( + ctx, requestID, updated, + )) + + got, err = store.FetchCommitRecord(ctx, requestID) + require.NoError(t, err) + require.Equal(t, updated, got) + + require.NoError(t, store.DeleteCommitRecord(ctx, requestID)) + + _, err = store.FetchCommitRecord(ctx, requestID) + require.ErrorIs(t, err, ErrNoCommitRecord) + + // Deleting a missing row is a no-op, so a failed attempt can be + // abandoned more than once. + require.NoError(t, store.DeleteCommitRecord(ctx, requestID)) + + err = store.UpdateCommitRecord(ctx, requestID, []byte("gone")) + require.ErrorIs(t, err, ErrNoCommitRecord) +} + +// TestCommitVirtualPsbtStoreCompareAndSwap tests that a swap or +// conditional delete changes the row only when the stored bytes still +// match. +func TestCommitVirtualPsbtStoreCompareAndSwap(t *testing.T) { + t.Parallel() + + ctx := context.Background() + store := NewCommitVirtualPsbtStoreFromDB(NewTestDB(t)) + requestID := []byte("swap-id") + first := []byte("first") + + require.NoError(t, store.InsertCommitRecord(ctx, requestID, first)) + + err := store.SwapCommitRecord( + ctx, requestID, []byte("other"), []byte("nope"), nil, + ) + require.ErrorIs(t, err, ErrCommitRecordChanged) + + got, err := store.FetchCommitRecord(ctx, requestID) + require.NoError(t, err) + require.Equal(t, first, got) + + next := []byte("second") + require.NoError(t, store.SwapCommitRecord( + ctx, requestID, first, next, nil, + )) + + got, err = store.FetchCommitRecord(ctx, requestID) + require.NoError(t, err) + require.Equal(t, next, got) + + err = store.DeleteCommitRecordIf(ctx, requestID, first) + require.ErrorIs(t, err, ErrCommitRecordChanged) + + require.NoError(t, store.DeleteCommitRecordIf(ctx, requestID, next)) + + _, err = store.FetchCommitRecord(ctx, requestID) + require.ErrorIs(t, err, ErrNoCommitRecord) + + err = store.DeleteCommitRecordIf(ctx, requestID, next) + require.ErrorIs(t, err, ErrNoCommitRecord) +} + +// TestCommitVirtualPsbtStorePurgesFinished tests that completed and +// failed rows older than the cutoff are deleted and that pending rows +// are kept even when their blob is updated. +func TestCommitVirtualPsbtStorePurgesFinished(t *testing.T) { + t.Parallel() + + ctx := context.Background() + store := NewCommitVirtualPsbtStoreFromDB(NewTestDB(t)) + + pendingID := []byte("pending-id") + pending := []byte("pending") + require.NoError(t, store.InsertCommitRecord(ctx, pendingID, pending)) + require.NoError(t, store.SwapCommitRecord( + ctx, pendingID, pending, []byte("pending-2"), nil, + )) + + oldAt := time.Now().Add(-48 * time.Hour).UTC() + require.NoError(t, store.InsertCommitRecord( + ctx, []byte("old-ok"), []byte("claim"), + )) + require.NoError(t, store.SwapCommitRecord( + ctx, []byte("old-ok"), []byte("claim"), + []byte("old-completed"), &oldAt, + )) + + failedAt := time.Now().Add(-48 * time.Hour).UTC() + require.NoError(t, store.InsertCommitRecord( + ctx, []byte("failed"), []byte("claim"), + )) + require.NoError(t, store.SwapCommitRecord( + ctx, []byte("failed"), []byte("claim"), + []byte("failed-outcome"), &failedAt, + )) + + recentAt := time.Now().UTC() + require.NoError(t, store.InsertCommitRecord( + ctx, []byte("new-ok"), []byte("claim"), + )) + require.NoError(t, store.SwapCommitRecord( + ctx, []byte("new-ok"), []byte("claim"), + []byte("new-completed"), &recentAt, + )) + + cutoff := time.Now().Add(-24 * time.Hour).UTC() + finished, err := store.ListFinishedCommitRecords(ctx, cutoff) + require.NoError(t, err) + require.Len(t, finished, 2) + + deleted, err := store.PurgeFinishedCommitRecords(ctx, cutoff) + require.NoError(t, err) + require.EqualValues(t, 2, deleted) + + _, err = store.FetchCommitRecord(ctx, []byte("old-ok")) + require.ErrorIs(t, err, ErrNoCommitRecord) + _, err = store.FetchCommitRecord(ctx, []byte("failed")) + require.ErrorIs(t, err, ErrNoCommitRecord) + + got, err := store.FetchCommitRecord(ctx, []byte("new-ok")) + require.NoError(t, err) + require.Equal(t, []byte("new-completed"), got) + + got, err = store.FetchCommitRecord(ctx, pendingID) + require.NoError(t, err) + require.Equal(t, []byte("pending-2"), got) + + unstamped, err := store.ListUnstampedCommitRecords(ctx) + require.NoError(t, err) + require.Len(t, unstamped, 1) + require.Equal(t, pendingID, unstamped[0].RequestID) +} diff --git a/tapdb/migrations.go b/tapdb/migrations.go index bb75bdabf2..f8f4e6b676 100644 --- a/tapdb/migrations.go +++ b/tapdb/migrations.go @@ -24,7 +24,7 @@ const ( // daemon. // // NOTE: This MUST be updated when a new migration is added. - LatestMigrationVersion = 60 + LatestMigrationVersion = 74 ) // DatabaseBackend is an interface that contains all methods our different diff --git a/tapdb/sqlc/assets.sql.go b/tapdb/sqlc/assets.sql.go index c8bc3285c3..2e27d57a1f 100644 --- a/tapdb/sqlc/assets.sql.go +++ b/tapdb/sqlc/assets.sql.go @@ -3512,6 +3512,42 @@ func (q *Queries) UpsertManagedUTXO(ctx context.Context, arg UpsertManagedUTXOPa return utxo_id, err } +const UpsertWalletVerifiedInternalKey = `-- name: UpsertWalletVerifiedInternalKey :one +INSERT INTO internal_keys ( + raw_key, key_family, key_index +) VALUES ( + $1, $2, $3 +) ON CONFLICT (raw_key) + -- This query is restricted to a wallet-verified descriptor. It may + -- upgrade the historical 0/0 placeholder, but never overwrite a known, + -- conflicting locator. + DO UPDATE SET key_family = EXCLUDED.key_family, + key_index = EXCLUDED.key_index + WHERE (internal_keys.key_family = 0 AND internal_keys.key_index = 0) + OR (internal_keys.key_family = EXCLUDED.key_family AND + internal_keys.key_index = EXCLUDED.key_index) +RETURNING key_id +` + +type UpsertWalletVerifiedInternalKeyParams struct { + RawKey []byte + KeyFamily int32 + KeyIndex int32 +} + +func (q *Queries) UpsertWalletVerifiedInternalKey(ctx context.Context, + arg UpsertWalletVerifiedInternalKeyParams) (int64, error) { + + row := q.db.QueryRowContext( + ctx, UpsertWalletVerifiedInternalKey, arg.RawKey, arg.KeyFamily, + arg.KeyIndex, + ) + var keyID int64 + err := row.Scan(&keyID) + + return keyID, err +} + const UpsertMintSupplyPreCommit = `-- name: UpsertMintSupplyPreCommit :one WITH target_batch AS ( -- This CTE is used to fetch the ID of a batch, based on the serialized diff --git a/tapdb/sqlc/commit_virtual_psbt.sql.go b/tapdb/sqlc/commit_virtual_psbt.sql.go new file mode 100644 index 0000000000..f32d99a1ab --- /dev/null +++ b/tapdb/sqlc/commit_virtual_psbt.sql.go @@ -0,0 +1,234 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.29.0 +// source: commit_virtual_psbt.sql + +package sqlc + +import ( + "context" + "database/sql" +) + +const DeleteCommitVirtualPsbt = `-- name: DeleteCommitVirtualPsbt :exec +DELETE FROM commit_virtual_psbt_idem +WHERE request_id = $1 +` + +func (q *Queries) DeleteCommitVirtualPsbt(ctx context.Context, requestID []byte) error { + _, err := q.db.ExecContext(ctx, DeleteCommitVirtualPsbt, requestID) + return err +} + +const DeleteCommitVirtualPsbtIf = `-- name: DeleteCommitVirtualPsbtIf :execrows +DELETE FROM commit_virtual_psbt_idem +WHERE request_id = $1 + AND record = $2 +` + +type DeleteCommitVirtualPsbtIfParams struct { + RequestID []byte + ExpectedRecord []byte +} + +func (q *Queries) DeleteCommitVirtualPsbtIf(ctx context.Context, arg DeleteCommitVirtualPsbtIfParams) (int64, error) { + result, err := q.db.ExecContext(ctx, DeleteCommitVirtualPsbtIf, arg.RequestID, arg.ExpectedRecord) + if err != nil { + return 0, err + } + return result.RowsAffected() +} + +const FetchCommitVirtualPsbt = `-- name: FetchCommitVirtualPsbt :one +SELECT record +FROM commit_virtual_psbt_idem +WHERE request_id = $1 +` + +func (q *Queries) FetchCommitVirtualPsbt(ctx context.Context, requestID []byte) ([]byte, error) { + row := q.db.QueryRowContext(ctx, FetchCommitVirtualPsbt, requestID) + var record []byte + err := row.Scan(&record) + return record, err +} + +const InsertCommitVirtualPsbt = `-- name: InsertCommitVirtualPsbt :exec +INSERT INTO commit_virtual_psbt_idem ( + request_id, record +) VALUES ( + $1, $2 +) +` + +type InsertCommitVirtualPsbtParams struct { + RequestID []byte + Record []byte +} + +func (q *Queries) InsertCommitVirtualPsbt(ctx context.Context, arg InsertCommitVirtualPsbtParams) error { + _, err := q.db.ExecContext(ctx, InsertCommitVirtualPsbt, arg.RequestID, arg.Record) + return err +} + +const ListCommitVirtualPsbts = `-- name: ListCommitVirtualPsbts :many +SELECT request_id, record +FROM commit_virtual_psbt_idem +` + +type ListCommitVirtualPsbtsRow struct { + RequestID []byte + Record []byte +} + +func (q *Queries) ListCommitVirtualPsbts(ctx context.Context) ([]ListCommitVirtualPsbtsRow, error) { + rows, err := q.db.QueryContext(ctx, ListCommitVirtualPsbts) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListCommitVirtualPsbtsRow + for rows.Next() { + var i ListCommitVirtualPsbtsRow + if err := rows.Scan(&i.RequestID, &i.Record); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const ListFinishedCommitVirtualPsbtsBefore = `-- name: ListFinishedCommitVirtualPsbtsBefore :many +SELECT request_id, record +FROM commit_virtual_psbt_idem +WHERE finished_at IS NOT NULL + AND finished_at < $1 +` + +type ListFinishedCommitVirtualPsbtsBeforeRow struct { + RequestID []byte + Record []byte +} + +func (q *Queries) ListFinishedCommitVirtualPsbtsBefore(ctx context.Context, finishedBefore sql.NullTime) ([]ListFinishedCommitVirtualPsbtsBeforeRow, error) { + rows, err := q.db.QueryContext(ctx, ListFinishedCommitVirtualPsbtsBefore, finishedBefore) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListFinishedCommitVirtualPsbtsBeforeRow + for rows.Next() { + var i ListFinishedCommitVirtualPsbtsBeforeRow + if err := rows.Scan(&i.RequestID, &i.Record); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const ListUnstampedCommitVirtualPsbts = `-- name: ListUnstampedCommitVirtualPsbts :many +SELECT request_id, record +FROM commit_virtual_psbt_idem +WHERE finished_at IS NULL +` + +type ListUnstampedCommitVirtualPsbtsRow struct { + RequestID []byte + Record []byte +} + +func (q *Queries) ListUnstampedCommitVirtualPsbts(ctx context.Context) ([]ListUnstampedCommitVirtualPsbtsRow, error) { + rows, err := q.db.QueryContext(ctx, ListUnstampedCommitVirtualPsbts) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListUnstampedCommitVirtualPsbtsRow + for rows.Next() { + var i ListUnstampedCommitVirtualPsbtsRow + if err := rows.Scan(&i.RequestID, &i.Record); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const PurgeFinishedCommitVirtualPsbts = `-- name: PurgeFinishedCommitVirtualPsbts :execrows +DELETE FROM commit_virtual_psbt_idem +WHERE finished_at IS NOT NULL + AND finished_at < $1 +` + +func (q *Queries) PurgeFinishedCommitVirtualPsbts(ctx context.Context, finishedBefore sql.NullTime) (int64, error) { + result, err := q.db.ExecContext(ctx, PurgeFinishedCommitVirtualPsbts, finishedBefore) + if err != nil { + return 0, err + } + return result.RowsAffected() +} + +const SwapCommitVirtualPsbt = `-- name: SwapCommitVirtualPsbt :execrows +UPDATE commit_virtual_psbt_idem +SET record = $1, + finished_at = COALESCE($2, finished_at) +WHERE request_id = $3 + AND record = $4 +` + +type SwapCommitVirtualPsbtParams struct { + NextRecord []byte + FinishedAt sql.NullTime + RequestID []byte + ExpectedRecord []byte +} + +func (q *Queries) SwapCommitVirtualPsbt(ctx context.Context, arg SwapCommitVirtualPsbtParams) (int64, error) { + result, err := q.db.ExecContext(ctx, SwapCommitVirtualPsbt, + arg.NextRecord, + arg.FinishedAt, + arg.RequestID, + arg.ExpectedRecord, + ) + if err != nil { + return 0, err + } + return result.RowsAffected() +} + +const UpdateCommitVirtualPsbt = `-- name: UpdateCommitVirtualPsbt :execrows +UPDATE commit_virtual_psbt_idem +SET record = $2 +WHERE request_id = $1 +` + +type UpdateCommitVirtualPsbtParams struct { + RequestID []byte + Record []byte +} + +func (q *Queries) UpdateCommitVirtualPsbt(ctx context.Context, arg UpdateCommitVirtualPsbtParams) (int64, error) { + result, err := q.db.ExecContext(ctx, UpdateCommitVirtualPsbt, arg.RequestID, arg.Record) + if err != nil { + return 0, err + } + return result.RowsAffected() +} diff --git a/tapdb/sqlc/migrations/000073_commit_virtual_psbt_idem.down.sql b/tapdb/sqlc/migrations/000073_commit_virtual_psbt_idem.down.sql new file mode 100644 index 0000000000..a9442f8d59 --- /dev/null +++ b/tapdb/sqlc/migrations/000073_commit_virtual_psbt_idem.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS commit_virtual_psbt_idem; diff --git a/tapdb/sqlc/migrations/000073_commit_virtual_psbt_idem.up.sql b/tapdb/sqlc/migrations/000073_commit_virtual_psbt_idem.up.sql new file mode 100644 index 0000000000..5470f30552 --- /dev/null +++ b/tapdb/sqlc/migrations/000073_commit_virtual_psbt_idem.up.sql @@ -0,0 +1,11 @@ +-- commit_virtual_psbt_idem stores the outcome of CommitVirtualPsbts +-- calls that set a request_id. The record blob is an opaque encoding +-- owned by the RPC server, so later fields do not need a migration. +CREATE TABLE IF NOT EXISTS commit_virtual_psbt_idem ( + -- request_id is the caller-supplied idempotency key. + request_id BLOB PRIMARY KEY + CHECK (length(request_id) BETWEEN 1 AND 64), + + -- record holds the pending or completed commit outcome. + record BLOB NOT NULL +); diff --git a/tapdb/sqlc/migrations/000074_commit_virtual_psbt_idem_finished_at.down.sql b/tapdb/sqlc/migrations/000074_commit_virtual_psbt_idem_finished_at.down.sql new file mode 100644 index 0000000000..2238c750d9 --- /dev/null +++ b/tapdb/sqlc/migrations/000074_commit_virtual_psbt_idem_finished_at.down.sql @@ -0,0 +1,4 @@ +DROP INDEX IF EXISTS commit_virtual_psbt_idem_finished_at_idx; + +ALTER TABLE commit_virtual_psbt_idem + DROP COLUMN finished_at; diff --git a/tapdb/sqlc/migrations/000074_commit_virtual_psbt_idem_finished_at.up.sql b/tapdb/sqlc/migrations/000074_commit_virtual_psbt_idem_finished_at.up.sql new file mode 100644 index 0000000000..b38924be8b --- /dev/null +++ b/tapdb/sqlc/migrations/000074_commit_virtual_psbt_idem_finished_at.up.sql @@ -0,0 +1,12 @@ +-- finished_at is when a CommitVirtualPsbts request recorded a terminal +-- outcome (completed or failed). Pending rows leave it null and are +-- never purged. The partial index lets retention delete old responses +-- without reading the record blob, which can be up to 32 MiB. +-- Existing rows stay null; no backfill is required. + +ALTER TABLE commit_virtual_psbt_idem + ADD COLUMN finished_at TIMESTAMP; + +CREATE INDEX commit_virtual_psbt_idem_finished_at_idx + ON commit_virtual_psbt_idem (finished_at) + WHERE finished_at IS NOT NULL; diff --git a/tapdb/sqlc/models.go b/tapdb/sqlc/models.go index 6b46ad3005..e4811216cf 100644 --- a/tapdb/sqlc/models.go +++ b/tapdb/sqlc/models.go @@ -216,6 +216,12 @@ type ChainTxn struct { TxIndex sql.NullInt32 } +type CommitVirtualPsbtIdem struct { + RequestID []byte + Record []byte + FinishedAt sql.NullTime +} + type FederationGlobalSyncConfig struct { ProofType string AllowSyncInsert bool diff --git a/tapdb/sqlc/querier.go b/tapdb/sqlc/querier.go index c17ef127fd..5b9804fdff 100644 --- a/tapdb/sqlc/querier.go +++ b/tapdb/sqlc/querier.go @@ -131,6 +131,7 @@ type Querier interface { // Fetches all push log entries for a given asset group, ordered by // creation time with the most recent entries first. FetchSupplySyncerPushLogs(ctx context.Context, groupKey []byte) ([]SupplySyncerPushLog, error) + FetchSupplySyncerPushedServers(ctx context.Context, arg FetchSupplySyncerPushedServersParams) ([]string, error) // Sort the nodes by node_index here instead of returning the indices. FetchTapscriptTree(ctx context.Context, rootHash []byte) ([]FetchTapscriptTreeRow, error) FetchTransferInputs(ctx context.Context, transferID int64) ([]FetchTransferInputsRow, error) @@ -240,6 +241,8 @@ type Querier interface { QuerySupplyCommitStateMachine(ctx context.Context, groupKey []byte) (QuerySupplyCommitStateMachineRow, error) QuerySupplyCommitment(ctx context.Context, commitID int64) (QuerySupplyCommitmentRow, error) QuerySupplyCommitmentByOutpoint(ctx context.Context, arg QuerySupplyCommitmentByOutpointParams) (QuerySupplyCommitmentByOutpointRow, error) + QuerySupplyCommitmentByTxid(ctx context.Context, arg QuerySupplyCommitmentByTxidParams) (QuerySupplyCommitmentByTxidRow, error) + QuerySupplyCommitTransitionByNewCommitment(ctx context.Context, newCommitmentID sql.NullInt64) (QuerySupplyCommitTransitionByNewCommitmentRow, error) QuerySupplyCommitmentBySpentOutpoint(ctx context.Context, arg QuerySupplyCommitmentBySpentOutpointParams) (QuerySupplyCommitmentBySpentOutpointRow, error) QuerySupplyCommitmentOutpoint(ctx context.Context, commitID int64) (QuerySupplyCommitmentOutpointRow, error) QuerySupplyLeavesByHeight(ctx context.Context, arg QuerySupplyLeavesByHeightParams) ([]QuerySupplyLeavesByHeightRow, error) diff --git a/tapdb/sqlc/queries/commit_virtual_psbt.sql b/tapdb/sqlc/queries/commit_virtual_psbt.sql new file mode 100644 index 0000000000..7b919ad55f --- /dev/null +++ b/tapdb/sqlc/queries/commit_virtual_psbt.sql @@ -0,0 +1,52 @@ +-- name: InsertCommitVirtualPsbt :exec +INSERT INTO commit_virtual_psbt_idem ( + request_id, record +) VALUES ( + $1, $2 +); + +-- name: FetchCommitVirtualPsbt :one +SELECT record +FROM commit_virtual_psbt_idem +WHERE request_id = $1; + +-- name: ListCommitVirtualPsbts :many +SELECT request_id, record +FROM commit_virtual_psbt_idem; + +-- name: UpdateCommitVirtualPsbt :execrows +UPDATE commit_virtual_psbt_idem +SET record = $2 +WHERE request_id = $1; + +-- name: DeleteCommitVirtualPsbt :exec +DELETE FROM commit_virtual_psbt_idem +WHERE request_id = $1; + +-- name: SwapCommitVirtualPsbt :execrows +UPDATE commit_virtual_psbt_idem +SET record = sqlc.arg('next_record'), + finished_at = COALESCE(sqlc.narg('finished_at'), finished_at) +WHERE request_id = sqlc.arg('request_id') + AND record = sqlc.arg('expected_record'); + +-- name: PurgeFinishedCommitVirtualPsbts :execrows +DELETE FROM commit_virtual_psbt_idem +WHERE finished_at IS NOT NULL + AND finished_at < sqlc.arg('finished_before'); + +-- name: ListFinishedCommitVirtualPsbtsBefore :many +SELECT request_id, record +FROM commit_virtual_psbt_idem +WHERE finished_at IS NOT NULL + AND finished_at < sqlc.arg('finished_before'); + +-- name: ListUnstampedCommitVirtualPsbts :many +SELECT request_id, record +FROM commit_virtual_psbt_idem +WHERE finished_at IS NULL; + +-- name: DeleteCommitVirtualPsbtIf :execrows +DELETE FROM commit_virtual_psbt_idem +WHERE request_id = sqlc.arg('request_id') + AND record = sqlc.arg('expected_record'); diff --git a/tapdb/sqlc/queries/supply_commit.sql b/tapdb/sqlc/queries/supply_commit.sql index c92d35bd1e..9d3cab1877 100644 --- a/tapdb/sqlc/queries/supply_commit.sql +++ b/tapdb/sqlc/queries/supply_commit.sql @@ -149,6 +149,20 @@ WHERE sc.group_key = @group_key AND sc.output_index = @output_index AND ct.txid = @txid; +-- name: QuerySupplyCommitmentByTxid :one +SELECT sqlc.embed(sc) +FROM supply_commitments AS sc +JOIN chain_txns AS ct + ON sc.chain_txn_id = ct.txn_id +WHERE sc.group_key = @group_key AND + ct.txid = @txid; + +-- name: QuerySupplyCommitTransitionByNewCommitment :one +SELECT sqlc.embed(t) +FROM supply_commit_transitions t +WHERE t.new_commitment_id = @new_commitment_id +LIMIT 1; + -- name: QuerySupplyCommitmentBySpentOutpoint :one WITH spent_commitment AS ( SELECT ssc.commit_id diff --git a/tapdb/sqlc/queries/supply_syncer.sql b/tapdb/sqlc/queries/supply_syncer.sql index 19365765da..a137280e70 100644 --- a/tapdb/sqlc/queries/supply_syncer.sql +++ b/tapdb/sqlc/queries/supply_syncer.sql @@ -18,3 +18,14 @@ SELECT id, group_key, max_pushed_block_height, server_address, FROM supply_syncer_push_log WHERE group_key = @group_key ORDER BY created_at DESC; + +-- name: FetchSupplySyncerPushedServers :many +-- Fetches the addresses of the servers a given supply commitment has +-- already been pushed to, identified by its commitment outpoint. The +-- push log records every successful remote insert, so this is the +-- sender's durable view of which servers already hold the commitment. +SELECT server_address +FROM supply_syncer_push_log +WHERE group_key = @group_key + AND commit_txid = @commit_txid + AND output_index = @output_index; diff --git a/tapdb/sqlc/schemas/generated_schema.sql b/tapdb/sqlc/schemas/generated_schema.sql index 1991d0dc7d..5058940ace 100644 --- a/tapdb/sqlc/schemas/generated_schema.sql +++ b/tapdb/sqlc/schemas/generated_schema.sql @@ -444,6 +444,19 @@ CREATE TABLE chain_txns ( tx_index INTEGER ); +CREATE TABLE commit_virtual_psbt_idem ( + -- request_id is the caller-supplied idempotency key. + request_id BLOB PRIMARY KEY + CHECK (length(request_id) BETWEEN 1 AND 64), + + -- record holds the pending or completed commit outcome. + record BLOB NOT NULL +, finished_at TIMESTAMP); + +CREATE INDEX commit_virtual_psbt_idem_finished_at_idx + ON commit_virtual_psbt_idem (finished_at) + WHERE finished_at IS NOT NULL; + CREATE INDEX creation_time_idx ON addr_events(creation_time); CREATE TABLE federation_global_sync_config ( diff --git a/tapdb/sqlc/supply_commit.sql.go b/tapdb/sqlc/supply_commit.sql.go index 196f1aab74..46428791d7 100644 --- a/tapdb/sqlc/supply_commit.sql.go +++ b/tapdb/sqlc/supply_commit.sql.go @@ -1,6 +1,6 @@ // Code generated by sqlc. DO NOT EDIT. // versions: -// sqlc v1.29.0 +// sqlc v1.27.0 // source: supply_commit.sql package sqlc @@ -609,6 +609,33 @@ func (q *Queries) QuerySupplyCommitStateMachine(ctx context.Context, groupKey [] return i, err } +const QuerySupplyCommitTransitionByNewCommitment = `-- name: QuerySupplyCommitTransitionByNewCommitment :one +SELECT t.transition_id, t.state_machine_group_key, t.old_commitment_id, t.new_commitment_id, t.pending_commit_txn_id, t.frozen, t.finalized, t.creation_time +FROM supply_commit_transitions t +WHERE t.new_commitment_id = $1 +LIMIT 1 +` + +type QuerySupplyCommitTransitionByNewCommitmentRow struct { + SupplyCommitTransition SupplyCommitTransition +} + +func (q *Queries) QuerySupplyCommitTransitionByNewCommitment(ctx context.Context, newCommitmentID sql.NullInt64) (QuerySupplyCommitTransitionByNewCommitmentRow, error) { + row := q.db.QueryRowContext(ctx, QuerySupplyCommitTransitionByNewCommitment, newCommitmentID) + var i QuerySupplyCommitTransitionByNewCommitmentRow + err := row.Scan( + &i.SupplyCommitTransition.TransitionID, + &i.SupplyCommitTransition.StateMachineGroupKey, + &i.SupplyCommitTransition.OldCommitmentID, + &i.SupplyCommitTransition.NewCommitmentID, + &i.SupplyCommitTransition.PendingCommitTxnID, + &i.SupplyCommitTransition.Frozen, + &i.SupplyCommitTransition.Finalized, + &i.SupplyCommitTransition.CreationTime, + ) + return i, err +} + const QuerySupplyCommitment = `-- name: QuerySupplyCommitment :one SELECT sc.commit_id, sc.group_key, sc.chain_txn_id, sc.output_index, sc.internal_key_id, sc.output_key, sc.block_header, sc.block_height, sc.merkle_proof, sc.supply_root_hash, sc.supply_root_sum, sc.spent_commitment, ct.tx_index FROM supply_commitments AS sc @@ -734,6 +761,44 @@ func (q *Queries) QuerySupplyCommitmentBySpentOutpoint(ctx context.Context, arg return i, err } +const QuerySupplyCommitmentByTxid = `-- name: QuerySupplyCommitmentByTxid :one +SELECT sc.commit_id, sc.group_key, sc.chain_txn_id, sc.output_index, sc.internal_key_id, sc.output_key, sc.block_header, sc.block_height, sc.merkle_proof, sc.supply_root_hash, sc.supply_root_sum, sc.spent_commitment +FROM supply_commitments AS sc +JOIN chain_txns AS ct + ON sc.chain_txn_id = ct.txn_id +WHERE sc.group_key = $1 AND + ct.txid = $2 +` + +type QuerySupplyCommitmentByTxidParams struct { + GroupKey []byte + Txid []byte +} + +type QuerySupplyCommitmentByTxidRow struct { + SupplyCommitment SupplyCommitment +} + +func (q *Queries) QuerySupplyCommitmentByTxid(ctx context.Context, arg QuerySupplyCommitmentByTxidParams) (QuerySupplyCommitmentByTxidRow, error) { + row := q.db.QueryRowContext(ctx, QuerySupplyCommitmentByTxid, arg.GroupKey, arg.Txid) + var i QuerySupplyCommitmentByTxidRow + err := row.Scan( + &i.SupplyCommitment.CommitID, + &i.SupplyCommitment.GroupKey, + &i.SupplyCommitment.ChainTxnID, + &i.SupplyCommitment.OutputIndex, + &i.SupplyCommitment.InternalKeyID, + &i.SupplyCommitment.OutputKey, + &i.SupplyCommitment.BlockHeader, + &i.SupplyCommitment.BlockHeight, + &i.SupplyCommitment.MerkleProof, + &i.SupplyCommitment.SupplyRootHash, + &i.SupplyCommitment.SupplyRootSum, + &i.SupplyCommitment.SpentCommitment, + ) + return i, err +} + const QuerySupplyCommitmentOutpoint = `-- name: QuerySupplyCommitmentOutpoint :one SELECT ct.txid, sc.output_index FROM supply_commitments AS sc diff --git a/tapdb/sqlc/supply_syncer.sql.go b/tapdb/sqlc/supply_syncer.sql.go index 8eefd56e4d..4e6e2f2ee1 100644 --- a/tapdb/sqlc/supply_syncer.sql.go +++ b/tapdb/sqlc/supply_syncer.sql.go @@ -51,6 +51,47 @@ func (q *Queries) FetchSupplySyncerPushLogs(ctx context.Context, groupKey []byte return items, nil } +const FetchSupplySyncerPushedServers = `-- name: FetchSupplySyncerPushedServers :many +SELECT server_address +FROM supply_syncer_push_log +WHERE group_key = $1 + AND commit_txid = $2 + AND output_index = $3 +` + +type FetchSupplySyncerPushedServersParams struct { + GroupKey []byte + CommitTxid []byte + OutputIndex int32 +} + +// Fetches the addresses of the servers a given supply commitment has +// already been pushed to, identified by its commitment outpoint. The +// push log records every successful remote insert, so this is the +// sender's durable view of which servers already hold the commitment. +func (q *Queries) FetchSupplySyncerPushedServers(ctx context.Context, arg FetchSupplySyncerPushedServersParams) ([]string, error) { + rows, err := q.db.QueryContext(ctx, FetchSupplySyncerPushedServers, arg.GroupKey, arg.CommitTxid, arg.OutputIndex) + if err != nil { + return nil, err + } + defer rows.Close() + var items []string + for rows.Next() { + var server_address string + if err := rows.Scan(&server_address); err != nil { + return nil, err + } + items = append(items, server_address) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + const InsertSupplySyncerPushLog = `-- name: InsertSupplySyncerPushLog :exec INSERT INTO supply_syncer_push_log ( group_key, max_pushed_block_height, server_address, diff --git a/tapdb/supply_commit.go b/tapdb/supply_commit.go index 9eaa00a599..0413c694c3 100644 --- a/tapdb/supply_commit.go +++ b/tapdb/supply_commit.go @@ -194,6 +194,18 @@ type SupplyCommitStore interface { arg sqlc.QuerySupplyCommitmentByOutpointParams) ( sqlc.QuerySupplyCommitmentByOutpointRow, error) + // QuerySupplyCommitmentByTxid fetches a supply commitment by its + // chain transaction ID. + QuerySupplyCommitmentByTxid(ctx context.Context, + arg sqlc.QuerySupplyCommitmentByTxidParams) ( + sqlc.QuerySupplyCommitmentByTxidRow, error) + + // QuerySupplyCommitTransitionByNewCommitment fetches the transition + // that created the given commitment. + QuerySupplyCommitTransitionByNewCommitment(ctx context.Context, + newCommitmentID sql.NullInt64) ( + sqlc.QuerySupplyCommitTransitionByNewCommitmentRow, error) + // QuerySupplyCommitmentBySpentOutpoint fetches a supply commitment by // its spent outpoint. QuerySupplyCommitmentBySpentOutpoint(ctx context.Context, @@ -882,6 +894,151 @@ func (s *SupplyCommitMachine) BindDanglingUpdatesToTransition( return boundEvents, nil } +// BeginIdleTransition starts a new, frozen transition that spends the latest +// confirmed supply commitment without requiring a new supply update. Any +// dangling updates are bound to the new transition and returned. The state +// machine must be in the default state, have a latest commitment, and have no +// pending transition. +func (s *SupplyCommitMachine) BeginIdleTransition(ctx context.Context, + assetSpec asset.Specifier) ([]supplycommit.SupplyUpdateEvent, error) { + + groupKey := assetSpec.UnwrapGroupKeyToPtr() + if groupKey == nil { + return nil, ErrMissingGroupKey + } + groupKeyBytes := schnorr.SerializePubKey(groupKey) + + var boundEvents []supplycommit.SupplyUpdateEvent + + writeTx := WriteTxOption() + err := s.db.ExecTx(ctx, writeTx, func(db SupplyCommitStore) error { + // Start from a clean slate, so a failed attempt can be retried. + boundEvents = nil + + stateMachine, err := db.QuerySupplyCommitStateMachine( + ctx, groupKeyBytes, + ) + if err != nil { + return fmt.Errorf("failed to query state machine: %w", + err) + } + + currentState, err := intToState(stateMachine.CurrentStateID) + if err != nil { + return fmt.Errorf("invalid state ID %d: %w", + stateMachine.CurrentStateID, err) + } + if _, ok := currentState.(*supplycommit.DefaultState); !ok { + return fmt.Errorf("cannot begin idle transition in "+ + "state: %s", currentState.String()) + } + + // An idle transition spends the latest commitment, so there + // has to be one. + if !stateMachine.LatestCommitmentID.Valid { + return fmt.Errorf("cannot begin idle transition "+ + "without a latest commitment for group key %x", + groupKeyBytes) + } + + // We can't start a new transition while one is pending. + _, err = db.QueryPendingSupplyCommitTransition( + ctx, groupKeyBytes, + ) + switch { + case err == nil: + return fmt.Errorf("cannot begin idle transition, "+ + "a transition is already pending for group "+ + "key %x", groupKeyBytes) + + case !errors.Is(err, sql.ErrNoRows): + return fmt.Errorf("failed to query pending "+ + "transition: %w", err) + } + + // The transition is created frozen, so that updates arriving + // while it is in flight become dangling updates for the next + // one. + transitionID, err := db.InsertSupplyCommitTransition( + ctx, InsertSupplyCommitTransition{ + StateMachineGroupKey: groupKeyBytes, + OldCommitmentID: stateMachine.LatestCommitmentID, //nolint:lll + Finalized: false, + Frozen: true, + CreationTime: time.Now().Unix(), + }, + ) + if err != nil { + return fmt.Errorf("failed to insert new "+ + "transition: %w", err) + } + + // Bind any dangling updates, they are committed together with + // the idle successor. + eventRows, err := db.QueryDanglingSupplyUpdateEvents( + ctx, groupKeyBytes, + ) + if err != nil && !errors.Is(err, sql.ErrNoRows) { + return fmt.Errorf("failed to query dangling "+ + "events: %w", err) + } + if len(eventRows) > 0 { + err = db.LinkDanglingSupplyUpdateEvents( + ctx, LinkDanglingSupplyUpdateEventsParams{ + GroupKey: groupKeyBytes, + TransitionID: sqlInt64(transitionID), + }, + ) + if err != nil { + return fmt.Errorf("failed to link dangling "+ + "events: %w", err) + } + } + + boundEvents = make( + []supplycommit.SupplyUpdateEvent, 0, len(eventRows), + ) + for _, eventRow := range eventRows { + event, err := deserializeSupplyUpdateEvent( + eventRow.UpdateTypeName, + bytes.NewReader(eventRow.EventData), + ) + if err != nil { + return fmt.Errorf("failed to deserialize "+ + "event: %w", err) + } + boundEvents = append(boundEvents, event) + } + + // Finally persist the updates pending state, so the cycle is + // resumed after a restart. + pendingStateName, err := stateToDBString( + &supplycommit.UpdatesPendingState{}, + ) + if err != nil { + return fmt.Errorf("error getting pending state "+ + "name: %w", err) + } + _, err = db.UpsertSupplyCommitStateMachine( + ctx, SupplyCommitMachineParams{ + GroupKey: groupKeyBytes, + StateName: sqlStr(pendingStateName), + }, + ) + if err != nil { + return fmt.Errorf("failed to update state machine "+ + "to pending: %w", err) + } + + return nil + }) + if err != nil { + return nil, err + } + + return boundEvents, nil +} + // InsertSignedCommitTx associates a new signed commitment anchor transaction // with the current active supply commitment state transition. func (s *SupplyCommitMachine) InsertSignedCommitTx(ctx context.Context, diff --git a/tapdb/supply_commit_history.go b/tapdb/supply_commit_history.go new file mode 100644 index 0000000000..8e29fab957 --- /dev/null +++ b/tapdb/supply_commit_history.go @@ -0,0 +1,169 @@ +package tapdb + +import ( + "bytes" + "context" + "fmt" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/btcec/v2/schnorr" + "github.com/btcsuite/btcd/chaincfg/chainhash" + "github.com/btcsuite/btcd/wire" + "github.com/lightninglabs/taproot-assets/asset" + "github.com/lightninglabs/taproot-assets/tapdb/sqlc" + "github.com/lightninglabs/taproot-assets/universe/supplycommit" + "github.com/lightninglabs/taproot-assets/universe/supplyverifier" +) + +// FetchCommitmentPushData loads everything the push dispatcher needs +// about a finalized commitment from the durable record: the root +// commitment (with its chain-transaction context), the update events +// the finalized transition committed, and the chain proof written at +// finalization. +func (s *SupplyCommitMachine) FetchCommitmentPushData(ctx context.Context, + groupKey *btcec.PublicKey, commitTxid chainhash.Hash) ( + supplycommit.RootCommitment, []supplycommit.SupplyUpdateEvent, + supplycommit.ChainProof, error) { + + var ( + groupKeyBytes = schnorr.SerializePubKey(groupKey) + commitment supplycommit.RootCommitment + updates []supplycommit.SupplyUpdateEvent + chainProof supplycommit.ChainProof + ) + + readTx := ReadTxOption() + err := s.db.ExecTx(ctx, readTx, func(db SupplyCommitStore) error { + commitRow, err := db.QuerySupplyCommitmentByTxid( + ctx, sqlc.QuerySupplyCommitmentByTxidParams{ + GroupKey: groupKeyBytes, + Txid: commitTxid[:], + }, + ) + if err != nil { + return fmt.Errorf("unable to query commitment for "+ + "tx %v: %w", commitTxid, err) + } + + commitOpt, err := fetchCommitment( + ctx, db, sqlInt64(commitRow.SupplyCommitment.CommitID), + ) + if err != nil { + return fmt.Errorf("unable to fetch commitment: %w", + err) + } + commit, err := commitOpt.UnwrapOrErr( + fmt.Errorf("commitment %d vanished mid-transaction", + commitRow.SupplyCommitment.CommitID), + ) + if err != nil { + return err + } + commitment = commit + + var haveProof bool + commitment.CommitmentBlock.WhenSome( + func(b supplycommit.CommitmentBlock) { + if b.BlockHeader == nil || + b.MerkleProof == nil { + + return + } + chainProof = supplycommit.ChainProof{ + Header: *b.BlockHeader, + BlockHeight: b.Height, + MerkleProof: *b.MerkleProof, + TxIndex: b.TxIndex, + } + haveProof = true + }, + ) + if !haveProof { + return fmt.Errorf("commitment %v has no chain proof", + commitTxid) + } + + transitionRow, err := + db.QuerySupplyCommitTransitionByNewCommitment( + ctx, sqlInt64(commitRow.SupplyCommitment.CommitID), + ) + if err != nil { + return fmt.Errorf("unable to query transition for "+ + "commitment %d: %w", + commitRow.SupplyCommitment.CommitID, err) + } + dbTransition := transitionRow.SupplyCommitTransition + + eventRows, err := db.QuerySupplyUpdateEvents( + ctx, sqlInt64(dbTransition.TransitionID), + ) + if err != nil { + return fmt.Errorf("unable to query update events: "+ + "%w", err) + } + updates = make( + []supplycommit.SupplyUpdateEvent, 0, len(eventRows), + ) + for _, eventRow := range eventRows { + event, err := deserializeSupplyUpdateEvent( + eventRow.UpdateTypeName, + bytes.NewReader(eventRow.EventData), + ) + if err != nil { + return fmt.Errorf("unable to deserialize "+ + "update event: %w", err) + } + updates = append(updates, event) + } + + return nil + }) + if err != nil { + return commitment, nil, chainProof, err + } + + return commitment, updates, chainProof, nil +} + +// FetchSupplyCommitPush loads the push payload for the supply +// commitment that created outpoint. The syncer uses it to insert a +// predecessor the remote universe has not seen. +func (s *SupplyCommitMachine) FetchSupplyCommitPush(ctx context.Context, + assetSpec asset.Specifier, outpoint wire.OutPoint) ( + supplycommit.RootCommitment, supplycommit.SupplyLeaves, + supplycommit.ChainProof, error) { + + var ( + zeroCommit supplycommit.RootCommitment + zeroLeaves supplycommit.SupplyLeaves + zeroProof supplycommit.ChainProof + ) + + groupKey, err := assetSpec.UnwrapGroupKeyOrErr() + if err != nil { + return zeroCommit, zeroLeaves, zeroProof, fmt.Errorf( + "asset specifier missing group key: %w", err) + } + + commitment, updates, chainProof, err := s.FetchCommitmentPushData( + ctx, groupKey, outpoint.Hash, + ) + if err != nil { + return zeroCommit, zeroLeaves, zeroProof, err + } + + if commitment.TxOutIdx != outpoint.Index { + return zeroCommit, zeroLeaves, zeroProof, fmt.Errorf( + "supply commitment %v is at output %d, not %d", + outpoint.Hash, commitment.TxOutIdx, outpoint.Index) + } + + leaves, err := supplycommit.NewSupplyLeavesFromEvents(updates) + if err != nil { + return zeroCommit, zeroLeaves, zeroProof, err + } + + return commitment, leaves, chainProof, nil +} + +var _ supplyverifier.SupplyCommitHistory = (*SupplyCommitMachine)(nil) diff --git a/tapdb/supply_commit_test.go b/tapdb/supply_commit_test.go index 11bae6264e..d2a9378e00 100644 --- a/tapdb/supply_commit_test.go +++ b/tapdb/supply_commit_test.go @@ -1478,6 +1478,76 @@ func TestBindDanglingUpdatesToTransition(t *testing.T) { ) } +// TestBeginIdleTransition tests that an idle transition can only be started +// from the default state with a latest commitment, that it is frozen, that it +// spends the latest commitment and that it picks up dangling updates. +func TestBeginIdleTransition(t *testing.T) { + t.Parallel() + + h := newSupplyCommitTestHarness(t) + + // Without a latest commitment there is nothing to spend, so we expect + // an error and no transition to be created. + _, err := h.commitMachine.BeginIdleTransition(h.ctx, h.assetSpec) + require.Error(t, err) + h.assertNoPendingTransition() + + // Create a finalized transition, so there is a latest commitment. + updates := []supplycommit.SupplyUpdateEvent{h.randMintEvent()} + transition := h.performSingleTransition(updates, []wire.OutPoint{}, 442) + h.assertTransitionApplied(transition) + + stateMachine, err := h.fetchStateMachine() + require.NoError(t, err) + require.True(t, stateMachine.LatestCommitmentID.Valid) + + // Add a dangling update, it should be bound to the idle transition. + dangling := h.randBurnEvent() + err = h.commitMachine.db.ExecTx( + h.ctx, WriteTxOption(), func(db SupplyCommitStore) error { + var b bytes.Buffer + err := serializeSupplyUpdateEvent(&b, dangling) + require.NoError(t, err) + updateTypeID, err := updateTypeToInt( + dangling.SupplySubTreeType(), + ) + require.NoError(t, err) + + return db.InsertSupplyUpdateEvent( + h.ctx, InsertSupplyUpdateEvent{ + GroupKey: h.groupKeyBytes, + UpdateTypeID: updateTypeID, + EventData: b.Bytes(), + }, + ) + }, + ) + require.NoError(t, err) + require.Len(t, h.fetchDanglingUpdates(), 1) + + bound, err := h.commitMachine.BeginIdleTransition(h.ctx, h.assetSpec) + require.NoError(t, err) + require.Len(t, bound, 1) + assertEqualEvents(t, dangling, bound[0]) + require.Empty(t, h.fetchDanglingUpdates()) + + // The new transition is frozen, unfinalized and spends the latest + // commitment, and the machine is now in the updates pending state. + dbTransition := h.assertPendingTransitionExists() + require.True(t, dbTransition.Frozen) + require.False(t, dbTransition.Finalized) + require.Equal( + t, stateMachine.LatestCommitmentID, dbTransition.OldCommitmentID, + ) + h.assertCurrentStateIs(&supplycommit.UpdatesPendingState{}) + h.assertPendingUpdates([]supplycommit.SupplyUpdateEvent{dangling}) + + // Starting another idle transition now must fail, as the machine is + // no longer in the default state. + _, err = h.commitMachine.BeginIdleTransition(h.ctx, h.assetSpec) + require.Error(t, err) +} + // TestSupplyCommitInsertSignedCommitTx tests associating a signed commit tx // with a transition. func TestSupplyCommitInsertSignedCommitTx(t *testing.T) { diff --git a/tapdb/supply_syncer.go b/tapdb/supply_syncer.go index 32060073d0..81d679dff4 100644 --- a/tapdb/supply_syncer.go +++ b/tapdb/supply_syncer.go @@ -104,3 +104,43 @@ func (s *SupplySyncerStore) LogSupplyCommitPush(ctx context.Context, return nil }) } + +// FetchPushedServers returns the addresses of the servers a supply +// commitment has already been pushed to, identified by its commitment +// outpoint. The syncer consults this before a push so a retry after a +// partial failure only targets the servers still missing the +// commitment. +func (s *SupplySyncerStore) FetchPushedServers(ctx context.Context, + assetSpec asset.Specifier, + commitment supplycommit.RootCommitment) ([]string, error) { + + groupKey, err := assetSpec.UnwrapGroupKeyOrErr() + if err != nil { + return nil, fmt.Errorf("group key must be specified for "+ + "supply syncer push lookup: %w", err) + } + groupKeyBytes := schnorr.SerializePubKey(groupKey) + + commitTxid := commitment.Txn.TxHash() + + var servers []string + readTx := NewBaseUniverseReadTx() + dbErr := s.db.ExecTx(ctx, &readTx, func(dbTx BaseUniverseStore) error { + var err error + servers, err = dbTx.FetchSupplySyncerPushedServers( + ctx, sqlc.FetchSupplySyncerPushedServersParams{ + GroupKey: groupKeyBytes, + CommitTxid: commitTxid[:], + OutputIndex: int32(commitment.TxOutIdx), + }, + ) + + return err + }) + if dbErr != nil { + return nil, fmt.Errorf("failed to fetch pushed servers: %w", + dbErr) + } + + return servers, nil +} diff --git a/tapdb/universe.go b/tapdb/universe.go index 932b27df97..ec3d27402d 100644 --- a/tapdb/universe.go +++ b/tapdb/universe.go @@ -168,6 +168,11 @@ type BaseUniverseStore interface { // a given asset group, ordered by creation time (newest first). FetchSupplySyncerPushLogs(ctx context.Context, groupKey []byte) ([]sqlc.SupplySyncerPushLog, error) + + // FetchSupplySyncerPushedServers returns server addresses that + // already received a given supply commitment push. + FetchSupplySyncerPushedServers(ctx context.Context, + arg sqlc.FetchSupplySyncerPushedServersParams) ([]string, error) } // getUniverseTreeSum retrieves the sum of a universe tree specified by its diff --git a/tapfreighter/burn_leaf_proof.go b/tapfreighter/burn_leaf_proof.go new file mode 100644 index 0000000000..a6a77ff918 --- /dev/null +++ b/tapfreighter/burn_leaf_proof.go @@ -0,0 +1,139 @@ +package tapfreighter + +import ( + "bytes" + "fmt" + + "github.com/lightninglabs/taproot-assets/asset" + "github.com/lightninglabs/taproot-assets/proof" +) + +// BurnLeafProof returns a self-contained copy of a confirmed burn suffix for a +// supply-commitment burn leaf. Universe servers verify that leaf with no prior +// snapshot, so the copy embeds the full proof file of every input the burn +// spends, including the primary input whose provenance a proof file would +// otherwise carry as its prefix. +func BurnLeafProof(suffix *proof.Proof, + inputFiles map[asset.PrevID]*proof.File) (*proof.Proof, error) { + + if suffix == nil { + return nil, fmt.Errorf("burn output proof suffix is nil") + } + + witnesses := suffix.Asset.Witnesses() + if len(witnesses) == 0 { + return nil, fmt.Errorf("burn output has no input witnesses") + } + + seen := make(map[asset.PrevID]struct{}, len(witnesses)) + files := make([]proof.File, 0, len(witnesses)) + for idx := range witnesses { + prevID := witnesses[idx].PrevID + if prevID == nil { + return nil, fmt.Errorf("burn input witness %d has "+ + "no previous ID", idx) + } + if _, ok := seen[*prevID]; ok { + return nil, fmt.Errorf("duplicate burn input %v", + prevID.OutPoint) + } + seen[*prevID] = struct{}{} + + inputFile := inputFiles[*prevID] + if inputFile == nil { + return nil, fmt.Errorf("missing proof for burn "+ + "input %v", prevID.OutPoint) + } + if inputFile.NumProofs() == 0 { + return nil, fmt.Errorf("empty proof for burn input %v", + prevID.OutPoint) + } + + last, err := inputFile.LastProof() + if err != nil { + return nil, fmt.Errorf("invalid proof for burn "+ + "input %v: %w", prevID.OutPoint, err) + } + + lastID := asset.PrevID{ + OutPoint: last.OutPoint(), + ID: last.Asset.ID(), + ScriptKey: asset.ToSerialized( + last.Asset.ScriptKey.PubKey, + ), + } + if lastID != *prevID { + return nil, fmt.Errorf("burn input proof mismatch: "+ + "expected %v, got %v", *prevID, lastID) + } + + files = append(files, *inputFile) + } + + var buf bytes.Buffer + if err := suffix.Encode(&buf); err != nil { + return nil, fmt.Errorf("unable to encode burn proof: %w", err) + } + + burnProof := &proof.Proof{} + if err := burnProof.Decode(bytes.NewReader(buf.Bytes())); err != nil { + return nil, fmt.Errorf("unable to decode burn proof: %w", err) + } + + burnProof.AdditionalInputs = files + + var encoded bytes.Buffer + if err := burnProof.Encode(&encoded); err != nil { + return nil, fmt.Errorf("unable to encode burn leaf: %w", err) + } + if encoded.Len() > proof.FileMaxProofSizeBytes { + return nil, fmt.Errorf("burn leaf proof is too large: "+ + "%d bytes, max is %d", encoded.Len(), + proof.FileMaxProofSizeBytes) + } + + return burnProof, nil +} + +// cloneProof returns an independent copy of a transition proof. +func cloneProof(p *proof.Proof) (*proof.Proof, error) { + if p == nil { + return nil, fmt.Errorf("proof is nil") + } + + var buf bytes.Buffer + if err := p.Encode(&buf); err != nil { + return nil, err + } + + cloned := &proof.Proof{} + if err := cloned.Decode(bytes.NewReader(buf.Bytes())); err != nil { + return nil, err + } + + return cloned, nil +} + +// CloneProofFile returns an independent copy of a proof file. +func CloneProofFile(file *proof.File) (*proof.File, error) { + return cloneProofFile(file) +} + +// cloneProofFile returns an independent copy of a proof file. +func cloneProofFile(file *proof.File) (*proof.File, error) { + if file == nil { + return nil, fmt.Errorf("proof file is nil") + } + + var buf bytes.Buffer + if err := file.Encode(&buf); err != nil { + return nil, err + } + + cloned := &proof.File{} + if err := cloned.Decode(bytes.NewReader(buf.Bytes())); err != nil { + return nil, err + } + + return cloned, nil +} diff --git a/tapfreighter/chain_porter.go b/tapfreighter/chain_porter.go index 06ee62532c..6d4f3ee7fb 100644 --- a/tapfreighter/chain_porter.go +++ b/tapfreighter/chain_porter.go @@ -155,6 +155,25 @@ type ChainPorter struct { // subscriberMtx guards the subscribers map. subscriberMtx sync.Mutex + // publishMu guards pre-anchored in-flight shipments, the + // in-flight request ID bindings, and terminal broadcast errors. + publishMu sync.Mutex + + // preAnchoredFlights coalesces concurrent publishes of one anchor + // transaction so a retry cannot start a second state machine. + preAnchoredFlights map[chainhash.Hash]*preAnchoredFlight + + // publishRequestIDs binds a caller request ID to the anchor + // transaction of the publish that is using it. The binding is + // removed when that publish completes or fails. + publishRequestIDs map[string]chainhash.Hash + + // terminalBroadcasts records anchors whose broadcast failed with + // ErrDoubleSpend. The transfer row is written before that + // broadcast, so a later publish of the same anchor must return + // this failure instead of the row. + terminalBroadcasts map[chainhash.Hash]error + *fn.ContextGuard } @@ -168,6 +187,13 @@ func NewChainPorter(cfg *ChainPorterConfig) *ChainPorter { cfg: cfg, outboundParcels: make(chan Parcel), subscribers: subscribers, + preAnchoredFlights: make( + map[chainhash.Hash]*preAnchoredFlight, + ), + publishRequestIDs: make(map[string]chainhash.Hash), + terminalBroadcasts: make( + map[chainhash.Hash]error, + ), ContextGuard: &fn.ContextGuard{ DefaultTimeout: tapgarden.DefaultTimeout, Quit: make(chan struct{}), @@ -313,20 +339,15 @@ func (p *ChainPorter) RequestShipment(req Parcel) (*OutboundParcel, error) { return nil, fmt.Errorf("failed to validate parcel: %w", err) } - if !fn.SendOrQuit(p.outboundParcels, req, p.Quit) { - return nil, fmt.Errorf("ChainPorter shutting down") + // A pre-anchored publish is the custom-anchor terminal step. A retry + // after a lost response must return the transfer already logged for + // that anchor instead of running the state machine again. + anchored, ok := req.(*PreAnchoredParcel) + if ok { + return p.requestPreAnchoredShipment(anchored) } - select { - case err := <-req.kit().errChan: - return nil, err - - case resp := <-req.kit().respChan: - return resp, nil - - case <-p.Quit: - return nil, fmt.Errorf("ChainPorter shutting down") - } + return p.enqueueShipment(req) } // QueryParcels returns the set of confirmed or unconfirmed parcels. If the @@ -918,7 +939,6 @@ func (p *ChainPorter) storePackageAnchorTxConf(pkg *sendPackage) error { } anchorTxBlockHeight := int32(pkg.TransferTxConfEvent.BlockHeight) - anchorTxBlockHeader := pkg.TransferTxConfEvent.Block.Header // Now we scan through the VPacket for any burns. // @@ -936,6 +956,61 @@ func (p *ChainPorter) storePackageAnchorTxConf(pkg *sendPackage) error { assetID := o.Asset.ID() + if o.ProofSuffix == nil { + return fmt.Errorf("burn output missing proof "+ + "suffix") + } + + parsedSuffix, err := cloneProof(o.ProofSuffix) + if err != nil { + return fmt.Errorf("error copying burn proof "+ + "suffix: %w", err) + } + + err = parsedSuffix.UpdateTransitionProof( + &proof.BaseProofParams{ + Block: pkg.TransferTxConfEvent.Block, + BlockHeight: pkg.TransferTxConfEvent.BlockHeight, + Tx: pkg.TransferTxConfEvent.Tx, + TxIndex: int( + pkg.TransferTxConfEvent.TxIndex, + ), + }, + ) + if err != nil { + return fmt.Errorf("error updating burn "+ + "transition proof: %w", err) + } + + burnInputs := make(map[asset.PrevID]*proof.File) + for _, witness := range parsedSuffix.Asset.Witnesses() { + if witness.PrevID == nil { + continue + } + + prevID := *witness.PrevID + inputFile, err := p.fetchInputProof( + ctx, prevID, + ) + if err != nil { + return fmt.Errorf("error fetching burn "+ + "input proof: %w", err) + } + + cloned, err := cloneProofFile(inputFile) + if err != nil { + return fmt.Errorf("unable to copy burn "+ + "input proof: %w", err) + } + burnInputs[prevID] = cloned + } + + burnProof, err := BurnLeafProof(parsedSuffix, burnInputs) + if err != nil { + return fmt.Errorf("unable to build burn "+ + "proof: %w", err) + } + // We prepare the burn and add it to the list. op := wire.OutPoint{ Hash: pkg.OutboundPkg.AnchorTx.TxHash(), @@ -948,14 +1023,10 @@ func (p *ChainPorter) storePackageAnchorTxConf(pkg *sendPackage) error { AnchorTxid: pkg.OutboundPkg.AnchorTx.TxHash(), Note: pkg.Note, ScriptKey: &o.Asset.ScriptKey, - Proof: o.ProofSuffix, + Proof: burnProof, OutPoint: op, } - // Set the block height and header in the burn proof. - b.Proof.BlockHeight = uint32(anchorTxBlockHeight) - b.Proof.BlockHeader = anchorTxBlockHeader - if o.Asset.GroupKey != nil { groupKey := o.Asset.GroupKey.GroupPubKey b.GroupKey = groupKey.SerializeCompressed() diff --git a/tapfreighter/fund_test.go b/tapfreighter/fund_test.go index df0e9f5300..fd45d53fcc 100644 --- a/tapfreighter/fund_test.go +++ b/tapfreighter/fund_test.go @@ -822,3 +822,90 @@ func TestFundPacket(t *testing.T) { }) } } + +// fetchOnlyArchiver adapts mockExporter to the Archiver interface. FundPacket +// only fetches the input proof on the success path exercised below. +type fetchOnlyArchiver struct { + *mockExporter +} + +func (f *fetchOnlyArchiver) FetchIssuanceProof(context.Context, asset.ID, + wire.OutPoint) (proof.Blob, error) { + + return nil, proof.ErrProofNotFound +} + +func (f *fetchOnlyArchiver) HasProof(context.Context, proof.Locator) (bool, + error) { + + return false, nil +} + +func (f *fetchOnlyArchiver) FetchProofs(context.Context, + asset.ID) ([]*proof.AnnotatedProof, error) { + + return nil, nil +} + +func (f *fetchOnlyArchiver) ImportProofs(context.Context, proof.VerifierCtx, + bool, ...*proof.AnnotatedProof) error { + + return nil +} + +// TestFundPacketSuccessKeepsLease makes sure a funded packet does not release +// the coins it just selected. Releasing on the success path would undo the +// lease the caller is about to spend. +func TestFundPacketSuccessKeepsLease(t *testing.T) { + ctx := context.Background() + + internalKey, _ := test.RandKeyDesc(t) + scriptKey := asset.RandScriptKey(t) + + const mintAmount = 500 + inputProof := randProof(t, mintAmount, internalKey, nil) + inputAsset := inputProof.Asset + inputCommitment, err := commitment.FromAssets(nil, &inputProof.Asset) + require.NoError(t, err) + + sel := &recordingSelector{ + selected: []*AnchoredCommitment{{ + AnchorPoint: inputProof.OutPoint(), + InternalKey: internalKey, + Commitment: inputCommitment, + Asset: &inputAsset, + }}, + } + wallet := NewAssetWallet(&WalletConfig{ + CoinSelector: sel, + AssetProofs: &fetchOnlyArchiver{ + mockExporter: &mockExporter{ + proofs: []*proof.Proof{&inputProof}, + }, + }, + AddrBook: &mockAddrBook{}, + KeyRing: tapgarden.NewMockKeyRing(), + ChainParams: testParams, + DisableSweepOrphanUtxos: true, + }) + + funded, err := wallet.FundPacket( + ctx, &tapsend.FundingDescriptor{ + AssetSpecifier: asset.NewSpecifierFromId( + inputAsset.ID(), + ), + Amount: 20, + }, + &tappsbt.VPacket{ + ChainParams: testParams, + Outputs: []*tappsbt.VOutput{{ + Amount: 20, + ScriptKey: scriptKey, + Interactive: false, + }}, + }, + ) + require.NoError(t, err) + require.NotNil(t, funded) + require.Zero(t, sel.releaseHits) +} diff --git a/tapfreighter/parcel.go b/tapfreighter/parcel.go index e7d335e241..239e84fd2b 100644 --- a/tapfreighter/parcel.go +++ b/tapfreighter/parcel.go @@ -436,6 +436,11 @@ type PreAnchoredParcel struct { // anchorTxHeightHint is an optional height hint for the anchor // transaction. anchorTxHeightHint fn.Option[uint32] + + // requestID is the caller's idempotency key for this publish. + // Empty means the caller did not set one. The anchor transaction + // remains the durable reconciliation key either way. + requestID []byte } // A compile-time assertion to ensure PreAnchoredParcel implements the Parcel @@ -462,6 +467,19 @@ func NewPreAnchoredParcel(vPackets []*tappsbt.VPacket, } } +// SetRequestID records the caller's idempotency key. A repeated key must +// refer to the same anchor transaction. An empty key clears any previous +// value. +func (p *PreAnchoredParcel) SetRequestID(id []byte) { + if len(id) == 0 { + p.requestID = nil + + return + } + + p.requestID = append([]byte(nil), id...) +} + // pkg returns the send package that should be delivered. func (p *PreAnchoredParcel) pkg() *sendPackage { log.Infof("New anchored delivery request with %d packets", diff --git a/tapfreighter/publish_idempotency.go b/tapfreighter/publish_idempotency.go new file mode 100644 index 0000000000..9936577029 --- /dev/null +++ b/tapfreighter/publish_idempotency.go @@ -0,0 +1,185 @@ +package tapfreighter + +import ( + "errors" + "fmt" + + "github.com/btcsuite/btcd/chaincfg/chainhash" + "github.com/lightninglabs/taproot-assets/fn" + "github.com/lightningnetwork/lnd/lnwallet" +) + +// ErrPublishRequestIDReused is returned when a publish request ID is +// presented again for a different anchor transaction than the one it was +// first bound to. +var ErrPublishRequestIDReused = errors.New("publish request id already " + + "used for a different anchor transaction") + +// preAnchoredFlight is one in-flight pre-anchored publish. Followers +// wait on done and share the leader's result. +type preAnchoredFlight struct { + done chan struct{} + resp *OutboundParcel + err error +} + +func newPreAnchoredFlight() *preAnchoredFlight { + return &preAnchoredFlight{ + done: make(chan struct{}), + } +} + +func (f *preAnchoredFlight) wait() (*OutboundParcel, error) { + <-f.done + + return f.resp, f.err +} + +func (f *preAnchoredFlight) finish(resp *OutboundParcel, err error) { + f.resp = resp + f.err = err + close(f.done) +} + +// requestPreAnchoredShipment reconciles a pre-anchored publish with a +// transfer already logged for its anchor, and coalesces concurrent +// publishes of that anchor onto one shipment. +func (p *ChainPorter) requestPreAnchoredShipment( + parcel *PreAnchoredParcel) (*OutboundParcel, error) { + + txHash := parcel.anchorTx.FinalTx.TxHash() + + p.publishMu.Lock() + if err := p.bindPublishRequestID(parcel.requestID, txHash); err != nil { + p.publishMu.Unlock() + + return nil, err + } + if flight := p.preAnchoredFlights[txHash]; flight != nil { + p.publishMu.Unlock() + + return flight.wait() + } + + flight := newPreAnchoredFlight() + p.preAnchoredFlights[txHash] = flight + p.publishMu.Unlock() + + resp, err := p.shipPreAnchored(parcel) + + p.publishMu.Lock() + // The row is durable before broadcast. Remember a double spend + // so a retry cannot report that row as a successful publish. + if errors.Is(err, lnwallet.ErrDoubleSpend) { + p.terminalBroadcasts[txHash] = err + } + flight.finish(resp, err) + delete(p.preAnchoredFlights, txHash) + // Followers bind before they wait, so every ID for this anchor + // is in the map. Drop them with the flight: the binding only has + // to reject reuse while the publish is in flight. + p.releasePublishRequestIDs(txHash) + p.publishMu.Unlock() + + return resp, err +} + +// bindPublishRequestID records that id belongs to txHash. The caller must +// hold publishMu. An empty id is not bound. Reuse for a different anchor +// is rejected. +func (p *ChainPorter) bindPublishRequestID(id []byte, + txHash chainhash.Hash) error { + + if len(id) == 0 { + return nil + } + + key := string(id) + prev, ok := p.publishRequestIDs[key] + if ok && prev != txHash { + return fmt.Errorf("%w", ErrPublishRequestIDReused) + } + + p.publishRequestIDs[key] = txHash + + return nil +} + +// releasePublishRequestIDs drops every request ID bound to txHash. The +// caller must hold publishMu. IDs for other anchors are left in place, +// including ones whose publish is still in flight. +func (p *ChainPorter) releasePublishRequestIDs(txHash chainhash.Hash) { + for key, bound := range p.publishRequestIDs { + if bound == txHash { + delete(p.publishRequestIDs, key) + } + } +} + +// terminalBroadcastFailure returns the double-spend error recorded for +// txHash, or nil. The caller must not hold publishMu. +func (p *ChainPorter) terminalBroadcastFailure( + txHash chainhash.Hash) error { + + p.publishMu.Lock() + defer p.publishMu.Unlock() + + return p.terminalBroadcasts[txHash] +} + +// shipPreAnchored returns the transfer already logged for the parcel's +// anchor, or enqueues a new shipment when none is logged. A logged +// anchor whose broadcast failed with ErrDoubleSpend is returned as +// that failure. +func (p *ChainPorter) shipPreAnchored( + parcel *PreAnchoredParcel) (*OutboundParcel, error) { + + ctx, cancel := p.WithCtxQuit() + defer cancel() + + txHash := parcel.anchorTx.FinalTx.TxHash() + existing, err := p.QueryParcels(ctx, fn.Some(txHash), false) + if err != nil { + return nil, fmt.Errorf("unable to query logged transfer: %w", + err) + } + if len(existing) > 0 { + // A row is written in StorePreBroadcast, before + // PublishTransaction. ErrDoubleSpend means that anchor + // can never confirm; the row is not a successful publish. + bcastErr := p.terminalBroadcastFailure(txHash) + if bcastErr != nil { + log.Infof("Anchor transaction %v was logged but its "+ + "broadcast failed and can never confirm", + txHash) + + return nil, bcastErr + } + + log.Infof("Anchor transaction %v already logged; returning "+ + "the existing transfer", txHash) + + return existing[0], nil + } + + return p.enqueueShipment(parcel) +} + +// enqueueShipment hands a parcel to the porter state machine and waits +// for its initial response. +func (p *ChainPorter) enqueueShipment(req Parcel) (*OutboundParcel, error) { + if !fn.SendOrQuit(p.outboundParcels, req, p.Quit) { + return nil, fmt.Errorf("ChainPorter shutting down") + } + + select { + case err := <-req.kit().errChan: + return nil, err + + case resp := <-req.kit().respChan: + return resp, nil + + case <-p.Quit: + return nil, fmt.Errorf("ChainPorter shutting down") + } +} diff --git a/tapfreighter/publish_idempotency_test.go b/tapfreighter/publish_idempotency_test.go new file mode 100644 index 0000000000..427e95a188 --- /dev/null +++ b/tapfreighter/publish_idempotency_test.go @@ -0,0 +1,555 @@ +package tapfreighter + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + "runtime" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/btcsuite/btcd/chaincfg/chainhash" + "github.com/btcsuite/btcd/btcutil/psbt" + "github.com/btcsuite/btcd/wire" + "github.com/lightninglabs/taproot-assets/fn" + "github.com/lightninglabs/taproot-assets/tappsbt" + "github.com/lightninglabs/taproot-assets/tapsend" + "github.com/lightningnetwork/lnd/lnwallet" + "github.com/stretchr/testify/require" +) + +// queryParcelLog is an ExportLog that serves parcels by anchor txid. +type queryParcelLog struct { + ExportLog + + mu sync.Mutex + parcels []*OutboundParcel + err error + calls atomic.Int32 + + // block, when set, is waited on inside QueryParcels. + block chan struct{} +} + +func (q *queryParcelLog) QueryParcels(_ context.Context, + anchorTxHash *chainhash.Hash, _ bool) ([]*OutboundParcel, error) { + + q.calls.Add(1) + if q.block != nil { + <-q.block + } + if q.err != nil { + return nil, q.err + } + if anchorTxHash == nil { + return nil, nil + } + + q.mu.Lock() + defer q.mu.Unlock() + + var matched []*OutboundParcel + for _, parcel := range q.parcels { + if parcel.AnchorTx == nil { + continue + } + if parcel.AnchorTx.TxHash() == *anchorTxHash { + matched = append(matched, parcel) + } + } + + return matched, nil +} + +func testAnchorTx(value int64) *wire.MsgTx { + tx := wire.NewMsgTx(2) + tx.AddTxIn(wire.NewTxIn(&wire.OutPoint{}, nil, nil)) + tx.AddTxOut(wire.NewTxOut(value, []byte{0x51})) + + return tx +} + +func testPreAnchoredParcel(tx *wire.MsgTx) *PreAnchoredParcel { + return NewPreAnchoredParcel( + []*tappsbt.VPacket{{ + Outputs: []*tappsbt.VOutput{{}}, + }}, + nil, + &tapsend.AnchorTransaction{ + FundedPsbt: &tapsend.FundedPsbt{ + Pkt: &psbt.Packet{}, + }, + FinalTx: tx, + }, + true, "pubandlog", fn.None[uint32](), + ) +} + +func testPorter(log ExportLog) *ChainPorter { + return NewChainPorter(&ChainPorterConfig{ + ExportLog: log, + }) +} + +// shipmentResult is the outcome of one RequestShipment call. +type shipmentResult struct { + resp *OutboundParcel + err error +} + +// requestShipmentAsync runs RequestShipment and fails the test if it does +// not return before the timeout. A lost-response retry must not block in +// the state machine once the anchor is already logged. +func requestShipmentAsync(t *testing.T, porter *ChainPorter, + parcel Parcel) shipmentResult { + + t.Helper() + + result := make(chan shipmentResult, 1) + go func() { + resp, err := porter.RequestShipment(parcel) + result <- shipmentResult{resp: resp, err: err} + }() + + select { + case got := <-result: + return got + + case <-time.After(2 * time.Second): + t.Fatal("shipment did not return") + return shipmentResult{} + } +} + +// TestPreAnchoredShipmentReturnsLoggedTransfer asserts that a repeat +// publish of an anchor that is already logged returns that transfer and +// does not enqueue another shipment. +func TestPreAnchoredShipmentReturnsLoggedTransfer(t *testing.T) { + t.Parallel() + + tx := testAnchorTx(1_000) + logged := &OutboundParcel{ + AnchorTx: tx, + Label: "existing", + } + log := &queryParcelLog{ + parcels: []*OutboundParcel{logged}, + } + porter := testPorter(log) + t.Cleanup(func() { + close(porter.Quit) + }) + + parcel := testPreAnchoredParcel(tx) + parcel.SetRequestID([]byte("req-1")) + + got := requestShipmentAsync(t, porter, parcel) + require.NoError(t, got.err) + require.Same(t, logged, got.resp) + + // A second call, with a different request ID, still returns the + // logged transfer. The new ID is then bound to this anchor. + other := testPreAnchoredParcel(tx) + other.SetRequestID([]byte("req-2")) + got = requestShipmentAsync(t, porter, other) + require.NoError(t, got.err) + require.Same(t, logged, got.resp) + + // An empty request ID reconciles the same way. + plain := testPreAnchoredParcel(tx) + got = requestShipmentAsync(t, porter, plain) + require.NoError(t, got.err) + require.Same(t, logged, got.resp) + + select { + case extra := <-porter.outboundParcels: + t.Fatalf("logged anchor was shipped again: %v", extra) + + default: + } +} + +// TestPreAnchoredShipmentDoesNotSucceedAfterDoubleSpend asserts that a +// transfer row written before broadcast is not a successful publish when +// that broadcast failed with ErrDoubleSpend. A retry must surface the +// failure. The same anchor with no request ID, the shape channel +// funding uses, is not a success either. +func TestPreAnchoredShipmentDoesNotSucceedAfterDoubleSpend(t *testing.T) { + t.Parallel() + + tx := testAnchorTx(1_000) + parcelLog := &queryParcelLog{} + porter := testPorter(parcelLog) + t.Cleanup(func() { + close(porter.Quit) + }) + + parcel := testPreAnchoredParcel(tx) + parcel.SetRequestID([]byte("req-fail")) + + done := make(chan shipmentResult, 1) + go func() { + resp, err := porter.RequestShipment(parcel) + done <- shipmentResult{resp: resp, err: err} + }() + + var got Parcel + select { + case got = <-porter.outboundParcels: + case <-time.After(2 * time.Second): + t.Fatal("anchor was not shipped") + } + + // StorePreBroadcast has already persisted the row. Broadcast then + // fails because the anchor can never confirm. + got.kit().errChan <- fmt.Errorf("unable to broadcast "+ + "transaction %v: %w", tx.TxHash(), lnwallet.ErrDoubleSpend) + + select { + case result := <-done: + require.ErrorIs(t, result.err, lnwallet.ErrDoubleSpend) + + case <-time.After(2 * time.Second): + t.Fatal("broadcast failure was not delivered") + } + + parcelLog.mu.Lock() + parcelLog.parcels = []*OutboundParcel{{ + AnchorTx: tx, + Label: "stranded", + }} + parcelLog.mu.Unlock() + + retry := testPreAnchoredParcel(tx) + retry.SetRequestID([]byte("req-fail")) + gotRetry := requestShipmentAsync(t, porter, retry) + require.ErrorIs(t, gotRetry.err, lnwallet.ErrDoubleSpend) + require.Nil(t, gotRetry.resp) + + // Channel funding and close ship a pre-anchored parcel with no + // request ID. A failed broadcast of that anchor is the same row. + plain := testPreAnchoredParcel(tx) + gotPlain := requestShipmentAsync(t, porter, plain) + require.ErrorIs(t, gotPlain.err, lnwallet.ErrDoubleSpend) + require.Nil(t, gotPlain.resp) + + select { + case extra := <-porter.outboundParcels: + t.Fatalf("failed anchor was shipped again: %v", extra) + + default: + } +} + +// TestPreAnchoredShipmentRejectsReusedRequestID asserts that one request +// ID cannot publish two different anchor transactions while the first +// publish is still in flight. +func TestPreAnchoredShipmentRejectsReusedRequestID(t *testing.T) { + t.Parallel() + + tx := testAnchorTx(1_000) + block := make(chan struct{}) + parcelLog := &queryParcelLog{block: block} + porter := testPorter(parcelLog) + t.Cleanup(func() { + close(porter.Quit) + }) + + first := testPreAnchoredParcel(tx) + first.SetRequestID([]byte("same-id")) + + done := make(chan shipmentResult, 1) + go func() { + resp, err := porter.RequestShipment(first) + done <- shipmentResult{resp: resp, err: err} + }() + + require.Eventually(t, func() bool { + return parcelLog.calls.Load() >= 1 + }, time.Second, 5*time.Millisecond) + + other := testPreAnchoredParcel(testAnchorTx(2_000)) + other.SetRequestID([]byte("same-id")) + got := requestShipmentAsync(t, porter, other) + require.ErrorIs(t, got.err, ErrPublishRequestIDReused) + + close(block) + + var shipped Parcel + select { + case shipped = <-porter.outboundParcels: + case <-time.After(2 * time.Second): + t.Fatal("in-flight anchor was not shipped") + } + + logged := &OutboundParcel{AnchorTx: tx} + shipped.kit().respChan <- logged + + select { + case result := <-done: + require.NoError(t, result.err) + require.Equal(t, logged, result.resp) + + case <-time.After(2 * time.Second): + t.Fatal("in-flight shipment did not finish") + } +} + +// TestPublishRequestIDsReleasedWhenPublishEnds asserts that a request +// ID is dropped once its publish completes, so distinct IDs do not +// accumulate for the life of the process. +func TestPublishRequestIDsReleasedWhenPublishEnds(t *testing.T) { + t.Parallel() + + const n = 8 + parcels := make([]*OutboundParcel, n) + for i := 0; i < n; i++ { + parcels[i] = &OutboundParcel{ + AnchorTx: testAnchorTx(int64(1_000 + i)), + } + } + porter := testPorter(&queryParcelLog{parcels: parcels}) + t.Cleanup(func() { + close(porter.Quit) + }) + + for i := 0; i < n; i++ { + parcel := testPreAnchoredParcel(parcels[i].AnchorTx) + parcel.SetRequestID([]byte{byte(i + 1)}) + got := requestShipmentAsync(t, porter, parcel) + require.NoError(t, got.err) + require.Same(t, parcels[i], got.resp) + } + + porter.publishMu.Lock() + defer porter.publishMu.Unlock() + require.Empty(t, porter.publishRequestIDs) +} + +// TestPublishRequestIDContractIsProcessLocal asserts the published +// contract matches the binding we keep: process-local and in-flight +// only. A new porter is a restart and accepts an id the previous +// process already used. +func TestPublishRequestIDContractIsProcessLocal(t *testing.T) { + t.Parallel() + + _, file, _, ok := runtime.Caller(0) + require.True(t, ok) + root := filepath.Join(filepath.Dir(file), "..") + + const phrase = "process-local and in-flight only" + for _, rel := range []string{ + "taprpc/assetwalletrpc/assetwallet.proto", + "docs/release-notes/release-notes-0.9.0.md", + } { + body, err := os.ReadFile(filepath.Join(root, rel)) + require.NoError(t, err) + require.Contains(t, string(body), phrase, rel) + } + + notes, err := os.ReadFile(filepath.Join( + root, "docs/release-notes/release-notes-0.9.0.md", + )) + require.NoError(t, err) + require.NotContains(t, string(notes), "life of the process") + + tx := testAnchorTx(1_000) + previous := testPorter(&queryParcelLog{ + parcels: []*OutboundParcel{{AnchorTx: tx}}, + }) + t.Cleanup(func() { + close(previous.Quit) + }) + + parcel := testPreAnchoredParcel(tx) + parcel.SetRequestID([]byte("restart-id")) + got := requestShipmentAsync(t, previous, parcel) + require.NoError(t, got.err) + + restarted := testPorter(&queryParcelLog{}) + t.Cleanup(func() { + close(restarted.Quit) + }) + + other := testPreAnchoredParcel(testAnchorTx(2_000)) + other.SetRequestID([]byte("restart-id")) + + done := make(chan shipmentResult, 1) + go func() { + resp, err := restarted.RequestShipment(other) + done <- shipmentResult{resp: resp, err: err} + }() + + select { + case shipped := <-restarted.outboundParcels: + shipped.kit().respChan <- &OutboundParcel{ + AnchorTx: other.anchorTx.FinalTx, + } + + case result := <-done: + require.NotErrorIs(t, result.err, ErrPublishRequestIDReused) + t.Fatalf("restarted porter rejected the publish: %v", + result.err) + + case <-time.After(2 * time.Second): + t.Fatal("restarted porter did not accept the request id") + } + + select { + case result := <-done: + require.NoError(t, result.err) + + case <-time.After(2 * time.Second): + t.Fatal("restarted publish did not finish") + } +} + +// TestPreAnchoredShipmentQueryErrorDoesNotEnqueue asserts that a failed +// transfer lookup is returned to the caller and does not start a +// shipment that might log a second row. +func TestPreAnchoredShipmentQueryErrorDoesNotEnqueue(t *testing.T) { + t.Parallel() + + queryErr := errors.New("db down") + porter := testPorter(&queryParcelLog{err: queryErr}) + t.Cleanup(func() { + close(porter.Quit) + }) + + got := requestShipmentAsync(t, porter, testPreAnchoredParcel( + testAnchorTx(1_000), + )) + require.ErrorIs(t, got.err, queryErr) + + select { + case extra := <-porter.outboundParcels: + t.Fatalf("shipment enqueued after query error: %v", extra) + + default: + } +} + +// TestPreAnchoredShipmentEnqueuesNewAnchor asserts that an anchor with +// no logged transfer is still handed to the state machine. +func TestPreAnchoredShipmentEnqueuesNewAnchor(t *testing.T) { + t.Parallel() + + tx := testAnchorTx(1_000) + porter := testPorter(&queryParcelLog{}) + t.Cleanup(func() { + close(porter.Quit) + }) + + parcel := testPreAnchoredParcel(tx) + parcel.SetRequestID([]byte("new")) + + done := make(chan shipmentResult, 1) + go func() { + resp, err := porter.RequestShipment(parcel) + done <- shipmentResult{resp: resp, err: err} + }() + + var got Parcel + select { + case got = <-porter.outboundParcels: + case <-time.After(2 * time.Second): + t.Fatal("new anchor was not shipped") + } + + shipped := &OutboundParcel{AnchorTx: tx, Label: "shipped"} + got.kit().respChan <- shipped + + select { + case result := <-done: + require.NoError(t, result.err) + require.Equal(t, shipped, result.resp) + + case <-time.After(2 * time.Second): + t.Fatal("shipment result was not delivered") + } +} + +// TestPreAnchoredShipmentCoalescesInFlight asserts that two publishes of +// an anchor that is not yet logged share one state-machine run. +func TestPreAnchoredShipmentCoalescesInFlight(t *testing.T) { + t.Parallel() + + tx := testAnchorTx(1_000) + block := make(chan struct{}) + log := &queryParcelLog{block: block} + porter := testPorter(log) + t.Cleanup(func() { + close(porter.Quit) + }) + + start := make(chan struct{}) + var ready sync.WaitGroup + ready.Add(2) + + results := make([]shipmentResult, 2) + var wg sync.WaitGroup + for idx := 0; idx < 2; idx++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + + ready.Done() + <-start + + parcel := testPreAnchoredParcel(tx) + parcel.SetRequestID([]byte{byte(i + 1)}) + resp, err := porter.RequestShipment(parcel) + results[i] = shipmentResult{resp: resp, err: err} + }(idx) + } + ready.Wait() + close(start) + + require.Eventually(t, func() bool { + return log.calls.Load() >= 1 + }, time.Second, 5*time.Millisecond) + + // The follower must join the in-flight publish rather than query + // and enqueue a second one. + time.Sleep(50 * time.Millisecond) + require.EqualValues(t, 1, log.calls.Load()) + + close(block) + + var got Parcel + select { + case got = <-porter.outboundParcels: + case <-time.After(2 * time.Second): + t.Fatal("in-flight anchor was not shipped") + } + + select { + case extra := <-porter.outboundParcels: + t.Fatalf("second shipment enqueued: %v", extra) + + default: + } + + shipped := &OutboundParcel{AnchorTx: tx, Label: "once"} + got.kit().respChan <- shipped + + finished := make(chan struct{}) + go func() { + wg.Wait() + close(finished) + }() + select { + case <-finished: + case <-time.After(2 * time.Second): + t.Fatal("in-flight shipments did not finish") + } + + require.NoError(t, results[0].err) + require.NoError(t, results[1].err) + require.Equal(t, shipped, results[0].resp) + require.Equal(t, shipped, results[1].resp) +} diff --git a/tapfreighter/release_coins_test.go b/tapfreighter/release_coins_test.go new file mode 100644 index 0000000000..3c1edff232 --- /dev/null +++ b/tapfreighter/release_coins_test.go @@ -0,0 +1,174 @@ +package tapfreighter + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/btcsuite/btcd/wire" + "github.com/lightninglabs/taproot-assets/commitment" + "github.com/lightninglabs/taproot-assets/tappsbt" + "github.com/lightninglabs/taproot-assets/tapsend" + "github.com/stretchr/testify/require" +) + +type mockCoinReleaser struct { + ctx context.Context + ctxErr error + hasDeadline bool + deadline time.Time + outpoints []wire.OutPoint +} + +func (m *mockCoinReleaser) ReleaseCoins(ctx context.Context, + ops ...wire.OutPoint) error { + + m.ctx = ctx + m.ctxErr = ctx.Err() + m.deadline, m.hasDeadline = ctx.Deadline() + m.outpoints = ops + + return ctx.Err() +} + +// TestReleaseCoinsDetached makes sure coins are released even if the caller +// context is already canceled (taproot-assets#2206) and that the release is +// bounded. +func TestReleaseCoinsDetached(t *testing.T) { + t.Parallel() + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + ops := []wire.OutPoint{{Index: 1}, {Index: 2}} + m := &mockCoinReleaser{} + start := time.Now() + releaseCoinsDetached(ctx, m, ops) + + require.NoError(t, m.ctxErr) + require.Equal(t, ops, m.outpoints) + require.True(t, m.hasDeadline) + require.LessOrEqual( + t, m.deadline.Sub(start), coinReleaseTimeout+time.Second, + ) +} + +// TestReleaseCoinsDetachedKeepsValues makes sure context values of the caller +// context are preserved on the release context. +func TestReleaseCoinsDetachedKeepsValues(t *testing.T) { + t.Parallel() + + type key struct{} + parent := context.WithValue(context.Background(), key{}, "v") + + m := &mockCoinReleaser{} + releaseCoinsDetached(parent, m, nil) + require.Equal(t, "v", m.ctx.Value(key{})) +} + +// recordingSelector fails the orphan sweep after selection so FundPacket and +// FundBurn return on the deferred release path. Release state is snapshotted +// inside ReleaseCoins: the helper cancels its timeout context before +// returning, so the context is done by the time the caller looks at it. +type recordingSelector struct { + selected []*AnchoredCommitment + releaseErr error + releaseValue any + hasDeadline bool + deadline time.Time + released []wire.OutPoint + releaseHits int +} + +func (s *recordingSelector) SelectCoins(_ context.Context, + _ CommitmentConstraints, _ MultiCommitmentSelectStrategy, + _ commitment.TapCommitmentVersion) ([]*AnchoredCommitment, error) { + + return s.selected, nil +} + +func (s *recordingSelector) SelectOrphanCoins(context.Context) ( + []*ZeroValueInput, error) { + + return nil, errors.New("orphan sweep failed") +} + +func (s *recordingSelector) ReleaseCoins(ctx context.Context, + ops ...wire.OutPoint) error { + + s.releaseHits++ + s.releaseErr = ctx.Err() + s.deadline, s.hasDeadline = ctx.Deadline() + s.releaseValue = ctx.Value(releaseValueKey{}) + s.released = append([]wire.OutPoint(nil), ops...) + + return ctx.Err() +} + +// releaseValueKey is the context key used to check that a canceled caller +// context still contributes its values to the release context. +type releaseValueKey struct{} + +// TestFundErrorPathReleasesOnCanceledContext makes sure FundPacket and +// FundBurn still release selected coins when the caller context is already +// canceled. The release context keeps the caller's values and is bounded. +func TestFundErrorPathReleasesOnCanceledContext(t *testing.T) { + t.Parallel() + + canceled, cancel := context.WithCancel(context.Background()) + cancel() + ctx := context.WithValue(canceled, releaseValueKey{}, "lease") + + op := wire.OutPoint{Index: 4} + run := func(t *testing.T, + call func(*AssetWallet, context.Context) error) { + + t.Helper() + + sel := &recordingSelector{ + selected: []*AnchoredCommitment{{ + AnchorPoint: op, + }}, + } + wallet := NewAssetWallet(&WalletConfig{ + CoinSelector: sel, + ChainParams: testParams, + }) + + start := time.Now() + err := call(wallet, ctx) + require.ErrorContains(t, err, "orphan sweep failed") + + // One release, on a live bounded context. The old defer passed + // the canceled caller context through and the release failed. + require.Equal(t, 1, sel.releaseHits) + require.NoError(t, sel.releaseErr) + require.Equal(t, []wire.OutPoint{op}, sel.released) + require.Equal(t, "lease", sel.releaseValue) + require.True(t, sel.hasDeadline) + require.LessOrEqual( + t, sel.deadline.Sub(start), + coinReleaseTimeout+time.Second, + ) + } + + t.Run("fund packet", func(t *testing.T) { + run(t, func(w *AssetWallet, ctx context.Context) error { + _, err := w.FundPacket( + ctx, &tapsend.FundingDescriptor{}, + &tappsbt.VPacket{ChainParams: testParams}, + ) + return err + }) + }) + + t.Run("fund burn", func(t *testing.T) { + run(t, func(w *AssetWallet, ctx context.Context) error { + _, err := w.FundBurn( + ctx, &tapsend.FundingDescriptor{}, + ) + return err + }) + }) +} diff --git a/tapfreighter/wallet.go b/tapfreighter/wallet.go index c894ae85cd..e0a7c6d013 100644 --- a/tapfreighter/wallet.go +++ b/tapfreighter/wallet.go @@ -41,8 +41,39 @@ const ( // and avoids the same UTXO being used in another transaction if the // confirmation of the first transaction takes a long time. defaultBroadcastCoinLeaseDuration = 365 * 24 * time.Hour + + // coinReleaseTimeout is the upper bound for the compensating release of + // leased coins on an error path. The release must not depend on the + // (likely canceled) caller context, but must still be bounded. + coinReleaseTimeout = 30 * time.Second ) +// coinReleaser is the subset of the CoinSelector needed to release coins. +type coinReleaser interface { + // ReleaseCoins releases/unlocks coins that were previously leased and + // makes them available for coin selection again. + ReleaseCoins(ctx context.Context, utxoOutpoints ...wire.OutPoint) error +} + +// releaseCoinsDetached releases the given leased coins on a context that keeps +// the values of the parent but not its cancellation, bounded by +// coinReleaseTimeout. It is meant for deferred cleanup paths that commonly run +// because the caller's context was canceled, in which case releasing on that +// context would fail immediately and leak the leases (taproot-assets#2206). +func releaseCoinsDetached(parent context.Context, releaser coinReleaser, + outpoints []wire.OutPoint) { + + ctx, cancel := context.WithTimeout( + context.WithoutCancel(parent), coinReleaseTimeout, + ) + defer cancel() + + err := releaser.ReleaseCoins(ctx, outpoints...) + if err != nil { + log.Errorf("Unable to release coins: %v", err) + } +} + var ( // defaultWalletLeaseIdentifier is the binary representation of the // SHA256 hash of the string "tapd-internal-lock-id" and is used for @@ -690,12 +721,9 @@ func (f *AssetWallet) FundPacket(ctx context.Context, ) outpoints = append(outpoints, zeroValueOutpoints...) - err := f.cfg.CoinSelector.ReleaseCoins( - ctx, outpoints..., + releaseCoinsDetached( + ctx, f.cfg.CoinSelector, outpoints, ) - if err != nil { - log.Errorf("Unable to release coins: %v", err) - } } }() @@ -771,12 +799,9 @@ func (f *AssetWallet) FundBurn(ctx context.Context, ) outpoints = append(outpoints, zeroValueOutpoints...) - err := f.cfg.CoinSelector.ReleaseCoins( - ctx, outpoints..., + releaseCoinsDetached( + ctx, f.cfg.CoinSelector, outpoints, ) - if err != nil { - log.Errorf("Unable to release coins: %v", err) - } } }() diff --git a/tapgarden/caretaker.go b/tapgarden/caretaker.go index 512af2245c..c6ee8389ed 100644 --- a/tapgarden/caretaker.go +++ b/tapgarden/caretaker.go @@ -141,10 +141,16 @@ type BatchCaretaker struct { // // TODO(roasbeef): rename to Cultivator? func NewBatchCaretaker(cfg *BatchCaretakerConfig) *BatchCaretaker { + var anchorIdx uint32 + if cfg.Batch != nil && cfg.Batch.GenesisPacket != nil { + anchorIdx = cfg.Batch.GenesisPacket.AssetAnchorOutIdx + } + return &BatchCaretaker{ batchKey: asset.ToSerialized(cfg.Batch.BatchKey.PubKey), cfg: cfg, confEvent: make(chan *chainntnfs.TxConfirmation, 1), + anchorOutputIndex: anchorIdx, ContextGuard: &fn.ContextGuard{ DefaultTimeout: DefaultTimeout, Quit: make(chan struct{}), @@ -649,6 +655,11 @@ func (b *BatchCaretaker) stateStep(currentState BatchState) (BatchState, error) genesisTxPkt.UnsignedTx. TxOut[b.anchorOutputIndex].PkScript = genesisScript + if isCustomAnchorPsbt(genesisTxPkt) { + pOut := &genesisTxPkt.Outputs[b.anchorOutputIndex] + pOut.TaprootInternalKey = nil + pOut.TaprootBip32Derivation = nil + } log.Infof("BatchCaretaker(%x): committing sprouts to disk", b.batchKey[:]) @@ -704,17 +715,30 @@ func (b *BatchCaretaker) stateStep(currentState BatchState) (BatchState, error) log.Infof("BatchCaretaker(%x): finalizing GenesisPacket", b.batchKey[:]) - // First, we'll have the wallet sign the PSBT is created, which - // was then modified. - // - // TODO(roasbeef): only execute if finalized? or missing sig ctx, cancel := b.WithCtxQuit() defer cancel() - signedPkt, err := b.cfg.Wallet.SignAndFinalizePsbt( - ctx, b.cfg.Batch.GenesisPacket.Pkt, - ) - if err != nil { - return 0, fmt.Errorf("unable to sign psbt: %w", err) + signedPkt := b.cfg.Batch.GenesisPacket.Pkt + + // Caller-authored anchor batches pause here until + // FinalizeBatch supplies a fully signed PSBT. Never ask the + // wallet to sign external inputs on restart. + if isCustomAnchorPsbt(signedPkt) { + if _, extractErr := psbt.Extract(signedPkt); extractErr != nil { + return BatchStateCommitted, nil + } + } else { + // First, we'll have the wallet sign the PSBT that was + // created, which was then modified. + _, extractErr := psbt.Extract(signedPkt) + if extractErr != nil { + signedPkt, extractErr = b.cfg.Wallet.SignAndFinalizePsbt( + ctx, signedPkt, + ) + if extractErr != nil { + return 0, fmt.Errorf("unable to sign psbt: %w", + extractErr) + } + } } // Final TX sanity check. @@ -863,9 +887,14 @@ func (b *BatchCaretaker) stateStep(currentState BatchState) (BatchState, error) // TODO(roasbeef): eventually want to be able to RBF the bump heightHint := b.cfg.Batch.HeightHint txHash := signedTx.TxHash() + anchorIdx := b.anchorOutputIndex + if int(anchorIdx) >= len(signedTx.TxOut) { + return 0, fmt.Errorf("asset anchor output index %d out "+ + "of range", anchorIdx) + } confCtx, confCancel := b.WithCtxQuitNoTimeout() confNtfn, errChan, err := b.cfg.ChainBridge.RegisterConfirmationsNtfn( - confCtx, &txHash, signedTx.TxOut[0].PkScript, 1, + confCtx, &txHash, signedTx.TxOut[anchorIdx].PkScript, 1, heightHint, true, nil, ) if err != nil { diff --git a/tapgarden/custom_anchor.go b/tapgarden/custom_anchor.go new file mode 100644 index 0000000000..170696d004 --- /dev/null +++ b/tapgarden/custom_anchor.go @@ -0,0 +1,816 @@ +package tapgarden + +import ( + "bytes" + "context" + "crypto/sha256" + "errors" + "fmt" + "io" + "reflect" + + "github.com/btcsuite/btcd/blockchain" + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/btcec/v2/schnorr" + "github.com/btcsuite/btcd/btcutil" + "github.com/btcsuite/btcd/btcutil/psbt" + "github.com/btcsuite/btcd/mempool" + "github.com/btcsuite/btcd/txscript" + "github.com/btcsuite/btcd/wire" + "github.com/lightninglabs/taproot-assets/address" + "github.com/lightninglabs/taproot-assets/asset" + "github.com/lightninglabs/taproot-assets/fn" + "github.com/lightninglabs/taproot-assets/tappsbt" + "github.com/lightninglabs/taproot-assets/tapsend" + "github.com/lightningnetwork/lnd/keychain" + "github.com/lightningnetwork/lnd/lntypes" + "slices" +) + +var customAnchorPsbtMarker = []byte{ + 0xfc, 0x04, 't', 'a', 'p', 'd', 0x01, +} + +// CustomAnchorLeaseID identifies wallet leases held for one mint batch. +type CustomAnchorLeaseID [32]byte + +// CustomAnchorLeaser leases individual wallet inputs for custom-anchor minting. +type CustomAnchorLeaser interface { + LeaseInput(ctx context.Context, leaseID CustomAnchorLeaseID, + op wire.OutPoint) (bool, error) + + ReleaseInput(ctx context.Context, leaseID CustomAnchorLeaseID, + op wire.OutPoint) error +} + +// CustomAnchorBatchLeaser leases many wallet inputs in one snapshot. +type CustomAnchorBatchLeaser interface { + LeaseInputs(ctx context.Context, leaseID CustomAnchorLeaseID, + ops []wire.OutPoint) ([]wire.OutPoint, error) + + ReleaseInputs(ctx context.Context, leaseID CustomAnchorLeaseID, + ops []wire.OutPoint) error +} + +func markCustomAnchorPsbt(packet *psbt.Packet) { + if isCustomAnchorPsbt(packet) { + return + } + + packet.Unknowns = append(packet.Unknowns, &psbt.Unknown{ + Key: fn.CopySlice(customAnchorPsbtMarker), + Value: []byte{1}, + }) +} + +func isCustomAnchorPsbt(packet *psbt.Packet) bool { + if packet == nil { + return false + } + + for _, unknown := range packet.Unknowns { + if bytes.Equal(unknown.Key, customAnchorPsbtMarker) { + return true + } + } + + return false +} + +func customAnchorLeaseID(batchKey *btcec.PublicKey) CustomAnchorLeaseID { + preimage := append( + []byte("tapd-custom-anchor-psbt-lease-v1:"), + batchKey.SerializeCompressed()..., + ) + + return CustomAnchorLeaseID(sha256.Sum256(preimage)) +} + +func customAnchorKeyDesc(chainParams address.ChainParams, packet *psbt.Packet, + assetAnchorOutIdx uint32) (keychain.KeyDescriptor, error) { + + var zero keychain.KeyDescriptor + if packet == nil || uint64(assetAnchorOutIdx) >= + uint64(len(packet.Outputs)) { + + return zero, fmt.Errorf("custom anchor output metadata is missing") + } + + pOut := packet.Outputs[assetAnchorOutIdx] + if len(pOut.Bip32Derivation) != 1 || + len(pOut.TaprootBip32Derivation) != 1 { + + return zero, fmt.Errorf("custom asset anchor output must specify " + + "exactly one BIP32 and Taproot BIP32 derivation") + } + + bip32Derivation := pOut.Bip32Derivation[0] + taprootDerivation := pOut.TaprootBip32Derivation[0] + desc, err := tappsbt.KeyDescFromBip32Derivation(bip32Derivation) + if err != nil { + return zero, fmt.Errorf("invalid custom anchor key derivation: %w", + err) + } + + expectedBip32, expectedTaproot := tappsbt.Bip32DerivationFromKeyDesc( + desc, chainParams.HDCoinType, + ) + if !bytes.Equal(expectedBip32.PubKey, bip32Derivation.PubKey) || + !slices.Equal(expectedBip32.Bip32Path, bip32Derivation.Bip32Path) || + !bytes.Equal( + expectedTaproot.XOnlyPubKey, + taprootDerivation.XOnlyPubKey, + ) || !slices.Equal( + expectedTaproot.Bip32Path, taprootDerivation.Bip32Path, + ) || len(taprootDerivation.LeafHashes) != 0 || + !bytes.Equal( + pOut.TaprootInternalKey, + taprootDerivation.XOnlyPubKey, + ) { + + return zero, fmt.Errorf("custom anchor key derivation doesn't " + + "match its internal key or network path") + } + + return desc, nil +} + +// customGenesisPsbt validates and packages a caller-authored mint anchor +// PSBT. Unlike fundGenesisPsbt, this path doesn't ask the backing wallet to +// add or reorder anything in the packet. +func customGenesisPsbt(chainParams address.ChainParams, + pendingBatch *MintingBatch, packet *psbt.Packet, + assetAnchorOutIdx uint32, + changeOutputIndex int32, + preCommitOutputIndex fn.Option[uint32]) (FundedMintAnchorPsbt, error) { + + var zero FundedMintAnchorPsbt + + if packet == nil || packet.UnsignedTx == nil { + return zero, fmt.Errorf("custom anchor PSBT is missing its " + + "unsigned transaction") + } + if len(packet.UnsignedTx.TxIn) == 0 { + return zero, fmt.Errorf("custom anchor PSBT must have at least " + + "one input") + } + if len(packet.Inputs) != len(packet.UnsignedTx.TxIn) { + return zero, fmt.Errorf("custom anchor PSBT input maps don't " + + "match unsigned transaction inputs") + } + if len(packet.Outputs) != len(packet.UnsignedTx.TxOut) { + return zero, fmt.Errorf("custom anchor PSBT output maps don't " + + "match unsigned transaction outputs") + } + + var buf bytes.Buffer + if err := packet.Serialize(&buf); err != nil { + return zero, fmt.Errorf("unable to copy custom anchor "+ + "PSBT: %w", err) + } + copied, err := psbt.NewFromRawBytes(&buf, false) + if err != nil { + return zero, fmt.Errorf("unable to copy custom anchor "+ + "PSBT: %w", err) + } + packet = copied + if int(assetAnchorOutIdx) >= len(packet.UnsignedTx.TxOut) { + return zero, fmt.Errorf("asset anchor output index %d out of "+ + "range", assetAnchorOutIdx) + } + if changeOutputIndex < -1 || + changeOutputIndex >= int32(len(packet.UnsignedTx.TxOut)) { + + return zero, fmt.Errorf("change output index %d out of range", + changeOutputIndex) + } + if changeOutputIndex == int32(assetAnchorOutIdx) { + return zero, fmt.Errorf("asset anchor and change output indexes " + + "must be distinct") + } + if err := packet.SanityCheck(); err != nil { + return zero, fmt.Errorf("invalid custom anchor PSBT: %w", err) + } + fee, err := packet.GetTxFee() + if err != nil { + return zero, fmt.Errorf("custom anchor PSBT has incomplete or "+ + "invalid input values: %w", err) + } + if fee < 0 { + return zero, fmt.Errorf("custom anchor PSBT outputs exceed " + + "known input value") + } + anchorOutput := packet.UnsignedTx.TxOut[assetAnchorOutIdx] + eventualAnchorOutput := tapsend.CreateDummyOutput() + eventualAnchorOutput.Value = anchorOutput.Value + if eventualAnchorOutput.Value < + mempool.GetDustThreshold(eventualAnchorOutput) { + + return zero, fmt.Errorf("custom asset anchor output is dust") + } + + for idx := range packet.Inputs { + pIn := &packet.Inputs[idx] + if len(pIn.PartialSigs) != 0 || len(pIn.FinalScriptSig) != 0 || + len(pIn.FinalScriptWitness) != 0 || + len(pIn.TaprootKeySpendSig) != 0 || + len(pIn.TaprootScriptSpendSig) != 0 { + + return zero, fmt.Errorf("custom anchor PSBT must be " + + "unsigned before batch preparation") + } + } + + pOut := packet.Outputs[assetAnchorOutIdx] + if len(pOut.TaprootInternalKey) != schnorr.PubKeyBytesLen { + return zero, fmt.Errorf("custom asset anchor output must specify " + + "a taproot internal key") + } + if _, err := schnorr.ParsePubKey(pOut.TaprootInternalKey); err != nil { + return zero, fmt.Errorf("invalid custom asset anchor internal "+ + "key: %w", err) + } + + funded := tapsend.FundedPsbt{ + Pkt: packet, + ChangeOutputIndex: changeOutputIndex, + } + markCustomAnchorPsbt(packet) + + var preCommitOut fn.Option[PreCommitmentOutput] + var preCommitIdx fn.Option[uint32] + if pendingBatch != nil && pendingBatch.SupplyCommitments { + idx, err := preCommitOutputIndex.UnwrapOrErr(fmt.Errorf( + "custom supply commitment batch requires a pre-commitment " + + "output index", + )) + if err != nil { + return zero, err + } + if int(idx) >= len(packet.UnsignedTx.TxOut) || + idx == assetAnchorOutIdx || idx == uint32(changeOutputIndex) { + + return zero, fmt.Errorf("invalid pre-commitment output "+ + "index %d", idx) + } + + delegationKey, err := fetchDelegationKey(pendingBatch) + if err != nil { + return zero, err + } + dKey, err := delegationKey.UnwrapOrErr(fmt.Errorf( + "missing supply commitment delegation key", + )) + if err != nil { + return zero, err + } + expectedOutput, err := PreCommitTxOut(*dKey.PubKey) + if err != nil { + return zero, err + } + actualOutput := packet.UnsignedTx.TxOut[idx] + if actualOutput.Value != expectedOutput.Value || + !bytes.Equal(actualOutput.PkScript, expectedOutput.PkScript) { + + return zero, fmt.Errorf("pre-commitment output %d doesn't "+ + "match the batch delegation key", idx) + } + + bip32Derivation, trBip32Derivation := + tappsbt.Bip32DerivationFromKeyDesc( + dKey, chainParams.HDCoinType, + ) + pCommitOut := &packet.Outputs[idx] + pCommitOut.Bip32Derivation = []*psbt.Bip32Derivation{bip32Derivation} + pCommitOut.TaprootBip32Derivation = []*psbt.TaprootBip32Derivation{ + trBip32Derivation, + } + pCommitOut.TaprootInternalKey = trBip32Derivation.XOnlyPubKey + + groupKey, err := fetchPreCommitGroupKey(pendingBatch) + if err != nil { + return zero, err + } + preCommitOut = fn.Some(NewPreCommitmentOutput( + idx, dKey, groupKey, + )) + preCommitIdx = fn.Some(idx) + } else if preCommitOutputIndex.IsSome() { + return zero, fmt.Errorf("pre-commitment output index specified " + + "for batch without supply commitments") + } + changeIdx := uint32(0) + if changeOutputIndex >= 0 { + changeIdx = uint32(changeOutputIndex) + } + + indexes := AnchorTxOutputIndexes{ + AssetAnchorOutIdx: assetAnchorOutIdx, + ChangeOutIdx: changeIdx, + PreCommitOutIdx: preCommitIdx, + } + + return NewFundedMintAnchorPsbt( + funded, indexes, preCommitOut, + ) +} + +func acquireCustomAnchorLeases(ctx context.Context, wallet WalletAnchor, + leaseID CustomAnchorLeaseID, packet *psbt.Packet) ([]wire.OutPoint, + error) { + + if packet == nil || packet.UnsignedTx == nil { + return nil, fmt.Errorf("custom anchor PSBT is missing a transaction") + } + ops := make([]wire.OutPoint, 0, len(packet.UnsignedTx.TxIn)) + for _, txIn := range packet.UnsignedTx.TxIn { + ops = append(ops, txIn.PreviousOutPoint) + } + + return leaseCustomAnchorOutpoints(ctx, wallet, leaseID, ops) +} + +func leaseCustomAnchorOutpoints(ctx context.Context, wallet WalletAnchor, + leaseID CustomAnchorLeaseID, ops []wire.OutPoint) ([]wire.OutPoint, + error) { + + batchLeaser, ok := wallet.(CustomAnchorBatchLeaser) + if !ok { + return nil, fmt.Errorf("wallet does not support custom anchor leases") + } + + seen := make(map[wire.OutPoint]struct{}, len(ops)) + for _, op := range ops { + if _, ok := seen[op]; ok { + return nil, fmt.Errorf("custom anchor PSBT repeats input %v", op) + } + seen[op] = struct{}{} + } + + locked, err := batchLeaser.LeaseInputs(ctx, leaseID, ops) + if err != nil { + releaseErr := releaseCustomAnchorOutpoints(ctx, wallet, leaseID, locked) + return nil, errors.Join(err, releaseErr) + } + + lockedSet := make(map[wire.OutPoint]struct{}, len(locked)) + for _, op := range locked { + if _, requested := seen[op]; !requested { + releaseErr := releaseCustomAnchorOutpoints( + ctx, wallet, leaseID, locked, + ) + return nil, errors.Join(fmt.Errorf( + "wallet returned unrequested custom anchor lease %v", op, + ), releaseErr) + } + if _, duplicate := lockedSet[op]; duplicate { + releaseErr := releaseCustomAnchorOutpoints( + ctx, wallet, leaseID, locked, + ) + return nil, errors.Join(fmt.Errorf( + "wallet returned duplicate custom anchor lease %v", op, + ), releaseErr) + } + lockedSet[op] = struct{}{} + } + + return locked, nil +} + +// renewCustomAnchorLeases extends wallet leases while a prepared batch waits +// for an external signature. +func renewCustomAnchorLeases(ctx context.Context, wallet WalletAnchor, + leaseID CustomAnchorLeaseID, funded *FundedMintAnchorPsbt) error { + + if funded == nil || funded.Pkt == nil { + return nil + } + + _, err := acquireCustomAnchorLeases(ctx, wallet, leaseID, funded.Pkt) + return err +} + +func releaseCustomAnchorOutpoints(ctx context.Context, wallet WalletAnchor, + leaseID CustomAnchorLeaseID, ops []wire.OutPoint) error { + + if len(ops) == 0 { + return nil + } + + batchLeaser, ok := wallet.(CustomAnchorBatchLeaser) + if !ok { + return fmt.Errorf("wallet does not support custom anchor leases") + } + + return batchLeaser.ReleaseInputs(ctx, leaseID, ops) +} + +func releaseCustomAnchorLeases(ctx context.Context, wallet WalletAnchor, + leaseID CustomAnchorLeaseID, funded *FundedMintAnchorPsbt) error { + + if funded == nil { + return nil + } + + return releaseCustomAnchorOutpoints(ctx, wallet, leaseID, funded.LockedUTXOs) +} + +func releaseBatchFundingInputs(ctx context.Context, wallet WalletAnchor, + batch *MintingBatch) { + + if batch == nil || batch.GenesisPacket == nil { + return + } + + var err error + if isCustomAnchorPsbt(batch.GenesisPacket.Pkt) { + err = releaseCustomAnchorLeases( + ctx, wallet, customAnchorLeaseID(batch.BatchKey.PubKey), + batch.GenesisPacket, + ) + } else { + err = releaseFundingInputs(ctx, wallet, &batch.GenesisPacket.FundedPsbt) + } + if err != nil { + batchKeySerial := asset.ToSerialized(batch.BatchKey.PubKey) + log.Warnf("Unable to release funding inputs of cancelled "+ + "batch (%x): %v", batchKeySerial[:], err) + } +} + +func releaseFundingInputs(ctx context.Context, wallet WalletAnchor, + funded *tapsend.FundedPsbt) error { + + if funded == nil { + return nil + } + + outpoints := funded.LockedUTXOs + if len(outpoints) == 0 && funded.Pkt != nil && + funded.Pkt.UnsignedTx != nil { + + txIns := funded.Pkt.UnsignedTx.TxIn + outpoints = make([]wire.OutPoint, 0, len(txIns)) + for _, txIn := range txIns { + outpoints = append(outpoints, txIn.PreviousOutPoint) + } + } + + var unlockErrs []error + for _, outpoint := range outpoints { + if err := wallet.UnlockInput(ctx, outpoint); err != nil { + unlockErrs = append(unlockErrs, fmt.Errorf( + "unable to unlock input %v: %w", outpoint, err, + )) + } + } + + return errors.Join(unlockErrs...) +} + +func batchFundingError(ctx context.Context, wallet WalletAnchor, + batchKey *btcec.PublicKey, funded *FundedMintAnchorPsbt, + cause error) error { + + if funded == nil { + return cause + } + if isCustomAnchorPsbt(funded.Pkt) { + releaseErr := releaseCustomAnchorLeases( + ctx, wallet, customAnchorLeaseID(batchKey), funded, + ) + return errors.Join(cause, releaseErr) + } + + cleanupCtx, cancel := context.WithTimeout( + context.WithoutCancel(ctx), DefaultTimeout, + ) + defer cancel() + + releaseErr := releaseFundingInputs(cleanupCtx, wallet, &funded.FundedPsbt) + if releaseErr == nil { + return cause + } + + return errors.Join(cause, releaseErr) +} + +// prepareBatch commits the asset tree into a caller-authored anchor PSBT and +// then pauses at the committed state so the packet can be signed externally. +func (c *ChainPlanter) prepareBatch(ctx context.Context, + batch *MintingBatch) (*MintingBatch, error) { + + if !batch.IsFunded() || !isCustomAnchorPsbt(batch.GenesisPacket.Pkt) { + return nil, fmt.Errorf("batch does not use a custom anchor PSBT") + } + if batch.State() != BatchStatePending && + batch.State() != BatchStateFrozen { + + return nil, fmt.Errorf("batch is not ready for preparation: %v", + batch.State()) + } + + sealedBatch, err := c.sealBatch(ctx, SealParams{}, batch) + if err != nil && !errors.Is(err, ErrBatchAlreadySealed) { + return nil, err + } + if sealedBatch != nil { + batch = sealedBatch + } + + if batch.State() == BatchStatePending { + if err := freezeMintingBatch(ctx, c.cfg.Log, batch); err != nil { + return nil, err + } + batch.UpdateState(BatchStateFrozen) + } + + caretaker := c.newCaretakerForBatch(batch, nil) + nextState, err := caretaker.stateStep(BatchStateFrozen) + delete(c.caretakers, asset.ToSerialized(batch.BatchKey.PubKey)) + if err != nil { + return nil, err + } + if nextState != BatchStateCommitted { + return nil, fmt.Errorf("unexpected prepared batch state: %v", + nextState) + } + + err = c.cfg.Log.UpdateBatchState( + ctx, batch.BatchKey.PubKey, BatchStateCommitted, + ) + if err != nil { + return nil, fmt.Errorf("unable to persist prepared batch: %w", + err) + } + + batch.UpdateState(BatchStateCommitted) + + err = renewCustomAnchorLeases( + ctx, c.cfg.Wallet, customAnchorLeaseID(batch.BatchKey.PubKey), + batch.GenesisPacket, + ) + if err != nil { + return nil, fmt.Errorf("unable to renew custom anchor leases: %w", + err) + } + + return batch, nil +} + +func mergeSignedCustomPsbt(stored, + signed *psbt.Packet) (*psbt.Packet, error) { + + if stored == nil || signed == nil { + return nil, fmt.Errorf("signed custom anchor PSBT is missing") + } + if err := signed.SanityCheck(); err != nil { + return nil, fmt.Errorf("invalid signed custom anchor PSBT: %w", err) + } + normalizePacket := func(pkt *psbt.Packet) (*psbt.Packet, error) { + var buf bytes.Buffer + if err := pkt.Serialize(&buf); err != nil { + return nil, err + } + return psbt.NewFromRawBytes(&buf, false) + } + storedNorm, err := normalizePacket(stored) + if err != nil { + return nil, err + } + signedNorm, err := normalizePacket(signed) + if err != nil { + return nil, err + } + if !reflect.DeepEqual(storedNorm.UnsignedTx, signedNorm.UnsignedTx) || + !reflect.DeepEqual(storedNorm.Outputs, signedNorm.Outputs) || + !reflect.DeepEqual(storedNorm.XPubs, signedNorm.XPubs) || + !reflect.DeepEqual(storedNorm.Unknowns, signedNorm.Unknowns) || + len(stored.Inputs) != len(signed.Inputs) { + + return nil, fmt.Errorf("signed custom anchor PSBT changes prepared " + + "transaction or metadata") + } + + hasSignature := false + for idx := range stored.Inputs { + storedCmp := stored.Inputs[idx] + signedCmp := signed.Inputs[idx] + isFinal := signedCmp.FinalScriptSig != nil || + signedCmp.FinalScriptWitness != nil + if isFinal { + if signedCmp.WitnessUtxo != nil && + !reflect.DeepEqual( + storedCmp.WitnessUtxo, signedCmp.WitnessUtxo, + ) { + + return nil, fmt.Errorf("signed custom anchor PSBT " + + "changes input UTXO") + } + if signedCmp.NonWitnessUtxo != nil && + !reflect.DeepEqual( + storedCmp.NonWitnessUtxo, + signedCmp.NonWitnessUtxo, + ) { + + return nil, fmt.Errorf("signed custom anchor PSBT " + + "changes input UTXO") + } + if signedCmp.WitnessUtxo == nil && + signedCmp.NonWitnessUtxo == nil { + + return nil, fmt.Errorf("finalized custom anchor PSBT " + + "drops input UTXO") + } + + hasSignature = true + continue + } + + storedCmp.PartialSigs = nil + storedCmp.FinalScriptSig = nil + storedCmp.FinalScriptWitness = nil + storedCmp.TaprootKeySpendSig = nil + storedCmp.TaprootScriptSpendSig = nil + signedCmp.PartialSigs = nil + signedCmp.FinalScriptSig = nil + signedCmp.FinalScriptWitness = nil + signedCmp.TaprootKeySpendSig = nil + signedCmp.TaprootScriptSpendSig = nil + + if !reflect.DeepEqual(storedCmp, signedCmp) { + return nil, fmt.Errorf("signed custom anchor PSBT changes input "+ + "%d metadata", idx) + } + + src := &signed.Inputs[idx] + if len(src.PartialSigs) != 0 || src.FinalScriptSig != nil || + src.FinalScriptWitness != nil || + len(src.TaprootKeySpendSig) != 0 || + len(src.TaprootScriptSpendSig) != 0 { + + hasSignature = true + } + } + + if !hasSignature { + return nil, fmt.Errorf("signed custom anchor PSBT has no signatures") + } + + var buf bytes.Buffer + if err := stored.Serialize(&buf); err != nil { + return nil, err + } + merged, err := psbt.NewFromRawBytes(&buf, false) + if err != nil { + return nil, err + } + for idx := range merged.Inputs { + src := &signed.Inputs[idx] + dst := &merged.Inputs[idx] + dst.PartialSigs = src.PartialSigs + dst.FinalScriptSig = src.FinalScriptSig + dst.FinalScriptWitness = src.FinalScriptWitness + dst.TaprootKeySpendSig = src.TaprootKeySpendSig + dst.TaprootScriptSpendSig = src.TaprootScriptSpendSig + } + + return merged, nil +} + +func validateAnchorInputSigHashTypes(packet *psbt.Packet) error { + for idx, pIn := range packet.Inputs { + if pIn.FinalScriptWitness == nil { + continue + } + + if len(pIn.FinalScriptWitness) == 0 { + continue + } + + reader := bytes.NewReader(pIn.FinalScriptWitness) + itemCount, err := wire.ReadVarInt(reader, 0) + if err != nil || itemCount == 0 { + continue + } + + itemSize, err := wire.ReadVarInt(reader, 0) + if err != nil { + return fmt.Errorf("unable to parse witness for input %d: %w", + idx, err) + } + if itemSize > uint64(reader.Len()) { + return fmt.Errorf("witness item exceeds serialized data") + } + + sig := make([]byte, itemSize) + if _, err := io.ReadFull(reader, sig); err != nil { + return fmt.Errorf("unable to read witness signature: %w", + err) + } + if len(sig) == 0 { + continue + } + + hashType := txscript.SigHashType(sig[len(sig)-1]) + switch hashType { + case txscript.SigHashAll, txscript.SigHashDefault: + continue + + default: + return fmt.Errorf("input %d uses disallowed sighash %v", + idx, hashType) + } + } + + return nil +} + +func validateCustomAnchorFeeRate(ctx context.Context, wallet WalletAnchor, + packet *psbt.Packet) error { + + fee, err := packet.GetTxFee() + if err != nil { + return fmt.Errorf("unable to determine custom anchor fee: %w", err) + } + + signedTx, err := psbt.Extract(packet) + if err != nil { + return fmt.Errorf("unable to extract custom anchor transaction: %w", + err) + } + + weight := lntypes.WeightUnit( + blockchain.GetTransactionWeight(btcutil.NewTx(signedTx)), + ) + + minRelayFee, err := wallet.MinRelayFee(ctx) + if err != nil { + return fmt.Errorf("unable to obtain minimum relay fee: %w", err) + } + + minFee := minRelayFee.FeeForWeight(weight) + if btcutil.Amount(fee) < minFee { + return fmt.Errorf("fee %d below minimum relay fee %d", fee, + minFee) + } + + return nil +} + +func validateFinalizedAnchorPsbt(packet *psbt.Packet) error { + tx, err := psbt.Extract(packet) + if err != nil { + return err + } + + if err := validateAnchorInputSigHashTypes(packet); err != nil { + return err + } + + prevOuts := txscript.NewMultiPrevOutFetcher(nil) + for idx := range packet.Inputs { + pIn := &packet.Inputs[idx] + var prevOut *wire.TxOut + switch { + case pIn.WitnessUtxo != nil: + prevOut = pIn.WitnessUtxo + + case pIn.NonWitnessUtxo != nil: + outpoint := tx.TxIn[idx].PreviousOutPoint + if int(outpoint.Index) >= len(pIn.NonWitnessUtxo.TxOut) || + pIn.NonWitnessUtxo.TxHash() != outpoint.Hash { + + return fmt.Errorf("invalid non-witness UTXO for input %d", + idx) + } + prevOut = pIn.NonWitnessUtxo.TxOut[outpoint.Index] + + default: + return fmt.Errorf("missing UTXO for input %d", idx) + } + + prevOuts.AddPrevOut(tx.TxIn[idx].PreviousOutPoint, prevOut) + } + + sigHashes := txscript.NewTxSigHashes(tx, prevOuts) + for idx := range tx.TxIn { + prevOut := prevOuts.FetchPrevOutput( + tx.TxIn[idx].PreviousOutPoint, + ) + vm, err := txscript.NewEngine( + prevOut.PkScript, tx, idx, txscript.StandardVerifyFlags, + nil, sigHashes, prevOut.Value, prevOuts, + ) + if err != nil { + return fmt.Errorf("unable to validate input %d: %w", idx, + err) + } + if err := vm.Execute(); err != nil { + return fmt.Errorf("invalid witness for input %d: %w", idx, + err) + } + } + + return nil +} diff --git a/tapgarden/custom_anchor_caretaker_test.go b/tapgarden/custom_anchor_caretaker_test.go new file mode 100644 index 0000000000..e5daaf208e --- /dev/null +++ b/tapgarden/custom_anchor_caretaker_test.go @@ -0,0 +1,159 @@ +package tapgarden + +import ( + "context" + "testing" + "time" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/chaincfg" + "github.com/btcsuite/btcd/btcutil" + "github.com/btcsuite/btcd/btcutil/psbt" + "github.com/btcsuite/btcd/txscript" + "github.com/btcsuite/btcd/wire" + "github.com/lightninglabs/taproot-assets/address" + "github.com/lightningnetwork/lnd/keychain" + "github.com/stretchr/testify/require" +) + +func randBatchKey(t *testing.T) keychain.KeyDescriptor { + t.Helper() + + priv, err := btcec.NewPrivateKey() + require.NoError(t, err) + + return keychain.KeyDescriptor{PubKey: priv.PubKey()} +} + +// TestCustomAnchorCommittedStepSkipsWalletSign proves an unsigned custom-anchor +// PSBT at COMMITTED does not invoke SignAndFinalizePsbt (restart-safe pause). +func TestCustomAnchorCommittedStepSkipsWalletSign(t *testing.T) { + pkt := testCustomAnchorPacket(t) + funded, err := customGenesisPsbt( + address.TestNet3Tap, nil, pkt, 0, -1, noneUint32(), + ) + require.NoError(t, err) + + wallet := NewMockWalletAnchor() + chain := NewMockChainBridge() + + batch := &MintingBatch{ + BatchKey: randBatchKey(t), + Seedlings: map[string]*Seedling{}, + AssetMetas: make(AssetMetas), + GenesisPacket: &funded, + } + batch.UpdateState(BatchStateCommitted) + + caretaker := NewBatchCaretaker(&BatchCaretakerConfig{ + Batch: batch, + GardenKit: GardenKit{ + Wallet: wallet, + ChainBridge: chain, + }, + }) + + next, err := caretaker.stateStep(BatchStateCommitted) + require.NoError(t, err) + require.Equal(t, BatchStateCommitted, next) + + select { + case <-wallet.SignPsbtSignal: + t.Fatal("wallet must not sign a prepared custom-anchor PSBT") + case <-time.After(50 * time.Millisecond): + } +} + +// TestCustomAnchorBroadcastWatchesAssetAnchorOutput proves confirmation +// registration uses the asset anchor output script, not TxOut[0]. +func TestCustomAnchorBroadcastWatchesAssetAnchorOutput(t *testing.T) { + const anchorIdx = uint32(1) + + pkt := testCustomAnchorPacket(t) + anchorScript := pkt.UnsignedTx.TxOut[0].PkScript + changeAddr, err := btcutil.NewAddressScriptHash( + []byte("change"), &chaincfg.RegressionNetParams, + ) + require.NoError(t, err) + changeScript, err := txscript.PayToAddrScript(changeAddr) + require.NoError(t, err) + + pkt.UnsignedTx.TxOut = []*wire.TxOut{ + {Value: 5000, PkScript: changeScript}, + {Value: pkt.UnsignedTx.TxOut[0].Value, PkScript: anchorScript}, + } + pkt.Outputs = []psbt.POutput{{}, {}} + markCustomAnchorPsbt(pkt) + pkt.Inputs[0].FinalScriptWitness = []byte{1, 0} + + funded := FundedMintAnchorPsbt{ + FundedPsbt: fundedPsbt(pkt), + AssetAnchorOutIdx: anchorIdx, + } + + wallet := NewMockWalletAnchor() + chain := NewMockChainBridge() + + batch := &MintingBatch{ + BatchKey: randBatchKey(t), + Seedlings: map[string]*Seedling{}, + AssetMetas: make(AssetMetas), + GenesisPacket: &funded, + } + batch.UpdateState(BatchStateBroadcast) + + caretaker := NewBatchCaretaker(&BatchCaretakerConfig{ + Batch: batch, + GardenKit: GardenKit{ + Wallet: wallet, + ChainBridge: chain, + }, + BroadcastCompleteChan: make(chan struct{}, 1), + BroadcastErrChan: make(chan error, 1), + }) + caretaker.anchorOutputIndex = anchorIdx + + confChecked := make(chan struct{}) + go func() { + <-chain.PublishReq + }() + go func() { + <-chain.ConfReqSignal + require.Equal(t, anchorScript, chain.LastConfPkScript) + close(confChecked) + }() + + _, err = caretaker.stateStep(BatchStateBroadcast) + require.NoError(t, err) + + select { + case <-confChecked: + case <-time.After(2 * time.Second): + t.Fatal("expected confirmation registration for anchor output") + } +} + +// TestCancelPreparedCustomAnchorBatch rejects cancellation after prepare. +func TestCancelPreparedCustomAnchorBatch(t *testing.T) { + planter := &ChainPlanter{} + batchKey, err := btcec.NewPrivateKey() + require.NoError(t, err) + + pkt := testCustomAnchorPacket(t) + funded, err := customGenesisPsbt( + address.TestNet3Tap, nil, pkt, 0, -1, noneUint32(), + ) + require.NoError(t, err) + + planter.pendingBatch = &MintingBatch{ + BatchKey: keychain.KeyDescriptor{PubKey: batchKey.PubKey()}, + Seedlings: map[string]*Seedling{}, + GenesisPacket: &funded, + } + planter.pendingBatch.UpdateState(BatchStateCommitted) + + err = planter.cancelMintingBatch( + context.Background(), planter.pendingBatch.BatchKey.PubKey, + ) + require.ErrorContains(t, err, "not cancellable") +} diff --git a/tapgarden/custom_anchor_test.go b/tapgarden/custom_anchor_test.go new file mode 100644 index 0000000000..e237266770 --- /dev/null +++ b/tapgarden/custom_anchor_test.go @@ -0,0 +1,221 @@ +package tapgarden + +import ( + "bytes" + "errors" + "testing" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/btcec/v2/schnorr" + "github.com/btcsuite/btcd/btcutil/psbt" + "github.com/btcsuite/btcd/chaincfg/chainhash" + "github.com/btcsuite/btcd/txscript" + "github.com/btcsuite/btcd/wire" + "github.com/lightninglabs/taproot-assets/address" + "github.com/lightninglabs/taproot-assets/fn" + "github.com/lightninglabs/taproot-assets/tapsend" + "github.com/stretchr/testify/require" +) + +func testCustomAnchorPacket(t *testing.T) *psbt.Packet { + t.Helper() + + _, pub := btcec.PrivKeyFromBytes(bytes.Repeat([]byte{1}, 32)) + pkScript, err := txscript.PayToTaprootScript(pub) + require.NoError(t, err) + var prevHash chainhash.Hash + prevHash[0] = 1 + tx := wire.NewMsgTx(2) + tx.AddTxIn(&wire.TxIn{PreviousOutPoint: wire.OutPoint{ + Hash: prevHash, Index: 1, + }}) + tx.AddTxOut(&wire.TxOut{Value: 1_000, PkScript: pkScript}) + pkt, err := psbt.NewFromUnsignedTx(tx) + require.NoError(t, err) + pkt.Inputs[0].WitnessUtxo = &wire.TxOut{ + Value: 2_000, PkScript: pkScript, + } + pkt.Outputs[0].TaprootInternalKey = schnorr.SerializePubKey(pub) + pkt.Unknowns = []*psbt.Unknown{{Key: []byte{0x50}, Value: []byte("x")}} + + return pkt +} + +func TestCustomGenesisPsbtValidation(t *testing.T) { + pkt := testCustomAnchorPacket(t) + funded, err := customGenesisPsbt( + address.TestNet3Tap, nil, pkt, 0, -1, noneUint32(), + ) + require.NoError(t, err) + require.True(t, isCustomAnchorPsbt(funded.Pkt)) + require.True(t, funded.GenesisOutpoint().IsSome()) + + bad := testCustomAnchorPacket(t) + bad.Inputs = nil + _, err = customGenesisPsbt( + address.TestNet3Tap, nil, bad, 0, -1, noneUint32(), + ) + require.ErrorContains(t, err, "input maps") + + underfunded := testCustomAnchorPacket(t) + underfunded.Inputs[0].WitnessUtxo.Value = 500 + _, err = customGenesisPsbt( + address.TestNet3Tap, nil, underfunded, 0, -1, noneUint32(), + ) + require.ErrorContains(t, err, "outputs exceed") + + dust := testCustomAnchorPacket(t) + dust.UnsignedTx.TxOut[0].Value = 1 + dust.UnsignedTx.TxOut[0].PkScript = []byte{txscript.OP_RETURN} + _, err = customGenesisPsbt( + address.TestNet3Tap, nil, dust, 0, -1, noneUint32(), + ) + require.ErrorContains(t, err, "anchor output is dust") +} + +func TestMergeSignedCustomPsbt(t *testing.T) { + stored := testCustomAnchorPacket(t) + markCustomAnchorPsbt(stored) + signed := clonePsbt(t, stored) + signed.Inputs[0].FinalScriptSig = []byte{} + signed.Inputs[0].FinalScriptWitness = []byte{1, 0} + signed.Inputs[0].TaprootInternalKey = nil + + merged, err := mergeSignedCustomPsbt(stored, signed) + require.NoError(t, err) + require.NotNil(t, merged.Inputs[0].FinalScriptSig) + require.NotEmpty(t, merged.Inputs[0].FinalScriptWitness) + require.Equal(t, stored.Inputs[0].WitnessUtxo, + merged.Inputs[0].WitnessUtxo) + + mutated := clonePsbt(t, signed) + mutated.Inputs[0].WitnessUtxo.Value++ + _, err = mergeSignedCustomPsbt(stored, mutated) + require.ErrorContains(t, err, "changes input UTXO") + require.Nil(t, stored.Inputs[0].FinalScriptSig) +} + +func TestFundedMintAnchorPsbtCopyPreservesMetadata(t *testing.T) { + pkt := testCustomAnchorPacket(t) + pkt.Outputs[0].Unknowns = []*psbt.Unknown{{ + Key: []byte{0x51}, Value: []byte("output"), + }} + pkt.Inputs[0].SighashType = txscript.SigHashSingle + original := &FundedMintAnchorPsbt{FundedPsbt: fundedPsbt(pkt)} + + copyPkt := original.Copy().Pkt + require.Equal(t, pkt.Unknowns, copyPkt.Unknowns) + require.Equal(t, pkt.Outputs, copyPkt.Outputs) + require.Equal(t, pkt.Inputs, copyPkt.Inputs) + copyPkt.Unknowns[0].Value[0] ^= 1 + require.NotEqual(t, pkt.Unknowns, copyPkt.Unknowns) +} + +func TestCustomGenesisPsbtSupplyPreCommitment(t *testing.T) { + seedling := RandGroupAnchorSeedling(t, "supply-anchor", true) + batch := &MintingBatch{ + Seedlings: map[string]*Seedling{ + seedling.AssetName: &seedling, + }, + SupplyCommitments: true, + } + + pkt := testCustomAnchorPacket(t) + delegationKey, err := seedling.DelegationKey.UnwrapOrErr( + errors.New("delegation key missing"), + ) + require.NoError(t, err) + preCommitOut, err := PreCommitTxOut(*delegationKey.PubKey) + require.NoError(t, err) + pkt.UnsignedTx.AddTxOut(&preCommitOut) + pkt.Outputs = append(pkt.Outputs, psbt.POutput{}) + + _, err = customGenesisPsbt( + address.TestNet3Tap, batch, clonePsbt(t, pkt), 0, -1, + noneUint32(), + ) + require.ErrorContains(t, err, "requires a pre-commitment output index") + + wrong := clonePsbt(t, pkt) + wrong.UnsignedTx.TxOut[1].PkScript[0] ^= 1 + _, err = customGenesisPsbt( + address.TestNet3Tap, batch, wrong, 0, -1, fn.Some(uint32(1)), + ) + require.ErrorContains(t, err, "doesn't match the batch delegation key") + + funded, err := customGenesisPsbt( + address.TestNet3Tap, batch, clonePsbt(t, pkt), 0, -1, + fn.Some(uint32(1)), + ) + require.NoError(t, err) + preCommit, err := funded.PreCommitmentOutput.UnwrapOrErr( + errors.New("pre-commitment output missing"), + ) + require.NoError(t, err) + require.Equal(t, uint32(1), preCommit.OutIdx) + require.Equal(t, schnorr.SerializePubKey(delegationKey.PubKey), + funded.Pkt.Outputs[1].TaprootInternalKey) + require.Len(t, funded.Pkt.Outputs[1].Bip32Derivation, 1) + require.Len(t, funded.Pkt.Outputs[1].TaprootBip32Derivation, 1) +} + +func noneUint32() fn.Option[uint32] { return fn.None[uint32]() } + +func fundedPsbt(pkt *psbt.Packet) tapsend.FundedPsbt { + return tapsend.FundedPsbt{Pkt: pkt, ChangeOutputIndex: -1} +} + +func clonePsbt(t *testing.T, pkt *psbt.Packet) *psbt.Packet { + t.Helper() + var buf bytes.Buffer + require.NoError(t, pkt.Serialize(&buf)) + clone, err := psbt.NewFromRawBytes(&buf, false) + require.NoError(t, err) + return clone +} + +func TestCustomGenesisPsbtDoesNotMutateCallerPacket(t *testing.T) { + original := testCustomAnchorPacket(t) + before := clonePsbt(t, original) + + _, err := customGenesisPsbt( + address.TestNet3Tap, nil, original, 0, -1, noneUint32(), + ) + require.NoError(t, err) + + after := clonePsbt(t, original) + require.Equal(t, before.UnsignedTx.TxOut[0].Value, + after.UnsignedTx.TxOut[0].Value) + require.False(t, isCustomAnchorPsbt(original)) +} + +func serializeFinalWitness(t *testing.T, hashType txscript.SigHashType) []byte { + t.Helper() + + sig := bytes.Repeat([]byte{1}, 64) + sig = append(sig, byte(hashType)) + + var buf bytes.Buffer + require.NoError(t, psbt.WriteTxWitness(&buf, [][]byte{sig})) + + return buf.Bytes() +} + +func TestValidateAnchorInputSigHashTypesRejectsNonAll(t *testing.T) { + pkt := testCustomAnchorPacket(t) + pkt.Inputs[0].FinalScriptWitness = serializeFinalWitness( + t, txscript.SigHashSingle, + ) + + err := validateAnchorInputSigHashTypes(pkt) + require.ErrorContains(t, err, "disallowed sighash") +} + +func TestValidateAnchorInputSigHashTypesAllowsDefault(t *testing.T) { + pkt := testCustomAnchorPacket(t) + pkt.Inputs[0].FinalScriptWitness = serializeFinalWitness( + t, txscript.SigHashDefault, + ) + + require.NoError(t, validateAnchorInputSigHashTypes(pkt)) +} diff --git a/tapgarden/interface.go b/tapgarden/interface.go index 848ad3c83c..d45095eed1 100644 --- a/tapgarden/interface.go +++ b/tapgarden/interface.go @@ -62,6 +62,9 @@ type Planter interface { // deriving all witnesses necessary to create the final genesis TX. SealBatch(params SealParams) (*MintingBatch, error) + // PrepareBatch commits a custom-anchor batch and returns the PSBT to sign. + PrepareBatch() (*MintingBatch, error) + // FinalizeBatch signals that the asset minter should finalize // the current batch, if one exists. FinalizeBatch(params FinalizeParams) (*MintingBatch, error) diff --git a/tapgarden/mock.go b/tapgarden/mock.go index f58e91ba23..9df351647a 100644 --- a/tapgarden/mock.go +++ b/tapgarden/mock.go @@ -593,6 +593,17 @@ type MockChainBridge struct { BlocksMu sync.RWMutex Blocks map[chainhash.Hash]*wire.MsgBlock + // BlocksByHeight is an optional height-indexed block map used by tests + // that exercise GetBlockByHeight. + BlocksByHeight map[int64]*wire.MsgBlock + + // TipHeight, when non-zero, overrides CurrentHeight. + TipHeight uint32 + + // LastConfPkScript records the pkScript from the most recent conf + // registration (for caretaker regression tests). + LastConfPkScript []byte + failFeeEstimates atomic.Bool errConf atomic.Int32 emptyConf atomic.Int32 @@ -653,9 +664,11 @@ func (m *MockChainBridge) SendConfNtfn(reqNo int, blockHash *chainhash.Hash, } func (m *MockChainBridge) RegisterConfirmationsNtfn(ctx context.Context, - _ *chainhash.Hash, _ []byte, _, _ uint32, _ bool, + _ *chainhash.Hash, pkScript []byte, _, _ uint32, _ bool, _ chan struct{}) (*chainntnfs.ConfirmationEvent, chan error, error) { + m.LastConfPkScript = pkScript + select { case <-ctx.Done(): return nil, nil, fmt.Errorf("shutting down") @@ -733,6 +746,16 @@ func (m *MockChainBridge) SetBlock(hash chainhash.Hash, block *wire.MsgBlock) { func (m *MockChainBridge) GetBlockByHeight(ctx context.Context, blockHeight int64) (*wire.MsgBlock, error) { + if m.BlocksByHeight != nil { + block, ok := m.BlocksByHeight[blockHeight] + if !ok { + return nil, fmt.Errorf("unknown block height %d", + blockHeight) + } + + return block, nil + } + return &wire.MsgBlock{}, nil } @@ -761,6 +784,10 @@ func (m *MockChainBridge) VerifyBlock(_ context.Context, } func (m *MockChainBridge) CurrentHeight(_ context.Context) (uint32, error) { + if m.TipHeight != 0 { + return m.TipHeight, nil + } + return 0, nil } diff --git a/tapgarden/planter.go b/tapgarden/planter.go index 2b9b763a2a..0e344aa06d 100644 --- a/tapgarden/planter.go +++ b/tapgarden/planter.go @@ -313,6 +313,7 @@ type UnsealedSeedling struct { type FinalizeParams struct { FeeRate fn.Option[chainfee.SatPerKWeight] SiblingTapTree fn.Option[asset.TapscriptTreeNodes] + SignedPsbt *psbt.Packet } // FundParams are the options available to change how a batch is funded, and how @@ -320,6 +321,18 @@ type FinalizeParams struct { type FundParams struct { FeeRate fn.Option[chainfee.SatPerKWeight] SiblingTapTree fn.Option[asset.TapscriptTreeNodes] + + // AnchorPsbt is an optional caller-authored anchor transaction. + AnchorPsbt *psbt.Packet + + // AssetAnchorOutIdx selects the output that receives the asset commitment. + AssetAnchorOutIdx uint32 + + // ChangeOutputIndex identifies a pre-existing change output. -1 means none. + ChangeOutputIndex int32 + + // PreCommitOutputIndex selects the supply commitment output when enabled. + PreCommitOutputIndex fn.Option[uint32] } // PendingGroupWitness specifies the asset group witness for an asset seedling @@ -390,6 +403,7 @@ const ( reqTypeCancelBatch reqTypeFundBatch reqTypeSealBatch + reqTypePrepareBatch ) // ChainPlanter is responsible for accepting new incoming requests to create @@ -624,6 +638,31 @@ func (c *ChainPlanter) Start() error { } } + if batchState == BatchStateCommitted && + batch.GenesisPacket != nil && + isCustomAnchorPsbt(batch.GenesisPacket.Pkt) { + + if _, err := psbt.Extract( + batch.GenesisPacket.Pkt, + ); err != nil { + + log.Infof("Skipping ChainCaretaker(%x) "+ + "awaiting external custom anchor "+ + "signature", batchKey) + if c.pendingBatch == nil { + c.pendingBatch = batch + } + _ = renewCustomAnchorLeases( + ctx, c.cfg.Wallet, + customAnchorLeaseID( + batch.BatchKey.PubKey, + ), + batch.GenesisPacket, + ) + continue + } + } + log.Infof("Launching ChainCaretaker(%x)", batchKey) caretaker := c.newCaretakerForBatch(batch, nil) if err := caretaker.Start(); err != nil { @@ -1851,15 +1890,30 @@ func (c *ChainPlanter) cancelMintingBatch(ctx context.Context, log.Infof("Cancelling MintingBatch(key=%x, num_assets=%v)", batchKeySerialized, len(c.pendingBatch.Seedlings)) + if c.pendingBatch.State() == BatchStateCommitted && + c.pendingBatch.GenesisPacket != nil && + isCustomAnchorPsbt(c.pendingBatch.GenesisPacket.Pkt) { + + return fmt.Errorf("prepared custom anchor batch is not " + + "cancellable") + } + // If the target batch was not assigned a caretaker, we only need to // update the batch state on disk to cancel it. + cancelState := BatchStateSeedlingCancelled + if c.pendingBatch.State() == BatchStateCommitted { + cancelState = BatchStateSproutCancelled + } + err := c.cfg.Log.UpdateBatchState( - ctx, batchKey, BatchStateSeedlingCancelled, + ctx, batchKey, cancelState, ) if err != nil { return fmt.Errorf("unable to cancel minting batch: %w", err) } + releaseBatchFundingInputs(ctx, c.cfg.Wallet, c.pendingBatch) + return nil } @@ -2023,6 +2077,26 @@ func (c *ChainPlanter) gardener() { Batch: verboseBatch, }) + case reqTypePrepareBatch: + if c.pendingBatch == nil { + req.Error(fmt.Errorf("no pending batch")) + break + } + + ctx, cancel := c.WithCtxQuit() + preparedBatch, err := c.prepareBatch( + ctx, c.pendingBatch, + ) + cancel() + if err != nil { + req.Error(fmt.Errorf("unable to prepare minting "+ + "batch: %w", err)) + break + } + + c.pendingBatch = preparedBatch + req.Resolve(preparedBatch.Copy()) + case reqTypeSealBatch: if c.pendingBatch == nil { req.Error(fmt.Errorf("no pending " + @@ -2065,6 +2139,30 @@ func (c *ChainPlanter) gardener() { } case reqTypeFinalizeBatch: + finalizeReqParams, paramErr := + typedParam[FinalizeParams](req) + if paramErr != nil { + req.Error(fmt.Errorf("bad finalize "+ + "params: %w", paramErr)) + break + } + + ctx, cancel := c.WithCtxQuit() + c.attachPendingCustomAnchorBatch(ctx) + cancel() + + if c.pendingBatch == nil && + finalizeReqParams.SignedPsbt != nil { + + if batch, ok := c.customAnchorBatchAwaitingRetry( + finalizeReqParams.SignedPsbt, + ); ok { + + req.Resolve(batch.Copy()) + break + } + } + if c.pendingBatch == nil { req.Error(fmt.Errorf("no pending " + "batch")) @@ -2075,14 +2173,6 @@ func (c *ChainPlanter) gardener() { batchKeySerial := asset.ToSerialized(batchKey) log.Infof("Finalizing batch %x", batchKeySerial) - finalizeReqParams, err := - typedParam[FinalizeParams](req) - if err != nil { - req.Error(fmt.Errorf("bad finalize "+ - "params: %w", err)) - break - } - caretaker, err := c.finalizeBatch( *finalizeReqParams, ) @@ -2182,6 +2272,45 @@ func (c *ChainPlanter) fundBatch(ctx context.Context, params FundParams, computeFunding := func(batch *MintingBatch) ( *FundedMintAnchorPsbt, error) { + if params.AnchorPsbt != nil { + anchorKeyDesc, err := customAnchorKeyDesc( + c.cfg.ChainParams, params.AnchorPsbt, + params.AssetAnchorOutIdx, + ) + if err != nil { + return nil, err + } + if !c.cfg.KeyRing.IsLocalKey(ctx, anchorKeyDesc) { + return nil, fmt.Errorf("custom asset anchor internal " + + "key is not controlled by the backing wallet") + } + + funded, err := customGenesisPsbt( + c.cfg.ChainParams, batch, params.AnchorPsbt, + params.AssetAnchorOutIdx, + params.ChangeOutputIndex, + params.PreCommitOutputIndex, + ) + if err != nil { + return nil, err + } + + locked, err := acquireCustomAnchorLeases( + ctx, c.cfg.Wallet, + customAnchorLeaseID(batch.BatchKey.PubKey), + funded.Pkt, + ) + if err != nil { + return nil, batchFundingError( + ctx, c.cfg.Wallet, batch.BatchKey.PubKey, + &funded, err, + ) + } + funded.LockedUTXOs = locked + + return &funded, nil + } + feeRate, err := c.anchorTxFeeRate(ctx, params.FeeRate) if err != nil { return nil, fmt.Errorf("unable to determine anchor "+ @@ -2243,7 +2372,10 @@ func (c *ChainPlanter) fundBatch(ctx context.Context, params FundParams, err = c.cfg.Log.CommitMintingBatch(ctx, newBatch) if err != nil { - return err + return batchFundingError( + ctx, c.cfg.Wallet, newBatch.BatchKey.PubKey, + mintAnchorTx, err, + ) } c.pendingBatch = newBatch @@ -2265,7 +2397,10 @@ func (c *ChainPlanter) fundBatch(ctx context.Context, params FundParams, ctx, workingBatch.BatchKey.PubKey, rootHash, *mintAnchorTx, ) if err != nil { - return fmt.Errorf("unable to commit batch funding: %w", err) + return batchFundingError( + ctx, c.cfg.Wallet, workingBatch.BatchKey.PubKey, + mintAnchorTx, fmt.Errorf("unable to commit batch funding: %w", err), + ) } // All persistence succeeded; commit the funding to memory. @@ -2644,6 +2779,70 @@ func (c *ChainPlanter) sealBatch(ctx context.Context, params SealParams, return batchWithGroupInfo, nil } +// attachPendingCustomAnchorBatch restores the in-memory pending batch when a +// prepared custom-anchor mint is waiting for an external signature. +func (c *ChainPlanter) attachPendingCustomAnchorBatch(ctx context.Context) { + if c.pendingBatch != nil { + return + } + + batches, err := c.cfg.Log.FetchNonFinalBatches(ctx) + if err != nil { + log.Warnf("Unable to restore pending custom anchor batch: %v", + err) + return + } + + for _, batch := range batches { + if batch.State() != BatchStateCommitted { + continue + } + if batch.GenesisPacket == nil || + !isCustomAnchorPsbt(batch.GenesisPacket.Pkt) { + + continue + } + if _, err := psbt.Extract(batch.GenesisPacket.Pkt); err == nil { + continue + } + + c.pendingBatch = batch + return + } +} + +// customAnchorBatchAwaitingRetry returns a batch that already accepted an +// identical signed PSBT and reached broadcast. +func (c *ChainPlanter) customAnchorBatchAwaitingRetry( + signed *psbt.Packet) (*MintingBatch, bool) { + + for _, caretaker := range c.caretakers { + batch := caretaker.cfg.Batch + if batch.GenesisPacket == nil || + !isCustomAnchorPsbt(batch.GenesisPacket.Pkt) { + + continue + } + if batch.State() < BatchStateBroadcast { + continue + } + + merged, err := mergeSignedCustomPsbt( + batch.GenesisPacket.Pkt, signed, + ) + if err != nil { + continue + } + if _, err := psbt.Extract(merged); err != nil { + continue + } + + return batch, true + } + + return nil, false +} + // finalizeBatch creates a new caretaker for the batch and starts it. func (c *ChainPlanter) finalizeBatch(params FinalizeParams) (*BatchCaretaker, error) { @@ -2657,6 +2856,67 @@ func (c *ChainPlanter) finalizeBatch(params FinalizeParams) (*BatchCaretaker, // funded. If so, reject any provided parameters, as they would conflict // with those previously used for batch funding. haveParams := params.FeeRate.IsSome() || params.SiblingTapTree.IsSome() + if params.SignedPsbt != nil { + if haveParams { + return nil, fmt.Errorf("signed PSBT cannot be combined with " + + "fee rate or tapscript sibling") + } + if c.pendingBatch.State() != BatchStateCommitted || + !isCustomAnchorPsbt(c.pendingBatch.GenesisPacket.Pkt) { + + return nil, fmt.Errorf("no prepared custom batch awaiting " + + "an external signature") + } + merged, err := mergeSignedCustomPsbt( + c.pendingBatch.GenesisPacket.Pkt, params.SignedPsbt, + ) + if err != nil { + return nil, err + } + ctx, cancel := c.WithCtxQuit() + defer cancel() + + if err := validateFinalizedAnchorPsbt(merged); err != nil { + return nil, fmt.Errorf("externally signed PSBT is not fully "+ + "valid: %w", err) + } + if err := validateCustomAnchorFeeRate(ctx, c.cfg.Wallet, merged); err != nil { + return nil, fmt.Errorf("custom anchor fee rate below relay "+ + "minimum: %w", err) + } + + if err := renewCustomAnchorLeases( + ctx, c.cfg.Wallet, + customAnchorLeaseID(c.pendingBatch.BatchKey.PubKey), + c.pendingBatch.GenesisPacket, + ); err != nil { + return nil, fmt.Errorf("unable to renew custom anchor "+ + "leases: %w", err) + } + + c.pendingBatch.GenesisPacket.Pkt = merged + + batchKey := asset.ToSerialized(c.pendingBatch.BatchKey.PubKey) + if existing, ok := c.caretakers[batchKey]; ok && + c.pendingBatch.State() >= BatchStateBroadcast { + + return existing, nil + } + + caretaker := c.newCaretakerForBatch(c.pendingBatch, nil) + if err := caretaker.Start(); err != nil { + return nil, fmt.Errorf("unable to start new caretaker: %w", + err) + } + + return caretaker, nil + } + if c.pendingBatch.IsFunded() && c.pendingBatch.GenesisPacket != nil && + isCustomAnchorPsbt(c.pendingBatch.GenesisPacket.Pkt) { + + return nil, fmt.Errorf("custom anchor batch must be prepared and " + + "finalized with an externally signed PSBT") + } if haveParams && c.pendingBatch.IsFunded() { return nil, fmt.Errorf("cannot provide finalize parameters " + "if batch already funded") @@ -2680,7 +2940,10 @@ func (c *ChainPlanter) finalizeBatch(params FinalizeParams) (*BatchCaretaker, // fails, the batch stays pending so the user can retry. if !c.pendingBatch.IsFunded() { err = c.fundBatch( - ctx, FundParams(params), c.pendingBatch, + ctx, FundParams{ + FeeRate: params.FeeRate, + SiblingTapTree: params.SiblingTapTree, + }, c.pendingBatch, ) if err != nil { return nil, err @@ -2772,6 +3035,18 @@ func (c *ChainPlanter) FundBatch(params FundParams) (*FundBatchResp, error) { return <-req.resp, <-req.err } +// PrepareBatch commits a caller-authored batch into its selected anchor PSBT +// and returns the unsigned commitment packet for external signing. +func (c *ChainPlanter) PrepareBatch() (*MintingBatch, error) { + req := newStateReq[*MintingBatch](reqTypePrepareBatch) + + if !fn.SendOrQuit[stateRequest](c.stateReqs, req, c.Quit) { + return nil, fmt.Errorf("chain planter shutting down") + } + + return <-req.resp, <-req.err +} + // SealBatch attempts to seal the current batch, by providing or deriving all // witnesses necessary to create the final genesis TX. func (c *ChainPlanter) SealBatch(params SealParams) (*MintingBatch, error) { @@ -3427,7 +3702,18 @@ func (f *FundedMintAnchorPsbt) Copy() *FundedMintAnchorPsbt { UnsignedTx: unsignedTx, Inputs: fn.CopySlice(f.Pkt.Inputs), Outputs: fn.CopySlice(f.Pkt.Outputs), - Unknowns: fn.CopySlice(f.Pkt.Unknowns), + } + if f.Pkt.Unknowns != nil { + newMintAnchorPsbt.Pkt.Unknowns = make( + []*psbt.Unknown, len(f.Pkt.Unknowns), + ) + for idx, unknown := range f.Pkt.Unknowns { + newMintAnchorPsbt.Pkt.Unknowns[idx] = + &psbt.Unknown{ + Key: bytes.Clone(unknown.Key), + Value: bytes.Clone(unknown.Value), + } + } } } diff --git a/taprpc/assetwalletrpc/assetwallet.pb.go b/taprpc/assetwalletrpc/assetwallet.pb.go index 89a428090a..d085d61f49 100644 --- a/taprpc/assetwalletrpc/assetwallet.pb.go +++ b/taprpc/assetwalletrpc/assetwallet.pb.go @@ -128,6 +128,64 @@ func (TransitionProofVersion) EnumDescriptor() ([]byte, []int) { return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{1} } +type CommitVirtualPsbtsStatus int32 + +const ( + // No CommitVirtualPsbts call with this request_id has been recorded. + CommitVirtualPsbtsStatus_COMMIT_VIRTUAL_PSBTS_STATUS_UNKNOWN CommitVirtualPsbtsStatus = 0 + // The call has been claimed and has not yet recorded a final response. + // Leased outpoints are present only after funding has returned. A repeat + // of CommitVirtualPsbts does not fund again while the call is in progress + // or while lnd still holds its leases. After those leases expire, the + // same request funds again. + CommitVirtualPsbtsStatus_COMMIT_VIRTUAL_PSBTS_STATUS_PENDING CommitVirtualPsbtsStatus = 1 + // The call completed. Repeating CommitVirtualPsbts with the same request + // returns the stored response while it is still inside the retention + // window. Replay of request_id is only guaranteed within that window. + CommitVirtualPsbtsStatus_COMMIT_VIRTUAL_PSBTS_STATUS_COMPLETED CommitVirtualPsbtsStatus = 2 +) + +// Enum value maps for CommitVirtualPsbtsStatus. +var ( + CommitVirtualPsbtsStatus_name = map[int32]string{ + 0: "COMMIT_VIRTUAL_PSBTS_STATUS_UNKNOWN", + 1: "COMMIT_VIRTUAL_PSBTS_STATUS_PENDING", + 2: "COMMIT_VIRTUAL_PSBTS_STATUS_COMPLETED", + } + CommitVirtualPsbtsStatus_value = map[string]int32{ + "COMMIT_VIRTUAL_PSBTS_STATUS_UNKNOWN": 0, + "COMMIT_VIRTUAL_PSBTS_STATUS_PENDING": 1, + "COMMIT_VIRTUAL_PSBTS_STATUS_COMPLETED": 2, + } +) + +func (x CommitVirtualPsbtsStatus) Enum() *CommitVirtualPsbtsStatus { + p := new(CommitVirtualPsbtsStatus) + *p = x + return p +} + +func (x CommitVirtualPsbtsStatus) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (CommitVirtualPsbtsStatus) Descriptor() protoreflect.EnumDescriptor { + return file_assetwalletrpc_assetwallet_proto_enumTypes[2].Descriptor() +} + +func (CommitVirtualPsbtsStatus) Type() protoreflect.EnumType { + return &file_assetwalletrpc_assetwallet_proto_enumTypes[2] +} + +func (x CommitVirtualPsbtsStatus) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use CommitVirtualPsbtsStatus.Descriptor instead. +func (CommitVirtualPsbtsStatus) EnumDescriptor() ([]byte, []int) { + return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{2} +} + // BackupMode specifies the backup format to use when exporting. type BackupMode int32 @@ -169,11 +227,11 @@ func (x BackupMode) String() string { } func (BackupMode) Descriptor() protoreflect.EnumDescriptor { - return file_assetwalletrpc_assetwallet_proto_enumTypes[2].Descriptor() + return file_assetwalletrpc_assetwallet_proto_enumTypes[3].Descriptor() } func (BackupMode) Type() protoreflect.EnumType { - return &file_assetwalletrpc_assetwallet_proto_enumTypes[2] + return &file_assetwalletrpc_assetwallet_proto_enumTypes[3] } func (x BackupMode) Number() protoreflect.EnumNumber { @@ -182,7 +240,7 @@ func (x BackupMode) Number() protoreflect.EnumNumber { // Deprecated: Use BackupMode.Descriptor instead. func (BackupMode) EnumDescriptor() ([]byte, []int) { - return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{2} + return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{3} } type FundVirtualPsbtRequest struct { @@ -689,8 +747,22 @@ type CommitVirtualPsbtsRequest struct { // The version to use when generating the state transition proof suffixes. // If unset, the daemon's default proof version is used. TransitionProofVersion TransitionProofVersion `protobuf:"varint,11,opt,name=transition_proof_version,json=transitionProofVersion,proto3,enum=assetwalletrpc.TransitionProofVersion" json:"transition_proof_version,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Optional caller-chosen idempotency key, 1 to 64 bytes. When empty, the + // RPC is unchanged and nothing is stored. When set, tapd records the + // outcome under this key. Only a completed or failed stored response is + // returned as-is, and only inside the retention window + // (wallet.commit-virtual-psbt-retention, 24h by default). After that + // window the stored response may be removed and the same request funds + // again. The same key with a different request is rejected. A repeat + // while the first call is still running, or while lnd still holds its + // input leases, is rejected; use GetCommitVirtualPsbtsStatus to read + // the lock ID and leased outpoints. After those leases expire, the + // pending row is deleted and the same request funds again. If + // custom_lock_id is empty, tapd derives a 32-byte lock ID as + // SHA-256(request_id) and uses that for the lnd lease. + RequestId []byte `protobuf:"bytes,12,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *CommitVirtualPsbtsRequest) Reset() { @@ -822,6 +894,13 @@ func (x *CommitVirtualPsbtsRequest) GetTransitionProofVersion() TransitionProofV return TransitionProofVersion_TRANSITION_PROOF_VERSION_V0 } +func (x *CommitVirtualPsbtsRequest) GetRequestId() []byte { + if x != nil { + return x.RequestId + } + return nil +} + type isCommitVirtualPsbtsRequest_AnchorChangeOutput interface { isCommitVirtualPsbtsRequest_AnchorChangeOutput() } @@ -835,7 +914,12 @@ type CommitVirtualPsbtsRequest_ExistingOutputIndex struct { } type CommitVirtualPsbtsRequest_Add struct { - // Add a new P2TR change output to the PSBT if required. + // Add a new P2TR change output to the PSBT if required. When set to + // false, tapd asks lnd not to add a new change output. Until lnd + // supports that mode (see lightningnetwork/lnd#10967), funding may + // still alter the anchor output set; tapd then fails closed with an + // error (see lightninglabs/taproot-assets#2209). Use + // skip_funding=true with caller-supplied inputs or add=true instead. Add bool `protobuf:"varint,5,opt,name=add,proto3,oneof"` } @@ -957,6 +1041,117 @@ func (x *CommitVirtualPsbtsResponse) GetLndLockedUtxos() []*taprpc.OutPoint { return nil } +type GetCommitVirtualPsbtsStatusRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + // The request_id passed to CommitVirtualPsbts. Required, 1 to 64 bytes. + RequestId []byte `protobuf:"bytes,1,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetCommitVirtualPsbtsStatusRequest) Reset() { + *x = GetCommitVirtualPsbtsStatusRequest{} + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[9] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetCommitVirtualPsbtsStatusRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetCommitVirtualPsbtsStatusRequest) ProtoMessage() {} + +func (x *GetCommitVirtualPsbtsStatusRequest) ProtoReflect() protoreflect.Message { + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[9] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetCommitVirtualPsbtsStatusRequest.ProtoReflect.Descriptor instead. +func (*GetCommitVirtualPsbtsStatusRequest) Descriptor() ([]byte, []int) { + return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{9} +} + +func (x *GetCommitVirtualPsbtsStatusRequest) GetRequestId() []byte { + if x != nil { + return x.RequestId + } + return nil +} + +type GetCommitVirtualPsbtsStatusResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + // Whether the commit is unknown, still in progress, or completed. + Status CommitVirtualPsbtsStatus `protobuf:"varint,1,opt,name=status,proto3,enum=assetwalletrpc.CommitVirtualPsbtsStatus" json:"status,omitempty"` + // The lnd lock ID for the leases, when known. This is the request's + // custom_lock_id (or the ID derived from request_id) until funding + // returns, then the lock ID reported by lnd. + LockId []byte `protobuf:"bytes,2,opt,name=lock_id,json=lockId,proto3" json:"lock_id,omitempty"` + // Outpoints leased for this commit. Empty until funding has returned. + // Only inputs added by CommitVirtualPsbts are included. + LndLockedUtxos []*taprpc.OutPoint `protobuf:"bytes,3,rep,name=lnd_locked_utxos,json=lndLockedUtxos,proto3" json:"lnd_locked_utxos,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetCommitVirtualPsbtsStatusResponse) Reset() { + *x = GetCommitVirtualPsbtsStatusResponse{} + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[10] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetCommitVirtualPsbtsStatusResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetCommitVirtualPsbtsStatusResponse) ProtoMessage() {} + +func (x *GetCommitVirtualPsbtsStatusResponse) ProtoReflect() protoreflect.Message { + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[10] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetCommitVirtualPsbtsStatusResponse.ProtoReflect.Descriptor instead. +func (*GetCommitVirtualPsbtsStatusResponse) Descriptor() ([]byte, []int) { + return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{10} +} + +func (x *GetCommitVirtualPsbtsStatusResponse) GetStatus() CommitVirtualPsbtsStatus { + if x != nil { + return x.Status + } + return CommitVirtualPsbtsStatus_COMMIT_VIRTUAL_PSBTS_STATUS_UNKNOWN +} + +func (x *GetCommitVirtualPsbtsStatusResponse) GetLockId() []byte { + if x != nil { + return x.LockId + } + return nil +} + +func (x *GetCommitVirtualPsbtsStatusResponse) GetLndLockedUtxos() []*taprpc.OutPoint { + if x != nil { + return x.LndLockedUtxos + } + return nil +} + type PublishAndLogRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The funded BTC level anchor transaction with all outputs updated to commit @@ -983,14 +1178,23 @@ type PublishAndLogRequest struct { // An optional short label for the transfer. This label can be used to track // the progress of the transfer via the logs or an event subscription. // Multiple transfers can share the same label. - Label string `protobuf:"bytes,7,opt,name=label,proto3" json:"label,omitempty"` + Label string `protobuf:"bytes,7,opt,name=label,proto3" json:"label,omitempty"` + // Optional caller-chosen idempotency key for this publish. A retry that + // repeats the key with the same anchor transaction returns the transfer + // already logged for that anchor. Reusing the key for a different anchor + // transaction is rejected while that publish is in flight. The binding is + // process-local and in-flight only: it is released when the publish + // completes or fails and is not kept across a daemon restart. An empty + // key still reconciles by the anchor transaction, so a lost response can + // be retried safely. + RequestId []byte `protobuf:"bytes,8,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *PublishAndLogRequest) Reset() { *x = PublishAndLogRequest{} - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[9] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[11] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1002,7 +1206,7 @@ func (x *PublishAndLogRequest) String() string { func (*PublishAndLogRequest) ProtoMessage() {} func (x *PublishAndLogRequest) ProtoReflect() protoreflect.Message { - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[9] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[11] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1015,7 +1219,7 @@ func (x *PublishAndLogRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use PublishAndLogRequest.ProtoReflect.Descriptor instead. func (*PublishAndLogRequest) Descriptor() ([]byte, []int) { - return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{9} + return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{11} } func (x *PublishAndLogRequest) GetAnchorPsbt() []byte { @@ -1067,6 +1271,13 @@ func (x *PublishAndLogRequest) GetLabel() string { return "" } +func (x *PublishAndLogRequest) GetRequestId() []byte { + if x != nil { + return x.RequestId + } + return nil +} + type NextInternalKeyRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The key family to derive the next internal key for. @@ -1077,7 +1288,7 @@ type NextInternalKeyRequest struct { func (x *NextInternalKeyRequest) Reset() { *x = NextInternalKeyRequest{} - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[10] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[12] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1089,7 +1300,7 @@ func (x *NextInternalKeyRequest) String() string { func (*NextInternalKeyRequest) ProtoMessage() {} func (x *NextInternalKeyRequest) ProtoReflect() protoreflect.Message { - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[10] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[12] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1102,7 +1313,7 @@ func (x *NextInternalKeyRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use NextInternalKeyRequest.ProtoReflect.Descriptor instead. func (*NextInternalKeyRequest) Descriptor() ([]byte, []int) { - return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{10} + return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{12} } func (x *NextInternalKeyRequest) GetKeyFamily() uint32 { @@ -1122,7 +1333,7 @@ type NextInternalKeyResponse struct { func (x *NextInternalKeyResponse) Reset() { *x = NextInternalKeyResponse{} - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[11] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[13] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1134,7 +1345,7 @@ func (x *NextInternalKeyResponse) String() string { func (*NextInternalKeyResponse) ProtoMessage() {} func (x *NextInternalKeyResponse) ProtoReflect() protoreflect.Message { - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[11] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[13] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1147,7 +1358,7 @@ func (x *NextInternalKeyResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use NextInternalKeyResponse.ProtoReflect.Descriptor instead. func (*NextInternalKeyResponse) Descriptor() ([]byte, []int) { - return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{11} + return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{13} } func (x *NextInternalKeyResponse) GetInternalKey() *taprpc.KeyDescriptor { @@ -1167,7 +1378,7 @@ type NextScriptKeyRequest struct { func (x *NextScriptKeyRequest) Reset() { *x = NextScriptKeyRequest{} - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[12] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[14] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1179,7 +1390,7 @@ func (x *NextScriptKeyRequest) String() string { func (*NextScriptKeyRequest) ProtoMessage() {} func (x *NextScriptKeyRequest) ProtoReflect() protoreflect.Message { - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[12] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[14] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1192,7 +1403,7 @@ func (x *NextScriptKeyRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use NextScriptKeyRequest.ProtoReflect.Descriptor instead. func (*NextScriptKeyRequest) Descriptor() ([]byte, []int) { - return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{12} + return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{14} } func (x *NextScriptKeyRequest) GetKeyFamily() uint32 { @@ -1213,7 +1424,7 @@ type NextScriptKeyResponse struct { func (x *NextScriptKeyResponse) Reset() { *x = NextScriptKeyResponse{} - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[13] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[15] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1225,7 +1436,7 @@ func (x *NextScriptKeyResponse) String() string { func (*NextScriptKeyResponse) ProtoMessage() {} func (x *NextScriptKeyResponse) ProtoReflect() protoreflect.Message { - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[13] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[15] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1238,7 +1449,7 @@ func (x *NextScriptKeyResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use NextScriptKeyResponse.ProtoReflect.Descriptor instead. func (*NextScriptKeyResponse) Descriptor() ([]byte, []int) { - return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{13} + return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{15} } func (x *NextScriptKeyResponse) GetScriptKey() *taprpc.ScriptKey { @@ -1259,7 +1470,7 @@ type QueryInternalKeyRequest struct { func (x *QueryInternalKeyRequest) Reset() { *x = QueryInternalKeyRequest{} - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[14] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[16] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1271,7 +1482,7 @@ func (x *QueryInternalKeyRequest) String() string { func (*QueryInternalKeyRequest) ProtoMessage() {} func (x *QueryInternalKeyRequest) ProtoReflect() protoreflect.Message { - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[14] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[16] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1284,7 +1495,7 @@ func (x *QueryInternalKeyRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use QueryInternalKeyRequest.ProtoReflect.Descriptor instead. func (*QueryInternalKeyRequest) Descriptor() ([]byte, []int) { - return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{14} + return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{16} } func (x *QueryInternalKeyRequest) GetInternalKey() []byte { @@ -1304,7 +1515,7 @@ type QueryInternalKeyResponse struct { func (x *QueryInternalKeyResponse) Reset() { *x = QueryInternalKeyResponse{} - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[15] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[17] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1316,7 +1527,7 @@ func (x *QueryInternalKeyResponse) String() string { func (*QueryInternalKeyResponse) ProtoMessage() {} func (x *QueryInternalKeyResponse) ProtoReflect() protoreflect.Message { - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[15] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[17] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1329,7 +1540,7 @@ func (x *QueryInternalKeyResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use QueryInternalKeyResponse.ProtoReflect.Descriptor instead. func (*QueryInternalKeyResponse) Descriptor() ([]byte, []int) { - return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{15} + return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{17} } func (x *QueryInternalKeyResponse) GetInternalKey() *taprpc.KeyDescriptor { @@ -1351,7 +1562,7 @@ type QueryScriptKeyRequest struct { func (x *QueryScriptKeyRequest) Reset() { *x = QueryScriptKeyRequest{} - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[16] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[18] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1363,7 +1574,7 @@ func (x *QueryScriptKeyRequest) String() string { func (*QueryScriptKeyRequest) ProtoMessage() {} func (x *QueryScriptKeyRequest) ProtoReflect() protoreflect.Message { - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[16] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[18] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1376,7 +1587,7 @@ func (x *QueryScriptKeyRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use QueryScriptKeyRequest.ProtoReflect.Descriptor instead. func (*QueryScriptKeyRequest) Descriptor() ([]byte, []int) { - return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{16} + return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{18} } func (x *QueryScriptKeyRequest) GetTweakedScriptKey() []byte { @@ -1397,7 +1608,7 @@ type QueryScriptKeyResponse struct { func (x *QueryScriptKeyResponse) Reset() { *x = QueryScriptKeyResponse{} - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[17] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[19] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1409,7 +1620,7 @@ func (x *QueryScriptKeyResponse) String() string { func (*QueryScriptKeyResponse) ProtoMessage() {} func (x *QueryScriptKeyResponse) ProtoReflect() protoreflect.Message { - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[17] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[19] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1422,7 +1633,7 @@ func (x *QueryScriptKeyResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use QueryScriptKeyResponse.ProtoReflect.Descriptor instead. func (*QueryScriptKeyResponse) Descriptor() ([]byte, []int) { - return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{17} + return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{19} } func (x *QueryScriptKeyResponse) GetScriptKey() *taprpc.ScriptKey { @@ -1452,7 +1663,7 @@ type ProveAssetOwnershipRequest struct { func (x *ProveAssetOwnershipRequest) Reset() { *x = ProveAssetOwnershipRequest{} - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[18] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[20] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1464,7 +1675,7 @@ func (x *ProveAssetOwnershipRequest) String() string { func (*ProveAssetOwnershipRequest) ProtoMessage() {} func (x *ProveAssetOwnershipRequest) ProtoReflect() protoreflect.Message { - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[18] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[20] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1477,7 +1688,7 @@ func (x *ProveAssetOwnershipRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ProveAssetOwnershipRequest.ProtoReflect.Descriptor instead. func (*ProveAssetOwnershipRequest) Descriptor() ([]byte, []int) { - return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{18} + return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{20} } func (x *ProveAssetOwnershipRequest) GetAssetId() []byte { @@ -1517,7 +1728,7 @@ type ProveAssetOwnershipResponse struct { func (x *ProveAssetOwnershipResponse) Reset() { *x = ProveAssetOwnershipResponse{} - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[19] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[21] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1529,7 +1740,7 @@ func (x *ProveAssetOwnershipResponse) String() string { func (*ProveAssetOwnershipResponse) ProtoMessage() {} func (x *ProveAssetOwnershipResponse) ProtoReflect() protoreflect.Message { - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[19] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[21] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1542,7 +1753,7 @@ func (x *ProveAssetOwnershipResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ProveAssetOwnershipResponse.ProtoReflect.Descriptor instead. func (*ProveAssetOwnershipResponse) Descriptor() ([]byte, []int) { - return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{19} + return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{21} } func (x *ProveAssetOwnershipResponse) GetProofWithWitness() []byte { @@ -1567,7 +1778,7 @@ type VerifyAssetOwnershipRequest struct { func (x *VerifyAssetOwnershipRequest) Reset() { *x = VerifyAssetOwnershipRequest{} - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[20] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[22] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1579,7 +1790,7 @@ func (x *VerifyAssetOwnershipRequest) String() string { func (*VerifyAssetOwnershipRequest) ProtoMessage() {} func (x *VerifyAssetOwnershipRequest) ProtoReflect() protoreflect.Message { - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[20] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[22] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1592,7 +1803,7 @@ func (x *VerifyAssetOwnershipRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use VerifyAssetOwnershipRequest.ProtoReflect.Descriptor instead. func (*VerifyAssetOwnershipRequest) Descriptor() ([]byte, []int) { - return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{20} + return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{22} } func (x *VerifyAssetOwnershipRequest) GetProofWithWitness() []byte { @@ -1629,7 +1840,7 @@ type VerifyAssetOwnershipResponse struct { func (x *VerifyAssetOwnershipResponse) Reset() { *x = VerifyAssetOwnershipResponse{} - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[21] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[23] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1641,7 +1852,7 @@ func (x *VerifyAssetOwnershipResponse) String() string { func (*VerifyAssetOwnershipResponse) ProtoMessage() {} func (x *VerifyAssetOwnershipResponse) ProtoReflect() protoreflect.Message { - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[21] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[23] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1654,7 +1865,7 @@ func (x *VerifyAssetOwnershipResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use VerifyAssetOwnershipResponse.ProtoReflect.Descriptor instead. func (*VerifyAssetOwnershipResponse) Descriptor() ([]byte, []int) { - return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{21} + return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{23} } func (x *VerifyAssetOwnershipResponse) GetValidProof() bool { @@ -1709,7 +1920,7 @@ type RemoveUTXOLeaseRequest struct { func (x *RemoveUTXOLeaseRequest) Reset() { *x = RemoveUTXOLeaseRequest{} - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[22] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[24] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1721,7 +1932,7 @@ func (x *RemoveUTXOLeaseRequest) String() string { func (*RemoveUTXOLeaseRequest) ProtoMessage() {} func (x *RemoveUTXOLeaseRequest) ProtoReflect() protoreflect.Message { - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[22] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[24] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1734,7 +1945,7 @@ func (x *RemoveUTXOLeaseRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use RemoveUTXOLeaseRequest.ProtoReflect.Descriptor instead. func (*RemoveUTXOLeaseRequest) Descriptor() ([]byte, []int) { - return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{22} + return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{24} } func (x *RemoveUTXOLeaseRequest) GetOutpoint() *taprpc.OutPoint { @@ -1752,7 +1963,7 @@ type RemoveUTXOLeaseResponse struct { func (x *RemoveUTXOLeaseResponse) Reset() { *x = RemoveUTXOLeaseResponse{} - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[23] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[25] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1764,7 +1975,7 @@ func (x *RemoveUTXOLeaseResponse) String() string { func (*RemoveUTXOLeaseResponse) ProtoMessage() {} func (x *RemoveUTXOLeaseResponse) ProtoReflect() protoreflect.Message { - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[23] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[25] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1777,7 +1988,7 @@ func (x *RemoveUTXOLeaseResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use RemoveUTXOLeaseResponse.ProtoReflect.Descriptor instead. func (*RemoveUTXOLeaseResponse) Descriptor() ([]byte, []int) { - return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{23} + return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{25} } type DeclareScriptKeyRequest struct { @@ -1790,7 +2001,7 @@ type DeclareScriptKeyRequest struct { func (x *DeclareScriptKeyRequest) Reset() { *x = DeclareScriptKeyRequest{} - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[24] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[26] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1802,7 +2013,7 @@ func (x *DeclareScriptKeyRequest) String() string { func (*DeclareScriptKeyRequest) ProtoMessage() {} func (x *DeclareScriptKeyRequest) ProtoReflect() protoreflect.Message { - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[24] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[26] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1815,7 +2026,7 @@ func (x *DeclareScriptKeyRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use DeclareScriptKeyRequest.ProtoReflect.Descriptor instead. func (*DeclareScriptKeyRequest) Descriptor() ([]byte, []int) { - return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{24} + return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{26} } func (x *DeclareScriptKeyRequest) GetScriptKey() *taprpc.ScriptKey { @@ -1836,7 +2047,7 @@ type DeclareScriptKeyResponse struct { func (x *DeclareScriptKeyResponse) Reset() { *x = DeclareScriptKeyResponse{} - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[25] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[27] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1848,7 +2059,7 @@ func (x *DeclareScriptKeyResponse) String() string { func (*DeclareScriptKeyResponse) ProtoMessage() {} func (x *DeclareScriptKeyResponse) ProtoReflect() protoreflect.Message { - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[25] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[27] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1861,7 +2072,7 @@ func (x *DeclareScriptKeyResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use DeclareScriptKeyResponse.ProtoReflect.Descriptor instead. func (*DeclareScriptKeyResponse) Descriptor() ([]byte, []int) { - return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{25} + return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{27} } func (x *DeclareScriptKeyResponse) GetScriptKey() *taprpc.ScriptKey { @@ -1883,7 +2094,7 @@ type ExportAssetWalletBackupRequest struct { func (x *ExportAssetWalletBackupRequest) Reset() { *x = ExportAssetWalletBackupRequest{} - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[26] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[28] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1895,7 +2106,7 @@ func (x *ExportAssetWalletBackupRequest) String() string { func (*ExportAssetWalletBackupRequest) ProtoMessage() {} func (x *ExportAssetWalletBackupRequest) ProtoReflect() protoreflect.Message { - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[26] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[28] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1908,7 +2119,7 @@ func (x *ExportAssetWalletBackupRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ExportAssetWalletBackupRequest.ProtoReflect.Descriptor instead. func (*ExportAssetWalletBackupRequest) Descriptor() ([]byte, []int) { - return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{26} + return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{28} } func (x *ExportAssetWalletBackupRequest) GetMode() BackupMode { @@ -1929,7 +2140,7 @@ type ExportAssetWalletBackupResponse struct { func (x *ExportAssetWalletBackupResponse) Reset() { *x = ExportAssetWalletBackupResponse{} - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[27] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[29] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1941,7 +2152,7 @@ func (x *ExportAssetWalletBackupResponse) String() string { func (*ExportAssetWalletBackupResponse) ProtoMessage() {} func (x *ExportAssetWalletBackupResponse) ProtoReflect() protoreflect.Message { - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[27] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[29] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1954,7 +2165,7 @@ func (x *ExportAssetWalletBackupResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ExportAssetWalletBackupResponse.ProtoReflect.Descriptor instead. func (*ExportAssetWalletBackupResponse) Descriptor() ([]byte, []int) { - return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{27} + return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{29} } func (x *ExportAssetWalletBackupResponse) GetBackup() []byte { @@ -1975,7 +2186,7 @@ type ImportAssetsFromBackupRequest struct { func (x *ImportAssetsFromBackupRequest) Reset() { *x = ImportAssetsFromBackupRequest{} - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[28] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[30] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1987,7 +2198,7 @@ func (x *ImportAssetsFromBackupRequest) String() string { func (*ImportAssetsFromBackupRequest) ProtoMessage() {} func (x *ImportAssetsFromBackupRequest) ProtoReflect() protoreflect.Message { - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[28] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[30] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2000,7 +2211,7 @@ func (x *ImportAssetsFromBackupRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ImportAssetsFromBackupRequest.ProtoReflect.Descriptor instead. func (*ImportAssetsFromBackupRequest) Descriptor() ([]byte, []int) { - return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{28} + return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{30} } func (x *ImportAssetsFromBackupRequest) GetBackup() []byte { @@ -2025,7 +2236,7 @@ type ImportAssetsFromBackupResponse struct { func (x *ImportAssetsFromBackupResponse) Reset() { *x = ImportAssetsFromBackupResponse{} - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[29] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[31] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2037,7 +2248,7 @@ func (x *ImportAssetsFromBackupResponse) String() string { func (*ImportAssetsFromBackupResponse) ProtoMessage() {} func (x *ImportAssetsFromBackupResponse) ProtoReflect() protoreflect.Message { - mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[29] + mi := &file_assetwalletrpc_assetwallet_proto_msgTypes[31] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2050,7 +2261,7 @@ func (x *ImportAssetsFromBackupResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ImportAssetsFromBackupResponse.ProtoReflect.Descriptor instead. func (*ImportAssetsFromBackupResponse) Descriptor() ([]byte, []int) { - return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{29} + return file_assetwalletrpc_assetwallet_proto_rawDescGZIP(), []int{31} } func (x *ImportAssetsFromBackupResponse) GetNumImported() uint32 { @@ -2106,7 +2317,7 @@ const file_assetwalletrpc_assetwallet_proto_rawDesc = "" + "signedPsbt\x12#\n" + "\rsigned_inputs\x18\x02 \x03(\rR\fsignedInputs\"@\n" + "\x19AnchorVirtualPsbtsRequest\x12#\n" + - "\rvirtual_psbts\x18\x01 \x03(\fR\fvirtualPsbts\"\xa7\x04\n" + + "\rvirtual_psbts\x18\x01 \x03(\fR\fvirtualPsbts\"\xc6\x04\n" + "\x19CommitVirtualPsbtsRequest\x12#\n" + "\rvirtual_psbts\x18\x01 \x03(\fR\fvirtualPsbts\x12.\n" + "\x13passive_asset_psbts\x18\x02 \x03(\fR\x11passiveAssetPsbts\x12\x1f\n" + @@ -2121,7 +2332,9 @@ const file_assetwalletrpc_assetwallet_proto_rawDesc = "" + "\x17lock_expiration_seconds\x18\t \x01(\x04R\x15lockExpirationSeconds\x12!\n" + "\fskip_funding\x18\n" + " \x01(\bR\vskipFunding\x12`\n" + - "\x18transition_proof_version\x18\v \x01(\x0e2&.assetwalletrpc.TransitionProofVersionR\x16transitionProofVersionB\x16\n" + + "\x18transition_proof_version\x18\v \x01(\x0e2&.assetwalletrpc.TransitionProofVersionR\x16transitionProofVersion\x12\x1d\n" + + "\n" + + "request_id\x18\f \x01(\fR\trequestIdB\x16\n" + "\x14anchor_change_outputB\x06\n" + "\x04fees\"\xfe\x01\n" + "\x1aCommitVirtualPsbtsResponse\x12\x1f\n" + @@ -2130,7 +2343,14 @@ const file_assetwalletrpc_assetwallet_proto_rawDesc = "" + "\rvirtual_psbts\x18\x02 \x03(\fR\fvirtualPsbts\x12.\n" + "\x13passive_asset_psbts\x18\x04 \x03(\fR\x11passiveAssetPsbts\x12.\n" + "\x13change_output_index\x18\x05 \x01(\x05R\x11changeOutputIndex\x12:\n" + - "\x10lnd_locked_utxos\x18\x06 \x03(\v2\x10.taprpc.OutPointR\x0elndLockedUtxos\"\xc7\x02\n" + + "\x10lnd_locked_utxos\x18\x06 \x03(\v2\x10.taprpc.OutPointR\x0elndLockedUtxos\"C\n" + + "\"GetCommitVirtualPsbtsStatusRequest\x12\x1d\n" + + "\n" + + "request_id\x18\x01 \x01(\fR\trequestId\"\xbc\x01\n" + + "#GetCommitVirtualPsbtsStatusResponse\x12@\n" + + "\x06status\x18\x01 \x01(\x0e2(.assetwalletrpc.CommitVirtualPsbtsStatusR\x06status\x12\x17\n" + + "\alock_id\x18\x02 \x01(\fR\x06lockId\x12:\n" + + "\x10lnd_locked_utxos\x18\x03 \x03(\v2\x10.taprpc.OutPointR\x0elndLockedUtxos\"\xe6\x02\n" + "\x14PublishAndLogRequest\x12\x1f\n" + "\vanchor_psbt\x18\x01 \x01(\fR\n" + "anchorPsbt\x12#\n" + @@ -2139,7 +2359,9 @@ const file_assetwalletrpc_assetwallet_proto_rawDesc = "" + "\x13change_output_index\x18\x04 \x01(\x05R\x11changeOutputIndex\x12:\n" + "\x10lnd_locked_utxos\x18\x05 \x03(\v2\x10.taprpc.OutPointR\x0elndLockedUtxos\x127\n" + "\x18skip_anchor_tx_broadcast\x18\x06 \x01(\bR\x15skipAnchorTxBroadcast\x12\x14\n" + - "\x05label\x18\a \x01(\tR\x05label\"7\n" + + "\x05label\x18\a \x01(\tR\x05label\x12\x1d\n" + + "\n" + + "request_id\x18\b \x01(\fR\trequestId\"7\n" + "\x16NextInternalKeyRequest\x12\x1d\n" + "\n" + "key_family\x18\x01 \x01(\rR\tkeyFamily\"S\n" + @@ -2205,18 +2427,23 @@ const file_assetwalletrpc_assetwallet_proto_rawDesc = "" + " COIN_SELECT_SCRIPT_TREES_ALLOWED\x10\x02*Z\n" + "\x16TransitionProofVersion\x12\x1f\n" + "\x1bTRANSITION_PROOF_VERSION_V0\x10\x00\x12\x1f\n" + - "\x1bTRANSITION_PROOF_VERSION_V1\x10\x01*2\n" + + "\x1bTRANSITION_PROOF_VERSION_V1\x10\x01*\x97\x01\n" + + "\x18CommitVirtualPsbtsStatus\x12'\n" + + "#COMMIT_VIRTUAL_PSBTS_STATUS_UNKNOWN\x10\x00\x12'\n" + + "#COMMIT_VIRTUAL_PSBTS_STATUS_PENDING\x10\x01\x12)\n" + + "%COMMIT_VIRTUAL_PSBTS_STATUS_COMPLETED\x10\x02*2\n" + "\n" + "BackupMode\x12\a\n" + "\x03RAW\x10\x00\x12\v\n" + "\aCOMPACT\x10\x01\x12\x0e\n" + "\n" + - "OPTIMISTIC\x10\x022\xa5\f\n" + + "OPTIMISTIC\x10\x022\xae\r\n" + "\vAssetWallet\x12b\n" + "\x0fFundVirtualPsbt\x12&.assetwalletrpc.FundVirtualPsbtRequest\x1a'.assetwalletrpc.FundVirtualPsbtResponse\x12b\n" + "\x0fSignVirtualPsbt\x12&.assetwalletrpc.SignVirtualPsbtRequest\x1a'.assetwalletrpc.SignVirtualPsbtResponse\x12Z\n" + "\x12AnchorVirtualPsbts\x12).assetwalletrpc.AnchorVirtualPsbtsRequest\x1a\x19.taprpc.SendAssetResponse\x12k\n" + - "\x12CommitVirtualPsbts\x12).assetwalletrpc.CommitVirtualPsbtsRequest\x1a*.assetwalletrpc.CommitVirtualPsbtsResponse\x12X\n" + + "\x12CommitVirtualPsbts\x12).assetwalletrpc.CommitVirtualPsbtsRequest\x1a*.assetwalletrpc.CommitVirtualPsbtsResponse\x12\x86\x01\n" + + "\x1bGetCommitVirtualPsbtsStatus\x122.assetwalletrpc.GetCommitVirtualPsbtsStatusRequest\x1a3.assetwalletrpc.GetCommitVirtualPsbtsStatusResponse\x12X\n" + "\x15PublishAndLogTransfer\x12$.assetwalletrpc.PublishAndLogRequest\x1a\x19.taprpc.SendAssetResponse\x12b\n" + "\x0fNextInternalKey\x12&.assetwalletrpc.NextInternalKeyRequest\x1a'.assetwalletrpc.NextInternalKeyResponse\x12\\\n" + "\rNextScriptKey\x12$.assetwalletrpc.NextScriptKeyRequest\x1a%.assetwalletrpc.NextScriptKeyResponse\x12e\n" + @@ -2241,104 +2468,111 @@ func file_assetwalletrpc_assetwallet_proto_rawDescGZIP() []byte { return file_assetwalletrpc_assetwallet_proto_rawDescData } -var file_assetwalletrpc_assetwallet_proto_enumTypes = make([]protoimpl.EnumInfo, 3) -var file_assetwalletrpc_assetwallet_proto_msgTypes = make([]protoimpl.MessageInfo, 31) +var file_assetwalletrpc_assetwallet_proto_enumTypes = make([]protoimpl.EnumInfo, 4) +var file_assetwalletrpc_assetwallet_proto_msgTypes = make([]protoimpl.MessageInfo, 33) var file_assetwalletrpc_assetwallet_proto_goTypes = []any{ - (CoinSelectType)(0), // 0: assetwalletrpc.CoinSelectType - (TransitionProofVersion)(0), // 1: assetwalletrpc.TransitionProofVersion - (BackupMode)(0), // 2: assetwalletrpc.BackupMode - (*FundVirtualPsbtRequest)(nil), // 3: assetwalletrpc.FundVirtualPsbtRequest - (*FundVirtualPsbtResponse)(nil), // 4: assetwalletrpc.FundVirtualPsbtResponse - (*TxTemplate)(nil), // 5: assetwalletrpc.TxTemplate - (*PrevId)(nil), // 6: assetwalletrpc.PrevId - (*SignVirtualPsbtRequest)(nil), // 7: assetwalletrpc.SignVirtualPsbtRequest - (*SignVirtualPsbtResponse)(nil), // 8: assetwalletrpc.SignVirtualPsbtResponse - (*AnchorVirtualPsbtsRequest)(nil), // 9: assetwalletrpc.AnchorVirtualPsbtsRequest - (*CommitVirtualPsbtsRequest)(nil), // 10: assetwalletrpc.CommitVirtualPsbtsRequest - (*CommitVirtualPsbtsResponse)(nil), // 11: assetwalletrpc.CommitVirtualPsbtsResponse - (*PublishAndLogRequest)(nil), // 12: assetwalletrpc.PublishAndLogRequest - (*NextInternalKeyRequest)(nil), // 13: assetwalletrpc.NextInternalKeyRequest - (*NextInternalKeyResponse)(nil), // 14: assetwalletrpc.NextInternalKeyResponse - (*NextScriptKeyRequest)(nil), // 15: assetwalletrpc.NextScriptKeyRequest - (*NextScriptKeyResponse)(nil), // 16: assetwalletrpc.NextScriptKeyResponse - (*QueryInternalKeyRequest)(nil), // 17: assetwalletrpc.QueryInternalKeyRequest - (*QueryInternalKeyResponse)(nil), // 18: assetwalletrpc.QueryInternalKeyResponse - (*QueryScriptKeyRequest)(nil), // 19: assetwalletrpc.QueryScriptKeyRequest - (*QueryScriptKeyResponse)(nil), // 20: assetwalletrpc.QueryScriptKeyResponse - (*ProveAssetOwnershipRequest)(nil), // 21: assetwalletrpc.ProveAssetOwnershipRequest - (*ProveAssetOwnershipResponse)(nil), // 22: assetwalletrpc.ProveAssetOwnershipResponse - (*VerifyAssetOwnershipRequest)(nil), // 23: assetwalletrpc.VerifyAssetOwnershipRequest - (*VerifyAssetOwnershipResponse)(nil), // 24: assetwalletrpc.VerifyAssetOwnershipResponse - (*RemoveUTXOLeaseRequest)(nil), // 25: assetwalletrpc.RemoveUTXOLeaseRequest - (*RemoveUTXOLeaseResponse)(nil), // 26: assetwalletrpc.RemoveUTXOLeaseResponse - (*DeclareScriptKeyRequest)(nil), // 27: assetwalletrpc.DeclareScriptKeyRequest - (*DeclareScriptKeyResponse)(nil), // 28: assetwalletrpc.DeclareScriptKeyResponse - (*ExportAssetWalletBackupRequest)(nil), // 29: assetwalletrpc.ExportAssetWalletBackupRequest - (*ExportAssetWalletBackupResponse)(nil), // 30: assetwalletrpc.ExportAssetWalletBackupResponse - (*ImportAssetsFromBackupRequest)(nil), // 31: assetwalletrpc.ImportAssetsFromBackupRequest - (*ImportAssetsFromBackupResponse)(nil), // 32: assetwalletrpc.ImportAssetsFromBackupResponse - nil, // 33: assetwalletrpc.TxTemplate.RecipientsEntry - (*taprpc.AddressWithAmount)(nil), // 34: taprpc.AddressWithAmount - (*taprpc.OutPoint)(nil), // 35: taprpc.OutPoint - (*taprpc.KeyDescriptor)(nil), // 36: taprpc.KeyDescriptor - (*taprpc.ScriptKey)(nil), // 37: taprpc.ScriptKey - (*taprpc.SendAssetResponse)(nil), // 38: taprpc.SendAssetResponse + (CoinSelectType)(0), // 0: assetwalletrpc.CoinSelectType + (TransitionProofVersion)(0), // 1: assetwalletrpc.TransitionProofVersion + (CommitVirtualPsbtsStatus)(0), // 2: assetwalletrpc.CommitVirtualPsbtsStatus + (BackupMode)(0), // 3: assetwalletrpc.BackupMode + (*FundVirtualPsbtRequest)(nil), // 4: assetwalletrpc.FundVirtualPsbtRequest + (*FundVirtualPsbtResponse)(nil), // 5: assetwalletrpc.FundVirtualPsbtResponse + (*TxTemplate)(nil), // 6: assetwalletrpc.TxTemplate + (*PrevId)(nil), // 7: assetwalletrpc.PrevId + (*SignVirtualPsbtRequest)(nil), // 8: assetwalletrpc.SignVirtualPsbtRequest + (*SignVirtualPsbtResponse)(nil), // 9: assetwalletrpc.SignVirtualPsbtResponse + (*AnchorVirtualPsbtsRequest)(nil), // 10: assetwalletrpc.AnchorVirtualPsbtsRequest + (*CommitVirtualPsbtsRequest)(nil), // 11: assetwalletrpc.CommitVirtualPsbtsRequest + (*CommitVirtualPsbtsResponse)(nil), // 12: assetwalletrpc.CommitVirtualPsbtsResponse + (*GetCommitVirtualPsbtsStatusRequest)(nil), // 13: assetwalletrpc.GetCommitVirtualPsbtsStatusRequest + (*GetCommitVirtualPsbtsStatusResponse)(nil), // 14: assetwalletrpc.GetCommitVirtualPsbtsStatusResponse + (*PublishAndLogRequest)(nil), // 15: assetwalletrpc.PublishAndLogRequest + (*NextInternalKeyRequest)(nil), // 16: assetwalletrpc.NextInternalKeyRequest + (*NextInternalKeyResponse)(nil), // 17: assetwalletrpc.NextInternalKeyResponse + (*NextScriptKeyRequest)(nil), // 18: assetwalletrpc.NextScriptKeyRequest + (*NextScriptKeyResponse)(nil), // 19: assetwalletrpc.NextScriptKeyResponse + (*QueryInternalKeyRequest)(nil), // 20: assetwalletrpc.QueryInternalKeyRequest + (*QueryInternalKeyResponse)(nil), // 21: assetwalletrpc.QueryInternalKeyResponse + (*QueryScriptKeyRequest)(nil), // 22: assetwalletrpc.QueryScriptKeyRequest + (*QueryScriptKeyResponse)(nil), // 23: assetwalletrpc.QueryScriptKeyResponse + (*ProveAssetOwnershipRequest)(nil), // 24: assetwalletrpc.ProveAssetOwnershipRequest + (*ProveAssetOwnershipResponse)(nil), // 25: assetwalletrpc.ProveAssetOwnershipResponse + (*VerifyAssetOwnershipRequest)(nil), // 26: assetwalletrpc.VerifyAssetOwnershipRequest + (*VerifyAssetOwnershipResponse)(nil), // 27: assetwalletrpc.VerifyAssetOwnershipResponse + (*RemoveUTXOLeaseRequest)(nil), // 28: assetwalletrpc.RemoveUTXOLeaseRequest + (*RemoveUTXOLeaseResponse)(nil), // 29: assetwalletrpc.RemoveUTXOLeaseResponse + (*DeclareScriptKeyRequest)(nil), // 30: assetwalletrpc.DeclareScriptKeyRequest + (*DeclareScriptKeyResponse)(nil), // 31: assetwalletrpc.DeclareScriptKeyResponse + (*ExportAssetWalletBackupRequest)(nil), // 32: assetwalletrpc.ExportAssetWalletBackupRequest + (*ExportAssetWalletBackupResponse)(nil), // 33: assetwalletrpc.ExportAssetWalletBackupResponse + (*ImportAssetsFromBackupRequest)(nil), // 34: assetwalletrpc.ImportAssetsFromBackupRequest + (*ImportAssetsFromBackupResponse)(nil), // 35: assetwalletrpc.ImportAssetsFromBackupResponse + nil, // 36: assetwalletrpc.TxTemplate.RecipientsEntry + (*taprpc.AddressWithAmount)(nil), // 37: taprpc.AddressWithAmount + (*taprpc.OutPoint)(nil), // 38: taprpc.OutPoint + (*taprpc.KeyDescriptor)(nil), // 39: taprpc.KeyDescriptor + (*taprpc.ScriptKey)(nil), // 40: taprpc.ScriptKey + (*taprpc.SendAssetResponse)(nil), // 41: taprpc.SendAssetResponse } var file_assetwalletrpc_assetwallet_proto_depIdxs = []int32{ - 5, // 0: assetwalletrpc.FundVirtualPsbtRequest.raw:type_name -> assetwalletrpc.TxTemplate + 6, // 0: assetwalletrpc.FundVirtualPsbtRequest.raw:type_name -> assetwalletrpc.TxTemplate 0, // 1: assetwalletrpc.FundVirtualPsbtRequest.coin_select_type:type_name -> assetwalletrpc.CoinSelectType - 6, // 2: assetwalletrpc.TxTemplate.inputs:type_name -> assetwalletrpc.PrevId - 33, // 3: assetwalletrpc.TxTemplate.recipients:type_name -> assetwalletrpc.TxTemplate.RecipientsEntry - 34, // 4: assetwalletrpc.TxTemplate.addresses_with_amounts:type_name -> taprpc.AddressWithAmount - 35, // 5: assetwalletrpc.PrevId.outpoint:type_name -> taprpc.OutPoint + 7, // 2: assetwalletrpc.TxTemplate.inputs:type_name -> assetwalletrpc.PrevId + 36, // 3: assetwalletrpc.TxTemplate.recipients:type_name -> assetwalletrpc.TxTemplate.RecipientsEntry + 37, // 4: assetwalletrpc.TxTemplate.addresses_with_amounts:type_name -> taprpc.AddressWithAmount + 38, // 5: assetwalletrpc.PrevId.outpoint:type_name -> taprpc.OutPoint 1, // 6: assetwalletrpc.CommitVirtualPsbtsRequest.transition_proof_version:type_name -> assetwalletrpc.TransitionProofVersion - 35, // 7: assetwalletrpc.CommitVirtualPsbtsResponse.lnd_locked_utxos:type_name -> taprpc.OutPoint - 35, // 8: assetwalletrpc.PublishAndLogRequest.lnd_locked_utxos:type_name -> taprpc.OutPoint - 36, // 9: assetwalletrpc.NextInternalKeyResponse.internal_key:type_name -> taprpc.KeyDescriptor - 37, // 10: assetwalletrpc.NextScriptKeyResponse.script_key:type_name -> taprpc.ScriptKey - 36, // 11: assetwalletrpc.QueryInternalKeyResponse.internal_key:type_name -> taprpc.KeyDescriptor - 37, // 12: assetwalletrpc.QueryScriptKeyResponse.script_key:type_name -> taprpc.ScriptKey - 35, // 13: assetwalletrpc.ProveAssetOwnershipRequest.outpoint:type_name -> taprpc.OutPoint - 35, // 14: assetwalletrpc.VerifyAssetOwnershipResponse.outpoint:type_name -> taprpc.OutPoint - 35, // 15: assetwalletrpc.RemoveUTXOLeaseRequest.outpoint:type_name -> taprpc.OutPoint - 37, // 16: assetwalletrpc.DeclareScriptKeyRequest.script_key:type_name -> taprpc.ScriptKey - 37, // 17: assetwalletrpc.DeclareScriptKeyResponse.script_key:type_name -> taprpc.ScriptKey - 2, // 18: assetwalletrpc.ExportAssetWalletBackupRequest.mode:type_name -> assetwalletrpc.BackupMode - 3, // 19: assetwalletrpc.AssetWallet.FundVirtualPsbt:input_type -> assetwalletrpc.FundVirtualPsbtRequest - 7, // 20: assetwalletrpc.AssetWallet.SignVirtualPsbt:input_type -> assetwalletrpc.SignVirtualPsbtRequest - 9, // 21: assetwalletrpc.AssetWallet.AnchorVirtualPsbts:input_type -> assetwalletrpc.AnchorVirtualPsbtsRequest - 10, // 22: assetwalletrpc.AssetWallet.CommitVirtualPsbts:input_type -> assetwalletrpc.CommitVirtualPsbtsRequest - 12, // 23: assetwalletrpc.AssetWallet.PublishAndLogTransfer:input_type -> assetwalletrpc.PublishAndLogRequest - 13, // 24: assetwalletrpc.AssetWallet.NextInternalKey:input_type -> assetwalletrpc.NextInternalKeyRequest - 15, // 25: assetwalletrpc.AssetWallet.NextScriptKey:input_type -> assetwalletrpc.NextScriptKeyRequest - 17, // 26: assetwalletrpc.AssetWallet.QueryInternalKey:input_type -> assetwalletrpc.QueryInternalKeyRequest - 19, // 27: assetwalletrpc.AssetWallet.QueryScriptKey:input_type -> assetwalletrpc.QueryScriptKeyRequest - 21, // 28: assetwalletrpc.AssetWallet.ProveAssetOwnership:input_type -> assetwalletrpc.ProveAssetOwnershipRequest - 23, // 29: assetwalletrpc.AssetWallet.VerifyAssetOwnership:input_type -> assetwalletrpc.VerifyAssetOwnershipRequest - 25, // 30: assetwalletrpc.AssetWallet.RemoveUTXOLease:input_type -> assetwalletrpc.RemoveUTXOLeaseRequest - 27, // 31: assetwalletrpc.AssetWallet.DeclareScriptKey:input_type -> assetwalletrpc.DeclareScriptKeyRequest - 29, // 32: assetwalletrpc.AssetWallet.ExportAssetWalletBackup:input_type -> assetwalletrpc.ExportAssetWalletBackupRequest - 31, // 33: assetwalletrpc.AssetWallet.ImportAssetsFromBackup:input_type -> assetwalletrpc.ImportAssetsFromBackupRequest - 4, // 34: assetwalletrpc.AssetWallet.FundVirtualPsbt:output_type -> assetwalletrpc.FundVirtualPsbtResponse - 8, // 35: assetwalletrpc.AssetWallet.SignVirtualPsbt:output_type -> assetwalletrpc.SignVirtualPsbtResponse - 38, // 36: assetwalletrpc.AssetWallet.AnchorVirtualPsbts:output_type -> taprpc.SendAssetResponse - 11, // 37: assetwalletrpc.AssetWallet.CommitVirtualPsbts:output_type -> assetwalletrpc.CommitVirtualPsbtsResponse - 38, // 38: assetwalletrpc.AssetWallet.PublishAndLogTransfer:output_type -> taprpc.SendAssetResponse - 14, // 39: assetwalletrpc.AssetWallet.NextInternalKey:output_type -> assetwalletrpc.NextInternalKeyResponse - 16, // 40: assetwalletrpc.AssetWallet.NextScriptKey:output_type -> assetwalletrpc.NextScriptKeyResponse - 18, // 41: assetwalletrpc.AssetWallet.QueryInternalKey:output_type -> assetwalletrpc.QueryInternalKeyResponse - 20, // 42: assetwalletrpc.AssetWallet.QueryScriptKey:output_type -> assetwalletrpc.QueryScriptKeyResponse - 22, // 43: assetwalletrpc.AssetWallet.ProveAssetOwnership:output_type -> assetwalletrpc.ProveAssetOwnershipResponse - 24, // 44: assetwalletrpc.AssetWallet.VerifyAssetOwnership:output_type -> assetwalletrpc.VerifyAssetOwnershipResponse - 26, // 45: assetwalletrpc.AssetWallet.RemoveUTXOLease:output_type -> assetwalletrpc.RemoveUTXOLeaseResponse - 28, // 46: assetwalletrpc.AssetWallet.DeclareScriptKey:output_type -> assetwalletrpc.DeclareScriptKeyResponse - 30, // 47: assetwalletrpc.AssetWallet.ExportAssetWalletBackup:output_type -> assetwalletrpc.ExportAssetWalletBackupResponse - 32, // 48: assetwalletrpc.AssetWallet.ImportAssetsFromBackup:output_type -> assetwalletrpc.ImportAssetsFromBackupResponse - 34, // [34:49] is the sub-list for method output_type - 19, // [19:34] is the sub-list for method input_type - 19, // [19:19] is the sub-list for extension type_name - 19, // [19:19] is the sub-list for extension extendee - 0, // [0:19] is the sub-list for field type_name + 38, // 7: assetwalletrpc.CommitVirtualPsbtsResponse.lnd_locked_utxos:type_name -> taprpc.OutPoint + 2, // 8: assetwalletrpc.GetCommitVirtualPsbtsStatusResponse.status:type_name -> assetwalletrpc.CommitVirtualPsbtsStatus + 38, // 9: assetwalletrpc.GetCommitVirtualPsbtsStatusResponse.lnd_locked_utxos:type_name -> taprpc.OutPoint + 38, // 10: assetwalletrpc.PublishAndLogRequest.lnd_locked_utxos:type_name -> taprpc.OutPoint + 39, // 11: assetwalletrpc.NextInternalKeyResponse.internal_key:type_name -> taprpc.KeyDescriptor + 40, // 12: assetwalletrpc.NextScriptKeyResponse.script_key:type_name -> taprpc.ScriptKey + 39, // 13: assetwalletrpc.QueryInternalKeyResponse.internal_key:type_name -> taprpc.KeyDescriptor + 40, // 14: assetwalletrpc.QueryScriptKeyResponse.script_key:type_name -> taprpc.ScriptKey + 38, // 15: assetwalletrpc.ProveAssetOwnershipRequest.outpoint:type_name -> taprpc.OutPoint + 38, // 16: assetwalletrpc.VerifyAssetOwnershipResponse.outpoint:type_name -> taprpc.OutPoint + 38, // 17: assetwalletrpc.RemoveUTXOLeaseRequest.outpoint:type_name -> taprpc.OutPoint + 40, // 18: assetwalletrpc.DeclareScriptKeyRequest.script_key:type_name -> taprpc.ScriptKey + 40, // 19: assetwalletrpc.DeclareScriptKeyResponse.script_key:type_name -> taprpc.ScriptKey + 3, // 20: assetwalletrpc.ExportAssetWalletBackupRequest.mode:type_name -> assetwalletrpc.BackupMode + 4, // 21: assetwalletrpc.AssetWallet.FundVirtualPsbt:input_type -> assetwalletrpc.FundVirtualPsbtRequest + 8, // 22: assetwalletrpc.AssetWallet.SignVirtualPsbt:input_type -> assetwalletrpc.SignVirtualPsbtRequest + 10, // 23: assetwalletrpc.AssetWallet.AnchorVirtualPsbts:input_type -> assetwalletrpc.AnchorVirtualPsbtsRequest + 11, // 24: assetwalletrpc.AssetWallet.CommitVirtualPsbts:input_type -> assetwalletrpc.CommitVirtualPsbtsRequest + 13, // 25: assetwalletrpc.AssetWallet.GetCommitVirtualPsbtsStatus:input_type -> assetwalletrpc.GetCommitVirtualPsbtsStatusRequest + 15, // 26: assetwalletrpc.AssetWallet.PublishAndLogTransfer:input_type -> assetwalletrpc.PublishAndLogRequest + 16, // 27: assetwalletrpc.AssetWallet.NextInternalKey:input_type -> assetwalletrpc.NextInternalKeyRequest + 18, // 28: assetwalletrpc.AssetWallet.NextScriptKey:input_type -> assetwalletrpc.NextScriptKeyRequest + 20, // 29: assetwalletrpc.AssetWallet.QueryInternalKey:input_type -> assetwalletrpc.QueryInternalKeyRequest + 22, // 30: assetwalletrpc.AssetWallet.QueryScriptKey:input_type -> assetwalletrpc.QueryScriptKeyRequest + 24, // 31: assetwalletrpc.AssetWallet.ProveAssetOwnership:input_type -> assetwalletrpc.ProveAssetOwnershipRequest + 26, // 32: assetwalletrpc.AssetWallet.VerifyAssetOwnership:input_type -> assetwalletrpc.VerifyAssetOwnershipRequest + 28, // 33: assetwalletrpc.AssetWallet.RemoveUTXOLease:input_type -> assetwalletrpc.RemoveUTXOLeaseRequest + 30, // 34: assetwalletrpc.AssetWallet.DeclareScriptKey:input_type -> assetwalletrpc.DeclareScriptKeyRequest + 32, // 35: assetwalletrpc.AssetWallet.ExportAssetWalletBackup:input_type -> assetwalletrpc.ExportAssetWalletBackupRequest + 34, // 36: assetwalletrpc.AssetWallet.ImportAssetsFromBackup:input_type -> assetwalletrpc.ImportAssetsFromBackupRequest + 5, // 37: assetwalletrpc.AssetWallet.FundVirtualPsbt:output_type -> assetwalletrpc.FundVirtualPsbtResponse + 9, // 38: assetwalletrpc.AssetWallet.SignVirtualPsbt:output_type -> assetwalletrpc.SignVirtualPsbtResponse + 41, // 39: assetwalletrpc.AssetWallet.AnchorVirtualPsbts:output_type -> taprpc.SendAssetResponse + 12, // 40: assetwalletrpc.AssetWallet.CommitVirtualPsbts:output_type -> assetwalletrpc.CommitVirtualPsbtsResponse + 14, // 41: assetwalletrpc.AssetWallet.GetCommitVirtualPsbtsStatus:output_type -> assetwalletrpc.GetCommitVirtualPsbtsStatusResponse + 41, // 42: assetwalletrpc.AssetWallet.PublishAndLogTransfer:output_type -> taprpc.SendAssetResponse + 17, // 43: assetwalletrpc.AssetWallet.NextInternalKey:output_type -> assetwalletrpc.NextInternalKeyResponse + 19, // 44: assetwalletrpc.AssetWallet.NextScriptKey:output_type -> assetwalletrpc.NextScriptKeyResponse + 21, // 45: assetwalletrpc.AssetWallet.QueryInternalKey:output_type -> assetwalletrpc.QueryInternalKeyResponse + 23, // 46: assetwalletrpc.AssetWallet.QueryScriptKey:output_type -> assetwalletrpc.QueryScriptKeyResponse + 25, // 47: assetwalletrpc.AssetWallet.ProveAssetOwnership:output_type -> assetwalletrpc.ProveAssetOwnershipResponse + 27, // 48: assetwalletrpc.AssetWallet.VerifyAssetOwnership:output_type -> assetwalletrpc.VerifyAssetOwnershipResponse + 29, // 49: assetwalletrpc.AssetWallet.RemoveUTXOLease:output_type -> assetwalletrpc.RemoveUTXOLeaseResponse + 31, // 50: assetwalletrpc.AssetWallet.DeclareScriptKey:output_type -> assetwalletrpc.DeclareScriptKeyResponse + 33, // 51: assetwalletrpc.AssetWallet.ExportAssetWalletBackup:output_type -> assetwalletrpc.ExportAssetWalletBackupResponse + 35, // 52: assetwalletrpc.AssetWallet.ImportAssetsFromBackup:output_type -> assetwalletrpc.ImportAssetsFromBackupResponse + 37, // [37:53] is the sub-list for method output_type + 21, // [21:37] is the sub-list for method input_type + 21, // [21:21] is the sub-list for extension type_name + 21, // [21:21] is the sub-list for extension extendee + 0, // [0:21] is the sub-list for field type_name } func init() { file_assetwalletrpc_assetwallet_proto_init() } @@ -2361,8 +2595,8 @@ func file_assetwalletrpc_assetwallet_proto_init() { File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_assetwalletrpc_assetwallet_proto_rawDesc), len(file_assetwalletrpc_assetwallet_proto_rawDesc)), - NumEnums: 3, - NumMessages: 31, + NumEnums: 4, + NumMessages: 33, NumExtensions: 0, NumServices: 1, }, diff --git a/taprpc/assetwalletrpc/assetwallet.pb.gw.go b/taprpc/assetwalletrpc/assetwallet.pb.gw.go index 088602a4fa..98d0399ce0 100644 --- a/taprpc/assetwalletrpc/assetwallet.pb.gw.go +++ b/taprpc/assetwalletrpc/assetwallet.pb.gw.go @@ -10,6 +10,7 @@ package assetwalletrpc import ( "context" + "errors" "io" "net/http" @@ -24,470 +25,485 @@ import ( ) // Suppress "imported and not used" errors -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray -var _ = metadata.Join +var ( + _ codes.Code + _ io.Reader + _ status.Status + _ = errors.New + _ = runtime.String + _ = utilities.NewDoubleArray + _ = metadata.Join +) func request_AssetWallet_FundVirtualPsbt_0(ctx context.Context, marshaler runtime.Marshaler, client AssetWalletClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq FundVirtualPsbtRequest - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq FundVirtualPsbtRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - + if req.Body != nil { + _, _ = io.Copy(io.Discard, req.Body) + } msg, err := client.FundVirtualPsbt(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err - } func local_request_AssetWallet_FundVirtualPsbt_0(ctx context.Context, marshaler runtime.Marshaler, server AssetWalletServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq FundVirtualPsbtRequest - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq FundVirtualPsbtRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - msg, err := server.FundVirtualPsbt(ctx, &protoReq) return msg, metadata, err - } func request_AssetWallet_SignVirtualPsbt_0(ctx context.Context, marshaler runtime.Marshaler, client AssetWalletClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq SignVirtualPsbtRequest - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq SignVirtualPsbtRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - + if req.Body != nil { + _, _ = io.Copy(io.Discard, req.Body) + } msg, err := client.SignVirtualPsbt(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err - } func local_request_AssetWallet_SignVirtualPsbt_0(ctx context.Context, marshaler runtime.Marshaler, server AssetWalletServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq SignVirtualPsbtRequest - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq SignVirtualPsbtRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - msg, err := server.SignVirtualPsbt(ctx, &protoReq) return msg, metadata, err - } func request_AssetWallet_AnchorVirtualPsbts_0(ctx context.Context, marshaler runtime.Marshaler, client AssetWalletClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq AnchorVirtualPsbtsRequest - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq AnchorVirtualPsbtsRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - + if req.Body != nil { + _, _ = io.Copy(io.Discard, req.Body) + } msg, err := client.AnchorVirtualPsbts(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err - } func local_request_AssetWallet_AnchorVirtualPsbts_0(ctx context.Context, marshaler runtime.Marshaler, server AssetWalletServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq AnchorVirtualPsbtsRequest - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq AnchorVirtualPsbtsRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - msg, err := server.AnchorVirtualPsbts(ctx, &protoReq) return msg, metadata, err - } func request_AssetWallet_CommitVirtualPsbts_0(ctx context.Context, marshaler runtime.Marshaler, client AssetWalletClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq CommitVirtualPsbtsRequest - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq CommitVirtualPsbtsRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - + if req.Body != nil { + _, _ = io.Copy(io.Discard, req.Body) + } msg, err := client.CommitVirtualPsbts(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err - } func local_request_AssetWallet_CommitVirtualPsbts_0(ctx context.Context, marshaler runtime.Marshaler, server AssetWalletServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq CommitVirtualPsbtsRequest - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq CommitVirtualPsbtsRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - msg, err := server.CommitVirtualPsbts(ctx, &protoReq) return msg, metadata, err - } -func request_AssetWallet_PublishAndLogTransfer_0(ctx context.Context, marshaler runtime.Marshaler, client AssetWalletClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq PublishAndLogRequest - var metadata runtime.ServerMetadata +func request_AssetWallet_GetCommitVirtualPsbtsStatus_0(ctx context.Context, marshaler runtime.Marshaler, client AssetWalletClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var ( + protoReq GetCommitVirtualPsbtsStatusRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if req.Body != nil { + _, _ = io.Copy(io.Discard, req.Body) + } + msg, err := client.GetCommitVirtualPsbtsStatus(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err +} - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { +func local_request_AssetWallet_GetCommitVirtualPsbtsStatus_0(ctx context.Context, marshaler runtime.Marshaler, server AssetWalletServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var ( + protoReq GetCommitVirtualPsbtsStatusRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } + msg, err := server.GetCommitVirtualPsbtsStatus(ctx, &protoReq) + return msg, metadata, err +} +func request_AssetWallet_PublishAndLogTransfer_0(ctx context.Context, marshaler runtime.Marshaler, client AssetWalletClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var ( + protoReq PublishAndLogRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if req.Body != nil { + _, _ = io.Copy(io.Discard, req.Body) + } msg, err := client.PublishAndLogTransfer(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err - } func local_request_AssetWallet_PublishAndLogTransfer_0(ctx context.Context, marshaler runtime.Marshaler, server AssetWalletServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq PublishAndLogRequest - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq PublishAndLogRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - msg, err := server.PublishAndLogTransfer(ctx, &protoReq) return msg, metadata, err - } func request_AssetWallet_NextInternalKey_0(ctx context.Context, marshaler runtime.Marshaler, client AssetWalletClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq NextInternalKeyRequest - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq NextInternalKeyRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - + if req.Body != nil { + _, _ = io.Copy(io.Discard, req.Body) + } msg, err := client.NextInternalKey(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err - } func local_request_AssetWallet_NextInternalKey_0(ctx context.Context, marshaler runtime.Marshaler, server AssetWalletServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq NextInternalKeyRequest - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq NextInternalKeyRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - msg, err := server.NextInternalKey(ctx, &protoReq) return msg, metadata, err - } func request_AssetWallet_NextScriptKey_0(ctx context.Context, marshaler runtime.Marshaler, client AssetWalletClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq NextScriptKeyRequest - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq NextScriptKeyRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - + if req.Body != nil { + _, _ = io.Copy(io.Discard, req.Body) + } msg, err := client.NextScriptKey(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err - } func local_request_AssetWallet_NextScriptKey_0(ctx context.Context, marshaler runtime.Marshaler, server AssetWalletServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq NextScriptKeyRequest - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq NextScriptKeyRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - msg, err := server.NextScriptKey(ctx, &protoReq) return msg, metadata, err - } func request_AssetWallet_QueryInternalKey_0(ctx context.Context, marshaler runtime.Marshaler, client AssetWalletClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryInternalKeyRequest - var metadata runtime.ServerMetadata - var ( - val string - ok bool - err error - _ = err + protoReq QueryInternalKeyRequest + metadata runtime.ServerMetadata + err error ) - - val, ok = pathParams["internal_key"] + if req.Body != nil { + _, _ = io.Copy(io.Discard, req.Body) + } + val, ok := pathParams["internal_key"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "internal_key") } - protoReq.InternalKey, err = runtime.Bytes(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "internal_key", err) } - msg, err := client.QueryInternalKey(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err - } func local_request_AssetWallet_QueryInternalKey_0(ctx context.Context, marshaler runtime.Marshaler, server AssetWalletServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryInternalKeyRequest - var metadata runtime.ServerMetadata - var ( - val string - ok bool - err error - _ = err + protoReq QueryInternalKeyRequest + metadata runtime.ServerMetadata + err error ) - - val, ok = pathParams["internal_key"] + val, ok := pathParams["internal_key"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "internal_key") } - protoReq.InternalKey, err = runtime.Bytes(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "internal_key", err) } - msg, err := server.QueryInternalKey(ctx, &protoReq) return msg, metadata, err - } func request_AssetWallet_QueryScriptKey_0(ctx context.Context, marshaler runtime.Marshaler, client AssetWalletClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryScriptKeyRequest - var metadata runtime.ServerMetadata - var ( - val string - ok bool - err error - _ = err + protoReq QueryScriptKeyRequest + metadata runtime.ServerMetadata + err error ) - - val, ok = pathParams["tweaked_script_key"] + if req.Body != nil { + _, _ = io.Copy(io.Discard, req.Body) + } + val, ok := pathParams["tweaked_script_key"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "tweaked_script_key") } - protoReq.TweakedScriptKey, err = runtime.Bytes(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "tweaked_script_key", err) } - msg, err := client.QueryScriptKey(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err - } func local_request_AssetWallet_QueryScriptKey_0(ctx context.Context, marshaler runtime.Marshaler, server AssetWalletServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryScriptKeyRequest - var metadata runtime.ServerMetadata - var ( - val string - ok bool - err error - _ = err + protoReq QueryScriptKeyRequest + metadata runtime.ServerMetadata + err error ) - - val, ok = pathParams["tweaked_script_key"] + val, ok := pathParams["tweaked_script_key"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "tweaked_script_key") } - protoReq.TweakedScriptKey, err = runtime.Bytes(val) if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "tweaked_script_key", err) } - msg, err := server.QueryScriptKey(ctx, &protoReq) return msg, metadata, err - } func request_AssetWallet_ProveAssetOwnership_0(ctx context.Context, marshaler runtime.Marshaler, client AssetWalletClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq ProveAssetOwnershipRequest - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq ProveAssetOwnershipRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - + if req.Body != nil { + _, _ = io.Copy(io.Discard, req.Body) + } msg, err := client.ProveAssetOwnership(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err - } func local_request_AssetWallet_ProveAssetOwnership_0(ctx context.Context, marshaler runtime.Marshaler, server AssetWalletServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq ProveAssetOwnershipRequest - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq ProveAssetOwnershipRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - msg, err := server.ProveAssetOwnership(ctx, &protoReq) return msg, metadata, err - } func request_AssetWallet_VerifyAssetOwnership_0(ctx context.Context, marshaler runtime.Marshaler, client AssetWalletClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq VerifyAssetOwnershipRequest - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq VerifyAssetOwnershipRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - + if req.Body != nil { + _, _ = io.Copy(io.Discard, req.Body) + } msg, err := client.VerifyAssetOwnership(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err - } func local_request_AssetWallet_VerifyAssetOwnership_0(ctx context.Context, marshaler runtime.Marshaler, server AssetWalletServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq VerifyAssetOwnershipRequest - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq VerifyAssetOwnershipRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - msg, err := server.VerifyAssetOwnership(ctx, &protoReq) return msg, metadata, err - } func request_AssetWallet_RemoveUTXOLease_0(ctx context.Context, marshaler runtime.Marshaler, client AssetWalletClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq RemoveUTXOLeaseRequest - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq RemoveUTXOLeaseRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - + if req.Body != nil { + _, _ = io.Copy(io.Discard, req.Body) + } msg, err := client.RemoveUTXOLease(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err - } func local_request_AssetWallet_RemoveUTXOLease_0(ctx context.Context, marshaler runtime.Marshaler, server AssetWalletServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq RemoveUTXOLeaseRequest - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq RemoveUTXOLeaseRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - msg, err := server.RemoveUTXOLease(ctx, &protoReq) return msg, metadata, err - } func request_AssetWallet_DeclareScriptKey_0(ctx context.Context, marshaler runtime.Marshaler, client AssetWalletClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq DeclareScriptKeyRequest - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq DeclareScriptKeyRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - + if req.Body != nil { + _, _ = io.Copy(io.Discard, req.Body) + } msg, err := client.DeclareScriptKey(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err - } func local_request_AssetWallet_DeclareScriptKey_0(ctx context.Context, marshaler runtime.Marshaler, server AssetWalletServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq DeclareScriptKeyRequest - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq DeclareScriptKeyRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - msg, err := server.DeclareScriptKey(ctx, &protoReq) return msg, metadata, err - } func request_AssetWallet_ExportAssetWalletBackup_0(ctx context.Context, marshaler runtime.Marshaler, client AssetWalletClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq ExportAssetWalletBackupRequest - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq ExportAssetWalletBackupRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - + if req.Body != nil { + _, _ = io.Copy(io.Discard, req.Body) + } msg, err := client.ExportAssetWalletBackup(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err - } func local_request_AssetWallet_ExportAssetWalletBackup_0(ctx context.Context, marshaler runtime.Marshaler, server AssetWalletServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq ExportAssetWalletBackupRequest - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq ExportAssetWalletBackupRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - msg, err := server.ExportAssetWalletBackup(ctx, &protoReq) return msg, metadata, err - } func request_AssetWallet_ImportAssetsFromBackup_0(ctx context.Context, marshaler runtime.Marshaler, client AssetWalletClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq ImportAssetsFromBackupRequest - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq ImportAssetsFromBackupRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - + if req.Body != nil { + _, _ = io.Copy(io.Discard, req.Body) + } msg, err := client.ImportAssetsFromBackup(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err - } func local_request_AssetWallet_ImportAssetsFromBackup_0(ctx context.Context, marshaler runtime.Marshaler, server AssetWalletServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq ImportAssetsFromBackupRequest - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq ImportAssetsFromBackupRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - msg, err := server.ImportAssetsFromBackup(ctx, &protoReq) return msg, metadata, err - } // RegisterAssetWalletHandlerServer registers the http handlers for service AssetWallet to "mux". // UnaryRPC :call AssetWalletServer directly. // StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. // Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterAssetWalletHandlerFromEndpoint instead. +// GRPC interceptors will not work for this type of registration. To use interceptors, you must use the "runtime.WithMiddlewares" option in the "runtime.NewServeMux" call. func RegisterAssetWalletHandlerServer(ctx context.Context, mux *runtime.ServeMux, server AssetWalletServer) error { - - mux.Handle("POST", pattern_AssetWallet_FundVirtualPsbt_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_AssetWallet_FundVirtualPsbt_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/FundVirtualPsbt", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/virtual-psbt/fund")) + annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/FundVirtualPsbt", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/virtual-psbt/fund")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -499,20 +515,15 @@ func RegisterAssetWalletHandlerServer(ctx context.Context, mux *runtime.ServeMux runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_AssetWallet_FundVirtualPsbt_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("POST", pattern_AssetWallet_SignVirtualPsbt_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_AssetWallet_SignVirtualPsbt_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/SignVirtualPsbt", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/virtual-psbt/sign")) + annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/SignVirtualPsbt", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/virtual-psbt/sign")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -524,20 +535,15 @@ func RegisterAssetWalletHandlerServer(ctx context.Context, mux *runtime.ServeMux runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_AssetWallet_SignVirtualPsbt_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("POST", pattern_AssetWallet_AnchorVirtualPsbts_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_AssetWallet_AnchorVirtualPsbts_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/AnchorVirtualPsbts", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/virtual-psbt/anchor")) + annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/AnchorVirtualPsbts", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/virtual-psbt/anchor")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -549,20 +555,15 @@ func RegisterAssetWalletHandlerServer(ctx context.Context, mux *runtime.ServeMux runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_AssetWallet_AnchorVirtualPsbts_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("POST", pattern_AssetWallet_CommitVirtualPsbts_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_AssetWallet_CommitVirtualPsbts_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/CommitVirtualPsbts", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/virtual-psbt/commit")) + annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/CommitVirtualPsbts", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/virtual-psbt/commit")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -574,20 +575,35 @@ func RegisterAssetWalletHandlerServer(ctx context.Context, mux *runtime.ServeMux runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_AssetWallet_CommitVirtualPsbts_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("POST", pattern_AssetWallet_PublishAndLogTransfer_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_AssetWallet_GetCommitVirtualPsbtsStatus_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/GetCommitVirtualPsbtsStatus", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/virtual-psbt/commit/status")) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_AssetWallet_GetCommitVirtualPsbtsStatus_0(annotatedContext, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) + if err != nil { + runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) + return + } + forward_AssetWallet_GetCommitVirtualPsbtsStatus_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) + mux.Handle(http.MethodPost, pattern_AssetWallet_PublishAndLogTransfer_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/PublishAndLogTransfer", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/virtual-psbt/log-transfer")) + annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/PublishAndLogTransfer", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/virtual-psbt/log-transfer")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -599,20 +615,15 @@ func RegisterAssetWalletHandlerServer(ctx context.Context, mux *runtime.ServeMux runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_AssetWallet_PublishAndLogTransfer_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("POST", pattern_AssetWallet_NextInternalKey_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_AssetWallet_NextInternalKey_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/NextInternalKey", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/internal-key/next")) + annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/NextInternalKey", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/internal-key/next")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -624,20 +635,15 @@ func RegisterAssetWalletHandlerServer(ctx context.Context, mux *runtime.ServeMux runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_AssetWallet_NextInternalKey_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("POST", pattern_AssetWallet_NextScriptKey_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_AssetWallet_NextScriptKey_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/NextScriptKey", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/script-key/next")) + annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/NextScriptKey", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/script-key/next")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -649,20 +655,15 @@ func RegisterAssetWalletHandlerServer(ctx context.Context, mux *runtime.ServeMux runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_AssetWallet_NextScriptKey_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_AssetWallet_QueryInternalKey_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodGet, pattern_AssetWallet_QueryInternalKey_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/QueryInternalKey", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/internal-key/{internal_key}")) + annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/QueryInternalKey", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/internal-key/{internal_key}")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -674,20 +675,15 @@ func RegisterAssetWalletHandlerServer(ctx context.Context, mux *runtime.ServeMux runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_AssetWallet_QueryInternalKey_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_AssetWallet_QueryScriptKey_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodGet, pattern_AssetWallet_QueryScriptKey_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/QueryScriptKey", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/script-key/{tweaked_script_key}")) + annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/QueryScriptKey", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/script-key/{tweaked_script_key}")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -699,20 +695,15 @@ func RegisterAssetWalletHandlerServer(ctx context.Context, mux *runtime.ServeMux runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_AssetWallet_QueryScriptKey_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("POST", pattern_AssetWallet_ProveAssetOwnership_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_AssetWallet_ProveAssetOwnership_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/ProveAssetOwnership", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/ownership/prove")) + annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/ProveAssetOwnership", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/ownership/prove")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -724,20 +715,15 @@ func RegisterAssetWalletHandlerServer(ctx context.Context, mux *runtime.ServeMux runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_AssetWallet_ProveAssetOwnership_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("POST", pattern_AssetWallet_VerifyAssetOwnership_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_AssetWallet_VerifyAssetOwnership_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/VerifyAssetOwnership", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/ownership/verify")) + annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/VerifyAssetOwnership", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/ownership/verify")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -749,20 +735,15 @@ func RegisterAssetWalletHandlerServer(ctx context.Context, mux *runtime.ServeMux runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_AssetWallet_VerifyAssetOwnership_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("POST", pattern_AssetWallet_RemoveUTXOLease_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_AssetWallet_RemoveUTXOLease_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/RemoveUTXOLease", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/utxo-lease/delete")) + annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/RemoveUTXOLease", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/utxo-lease/delete")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -774,20 +755,15 @@ func RegisterAssetWalletHandlerServer(ctx context.Context, mux *runtime.ServeMux runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_AssetWallet_RemoveUTXOLease_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("POST", pattern_AssetWallet_DeclareScriptKey_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_AssetWallet_DeclareScriptKey_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/DeclareScriptKey", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/script-key/declare")) + annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/DeclareScriptKey", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/script-key/declare")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -799,20 +775,15 @@ func RegisterAssetWalletHandlerServer(ctx context.Context, mux *runtime.ServeMux runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_AssetWallet_DeclareScriptKey_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("POST", pattern_AssetWallet_ExportAssetWalletBackup_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_AssetWallet_ExportAssetWalletBackup_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/ExportAssetWalletBackup", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/backup/export")) + annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/ExportAssetWalletBackup", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/backup/export")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -824,20 +795,15 @@ func RegisterAssetWalletHandlerServer(ctx context.Context, mux *runtime.ServeMux runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_AssetWallet_ExportAssetWalletBackup_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("POST", pattern_AssetWallet_ImportAssetsFromBackup_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_AssetWallet_ImportAssetsFromBackup_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/ImportAssetsFromBackup", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/backup/import")) + annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/ImportAssetsFromBackup", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/backup/import")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -849,9 +815,7 @@ func RegisterAssetWalletHandlerServer(ctx context.Context, mux *runtime.ServeMux runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_AssetWallet_ImportAssetsFromBackup_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) return nil @@ -878,7 +842,6 @@ func RegisterAssetWalletHandlerFromEndpoint(ctx context.Context, mux *runtime.Se } }() }() - return RegisterAssetWalletHandler(ctx, mux, conn) } @@ -892,16 +855,13 @@ func RegisterAssetWalletHandler(ctx context.Context, mux *runtime.ServeMux, conn // to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "AssetWalletClient". // Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "AssetWalletClient" // doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "AssetWalletClient" to call the correct interceptors. +// "AssetWalletClient" to call the correct interceptors. This client ignores the HTTP middlewares. func RegisterAssetWalletHandlerClient(ctx context.Context, mux *runtime.ServeMux, client AssetWalletClient) error { - - mux.Handle("POST", pattern_AssetWallet_FundVirtualPsbt_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_AssetWallet_FundVirtualPsbt_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/FundVirtualPsbt", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/virtual-psbt/fund")) + annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/FundVirtualPsbt", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/virtual-psbt/fund")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -912,18 +872,13 @@ func RegisterAssetWalletHandlerClient(ctx context.Context, mux *runtime.ServeMux runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_AssetWallet_FundVirtualPsbt_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("POST", pattern_AssetWallet_SignVirtualPsbt_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_AssetWallet_SignVirtualPsbt_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/SignVirtualPsbt", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/virtual-psbt/sign")) + annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/SignVirtualPsbt", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/virtual-psbt/sign")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -934,18 +889,13 @@ func RegisterAssetWalletHandlerClient(ctx context.Context, mux *runtime.ServeMux runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_AssetWallet_SignVirtualPsbt_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("POST", pattern_AssetWallet_AnchorVirtualPsbts_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_AssetWallet_AnchorVirtualPsbts_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/AnchorVirtualPsbts", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/virtual-psbt/anchor")) + annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/AnchorVirtualPsbts", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/virtual-psbt/anchor")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -956,18 +906,13 @@ func RegisterAssetWalletHandlerClient(ctx context.Context, mux *runtime.ServeMux runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_AssetWallet_AnchorVirtualPsbts_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("POST", pattern_AssetWallet_CommitVirtualPsbts_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_AssetWallet_CommitVirtualPsbts_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/CommitVirtualPsbts", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/virtual-psbt/commit")) + annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/CommitVirtualPsbts", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/virtual-psbt/commit")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -978,18 +923,30 @@ func RegisterAssetWalletHandlerClient(ctx context.Context, mux *runtime.ServeMux runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_AssetWallet_CommitVirtualPsbts_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("POST", pattern_AssetWallet_PublishAndLogTransfer_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_AssetWallet_GetCommitVirtualPsbtsStatus_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/GetCommitVirtualPsbtsStatus", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/virtual-psbt/commit/status")) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_AssetWallet_GetCommitVirtualPsbtsStatus_0(annotatedContext, inboundMarshaler, client, req, pathParams) + annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) + if err != nil { + runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) + return + } + forward_AssetWallet_GetCommitVirtualPsbtsStatus_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) + mux.Handle(http.MethodPost, pattern_AssetWallet_PublishAndLogTransfer_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/PublishAndLogTransfer", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/virtual-psbt/log-transfer")) + annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/PublishAndLogTransfer", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/virtual-psbt/log-transfer")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -1000,18 +957,13 @@ func RegisterAssetWalletHandlerClient(ctx context.Context, mux *runtime.ServeMux runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_AssetWallet_PublishAndLogTransfer_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("POST", pattern_AssetWallet_NextInternalKey_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_AssetWallet_NextInternalKey_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/NextInternalKey", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/internal-key/next")) + annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/NextInternalKey", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/internal-key/next")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -1022,18 +974,13 @@ func RegisterAssetWalletHandlerClient(ctx context.Context, mux *runtime.ServeMux runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_AssetWallet_NextInternalKey_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("POST", pattern_AssetWallet_NextScriptKey_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_AssetWallet_NextScriptKey_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/NextScriptKey", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/script-key/next")) + annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/NextScriptKey", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/script-key/next")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -1044,18 +991,13 @@ func RegisterAssetWalletHandlerClient(ctx context.Context, mux *runtime.ServeMux runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_AssetWallet_NextScriptKey_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_AssetWallet_QueryInternalKey_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodGet, pattern_AssetWallet_QueryInternalKey_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/QueryInternalKey", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/internal-key/{internal_key}")) + annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/QueryInternalKey", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/internal-key/{internal_key}")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -1066,18 +1008,13 @@ func RegisterAssetWalletHandlerClient(ctx context.Context, mux *runtime.ServeMux runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_AssetWallet_QueryInternalKey_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_AssetWallet_QueryScriptKey_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodGet, pattern_AssetWallet_QueryScriptKey_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/QueryScriptKey", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/script-key/{tweaked_script_key}")) + annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/QueryScriptKey", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/script-key/{tweaked_script_key}")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -1088,18 +1025,13 @@ func RegisterAssetWalletHandlerClient(ctx context.Context, mux *runtime.ServeMux runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_AssetWallet_QueryScriptKey_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("POST", pattern_AssetWallet_ProveAssetOwnership_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_AssetWallet_ProveAssetOwnership_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/ProveAssetOwnership", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/ownership/prove")) + annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/ProveAssetOwnership", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/ownership/prove")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -1110,18 +1042,13 @@ func RegisterAssetWalletHandlerClient(ctx context.Context, mux *runtime.ServeMux runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_AssetWallet_ProveAssetOwnership_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("POST", pattern_AssetWallet_VerifyAssetOwnership_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_AssetWallet_VerifyAssetOwnership_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/VerifyAssetOwnership", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/ownership/verify")) + annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/VerifyAssetOwnership", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/ownership/verify")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -1132,18 +1059,13 @@ func RegisterAssetWalletHandlerClient(ctx context.Context, mux *runtime.ServeMux runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_AssetWallet_VerifyAssetOwnership_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("POST", pattern_AssetWallet_RemoveUTXOLease_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_AssetWallet_RemoveUTXOLease_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/RemoveUTXOLease", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/utxo-lease/delete")) + annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/RemoveUTXOLease", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/utxo-lease/delete")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -1154,18 +1076,13 @@ func RegisterAssetWalletHandlerClient(ctx context.Context, mux *runtime.ServeMux runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_AssetWallet_RemoveUTXOLease_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("POST", pattern_AssetWallet_DeclareScriptKey_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_AssetWallet_DeclareScriptKey_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/DeclareScriptKey", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/script-key/declare")) + annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/DeclareScriptKey", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/script-key/declare")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -1176,18 +1093,13 @@ func RegisterAssetWalletHandlerClient(ctx context.Context, mux *runtime.ServeMux runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_AssetWallet_DeclareScriptKey_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("POST", pattern_AssetWallet_ExportAssetWalletBackup_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_AssetWallet_ExportAssetWalletBackup_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/ExportAssetWalletBackup", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/backup/export")) + annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/ExportAssetWalletBackup", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/backup/export")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -1198,18 +1110,13 @@ func RegisterAssetWalletHandlerClient(ctx context.Context, mux *runtime.ServeMux runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_AssetWallet_ExportAssetWalletBackup_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("POST", pattern_AssetWallet_ImportAssetsFromBackup_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_AssetWallet_ImportAssetsFromBackup_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/ImportAssetsFromBackup", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/backup/import")) + annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/assetwalletrpc.AssetWallet/ImportAssetsFromBackup", runtime.WithHTTPPathPattern("/v1/taproot-assets/wallet/backup/import")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -1220,74 +1127,45 @@ func RegisterAssetWalletHandlerClient(ctx context.Context, mux *runtime.ServeMux runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_AssetWallet_ImportAssetsFromBackup_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - return nil } var ( - pattern_AssetWallet_FundVirtualPsbt_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "taproot-assets", "wallet", "virtual-psbt", "fund"}, "")) - - pattern_AssetWallet_SignVirtualPsbt_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "taproot-assets", "wallet", "virtual-psbt", "sign"}, "")) - - pattern_AssetWallet_AnchorVirtualPsbts_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "taproot-assets", "wallet", "virtual-psbt", "anchor"}, "")) - - pattern_AssetWallet_CommitVirtualPsbts_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "taproot-assets", "wallet", "virtual-psbt", "commit"}, "")) - - pattern_AssetWallet_PublishAndLogTransfer_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "taproot-assets", "wallet", "virtual-psbt", "log-transfer"}, "")) - - pattern_AssetWallet_NextInternalKey_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "taproot-assets", "wallet", "internal-key", "next"}, "")) - - pattern_AssetWallet_NextScriptKey_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "taproot-assets", "wallet", "script-key", "next"}, "")) - - pattern_AssetWallet_QueryInternalKey_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"v1", "taproot-assets", "wallet", "internal-key", "internal_key"}, "")) - - pattern_AssetWallet_QueryScriptKey_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"v1", "taproot-assets", "wallet", "script-key", "tweaked_script_key"}, "")) - - pattern_AssetWallet_ProveAssetOwnership_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "taproot-assets", "wallet", "ownership", "prove"}, "")) - - pattern_AssetWallet_VerifyAssetOwnership_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "taproot-assets", "wallet", "ownership", "verify"}, "")) - - pattern_AssetWallet_RemoveUTXOLease_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "taproot-assets", "wallet", "utxo-lease", "delete"}, "")) - - pattern_AssetWallet_DeclareScriptKey_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "taproot-assets", "wallet", "script-key", "declare"}, "")) - - pattern_AssetWallet_ExportAssetWalletBackup_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "taproot-assets", "wallet", "backup", "export"}, "")) - - pattern_AssetWallet_ImportAssetsFromBackup_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "taproot-assets", "wallet", "backup", "import"}, "")) + pattern_AssetWallet_FundVirtualPsbt_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "taproot-assets", "wallet", "virtual-psbt", "fund"}, "")) + pattern_AssetWallet_SignVirtualPsbt_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "taproot-assets", "wallet", "virtual-psbt", "sign"}, "")) + pattern_AssetWallet_AnchorVirtualPsbts_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "taproot-assets", "wallet", "virtual-psbt", "anchor"}, "")) + pattern_AssetWallet_CommitVirtualPsbts_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "taproot-assets", "wallet", "virtual-psbt", "commit"}, "")) + pattern_AssetWallet_GetCommitVirtualPsbtsStatus_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4, 2, 5}, []string{"v1", "taproot-assets", "wallet", "virtual-psbt", "commit", "status"}, "")) + pattern_AssetWallet_PublishAndLogTransfer_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "taproot-assets", "wallet", "virtual-psbt", "log-transfer"}, "")) + pattern_AssetWallet_NextInternalKey_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "taproot-assets", "wallet", "internal-key", "next"}, "")) + pattern_AssetWallet_NextScriptKey_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "taproot-assets", "wallet", "script-key", "next"}, "")) + pattern_AssetWallet_QueryInternalKey_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"v1", "taproot-assets", "wallet", "internal-key", "internal_key"}, "")) + pattern_AssetWallet_QueryScriptKey_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"v1", "taproot-assets", "wallet", "script-key", "tweaked_script_key"}, "")) + pattern_AssetWallet_ProveAssetOwnership_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "taproot-assets", "wallet", "ownership", "prove"}, "")) + pattern_AssetWallet_VerifyAssetOwnership_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "taproot-assets", "wallet", "ownership", "verify"}, "")) + pattern_AssetWallet_RemoveUTXOLease_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "taproot-assets", "wallet", "utxo-lease", "delete"}, "")) + pattern_AssetWallet_DeclareScriptKey_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "taproot-assets", "wallet", "script-key", "declare"}, "")) + pattern_AssetWallet_ExportAssetWalletBackup_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "taproot-assets", "wallet", "backup", "export"}, "")) + pattern_AssetWallet_ImportAssetsFromBackup_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "taproot-assets", "wallet", "backup", "import"}, "")) ) var ( - forward_AssetWallet_FundVirtualPsbt_0 = runtime.ForwardResponseMessage - - forward_AssetWallet_SignVirtualPsbt_0 = runtime.ForwardResponseMessage - - forward_AssetWallet_AnchorVirtualPsbts_0 = runtime.ForwardResponseMessage - - forward_AssetWallet_CommitVirtualPsbts_0 = runtime.ForwardResponseMessage - - forward_AssetWallet_PublishAndLogTransfer_0 = runtime.ForwardResponseMessage - - forward_AssetWallet_NextInternalKey_0 = runtime.ForwardResponseMessage - - forward_AssetWallet_NextScriptKey_0 = runtime.ForwardResponseMessage - - forward_AssetWallet_QueryInternalKey_0 = runtime.ForwardResponseMessage - - forward_AssetWallet_QueryScriptKey_0 = runtime.ForwardResponseMessage - - forward_AssetWallet_ProveAssetOwnership_0 = runtime.ForwardResponseMessage - - forward_AssetWallet_VerifyAssetOwnership_0 = runtime.ForwardResponseMessage - - forward_AssetWallet_RemoveUTXOLease_0 = runtime.ForwardResponseMessage - - forward_AssetWallet_DeclareScriptKey_0 = runtime.ForwardResponseMessage - - forward_AssetWallet_ExportAssetWalletBackup_0 = runtime.ForwardResponseMessage - - forward_AssetWallet_ImportAssetsFromBackup_0 = runtime.ForwardResponseMessage + forward_AssetWallet_FundVirtualPsbt_0 = runtime.ForwardResponseMessage + forward_AssetWallet_SignVirtualPsbt_0 = runtime.ForwardResponseMessage + forward_AssetWallet_AnchorVirtualPsbts_0 = runtime.ForwardResponseMessage + forward_AssetWallet_CommitVirtualPsbts_0 = runtime.ForwardResponseMessage + forward_AssetWallet_GetCommitVirtualPsbtsStatus_0 = runtime.ForwardResponseMessage + forward_AssetWallet_PublishAndLogTransfer_0 = runtime.ForwardResponseMessage + forward_AssetWallet_NextInternalKey_0 = runtime.ForwardResponseMessage + forward_AssetWallet_NextScriptKey_0 = runtime.ForwardResponseMessage + forward_AssetWallet_QueryInternalKey_0 = runtime.ForwardResponseMessage + forward_AssetWallet_QueryScriptKey_0 = runtime.ForwardResponseMessage + forward_AssetWallet_ProveAssetOwnership_0 = runtime.ForwardResponseMessage + forward_AssetWallet_VerifyAssetOwnership_0 = runtime.ForwardResponseMessage + forward_AssetWallet_RemoveUTXOLease_0 = runtime.ForwardResponseMessage + forward_AssetWallet_DeclareScriptKey_0 = runtime.ForwardResponseMessage + forward_AssetWallet_ExportAssetWalletBackup_0 = runtime.ForwardResponseMessage + forward_AssetWallet_ImportAssetsFromBackup_0 = runtime.ForwardResponseMessage ) diff --git a/taprpc/assetwalletrpc/assetwallet.pb.json.go b/taprpc/assetwalletrpc/assetwallet.pb.json.go index f3f2c44200..2addc8b92e 100644 --- a/taprpc/assetwalletrpc/assetwallet.pb.json.go +++ b/taprpc/assetwalletrpc/assetwallet.pb.json.go @@ -121,6 +121,31 @@ func RegisterAssetWalletJSONCallbacks(registry map[string]func(ctx context.Conte callback(string(respBytes), nil) } + registry["assetwalletrpc.AssetWallet.GetCommitVirtualPsbtsStatus"] = func(ctx context.Context, + conn *grpc.ClientConn, reqJSON string, callback func(string, error)) { + + req := &GetCommitVirtualPsbtsStatusRequest{} + err := marshaler.Unmarshal([]byte(reqJSON), req) + if err != nil { + callback("", err) + return + } + + client := NewAssetWalletClient(conn) + resp, err := client.GetCommitVirtualPsbtsStatus(ctx, req) + if err != nil { + callback("", err) + return + } + + respBytes, err := marshaler.Marshal(resp) + if err != nil { + callback("", err) + return + } + callback(string(respBytes), nil) + } + registry["assetwalletrpc.AssetWallet.PublishAndLogTransfer"] = func(ctx context.Context, conn *grpc.ClientConn, reqJSON string, callback func(string, error)) { diff --git a/taprpc/assetwalletrpc/assetwallet.proto b/taprpc/assetwalletrpc/assetwallet.proto index 7b641253e8..1d9ec46dcb 100644 --- a/taprpc/assetwalletrpc/assetwallet.proto +++ b/taprpc/assetwalletrpc/assetwallet.proto @@ -43,11 +43,36 @@ service AssetWallet { rpc CommitVirtualPsbts (CommitVirtualPsbtsRequest) returns (CommitVirtualPsbtsResponse); + /* + GetCommitVirtualPsbtsStatus reports the outcome of a CommitVirtualPsbts + call made with a request_id. It says whether that call is still in + progress or completed, and lists the lnd lock ID and locked outpoints + recorded for it. An unknown request_id is reported as unknown rather + than an error. Repeating CommitVirtualPsbts returns a completed or + failed stored response as-is while it is still inside the retention + window. A repeat while the first call is still running, or while lnd + still holds its input leases, is rejected. After those leases expire, + the pending row is deleted and the same request funds again. + */ + rpc GetCommitVirtualPsbtsStatus (GetCommitVirtualPsbtsStatusRequest) + returns (GetCommitVirtualPsbtsStatusResponse); + /* PublishAndLogTransfer accepts a fully committed and signed anchor transaction and publishes it to the Bitcoin network. It also logs the transfer of the given active and passive assets in the database and ships any outgoing proofs to the counterparties. + + The RPC is safe to retry after a lost response. A repeat call whose + final anchor transaction is already logged returns that transfer as the + SendAssetResponse and does not insert another asset_transfers row or + publish the anchor again. Callers reconcile by retrying this RPC (with + the same request_id when they set one) or by calling ListTransfers with + the anchor txid. An empty request_id still reconciles by the anchor + transaction. A request_id must not be reused for a different anchor + transaction while that publish is in flight. The binding is + process-local and in-flight only: it is released when the publish + completes or fails, and it is not kept across a daemon restart. */ rpc PublishAndLogTransfer (PublishAndLogRequest) returns (taprpc.SendAssetResponse); @@ -334,7 +359,12 @@ message CommitVirtualPsbtsRequest { int32 existing_output_index = 4; /* - Add a new P2TR change output to the PSBT if required. + Add a new P2TR change output to the PSBT if required. When set to + false, tapd asks lnd not to add a new change output. Until lnd + supports that mode (see lightningnetwork/lnd#10967), funding may + still alter the anchor output set; tapd then fails closed with an + error (see lightninglabs/taproot-assets#2209). Use + skip_funding=true with caller-supplied inputs or add=true instead. */ bool add = 5; } @@ -377,6 +407,23 @@ message CommitVirtualPsbtsRequest { If unset, the daemon's default proof version is used. */ TransitionProofVersion transition_proof_version = 11; + + /* + Optional caller-chosen idempotency key, 1 to 64 bytes. When empty, the + RPC is unchanged and nothing is stored. When set, tapd records the + outcome under this key. Only a completed or failed stored response is + returned as-is, and only inside the retention window + (wallet.commit-virtual-psbt-retention, 24h by default). After that + window the stored response may be removed and the same request funds + again. The same key with a different request is rejected. A repeat + while the first call is still running, or while lnd still holds its + input leases, is rejected; use GetCommitVirtualPsbtsStatus to read + the lock ID and leased outpoints. After those leases expire, the + pending row is deleted and the same request funds again. If + custom_lock_id is empty, tapd derives a 32-byte lock ID as + SHA-256(request_id) and uses that for the lnd lease. + */ + bytes request_id = 12; } message CommitVirtualPsbtsResponse { @@ -419,6 +466,56 @@ message CommitVirtualPsbtsResponse { repeated taprpc.OutPoint lnd_locked_utxos = 6; } +enum CommitVirtualPsbtsStatus { + /* + No CommitVirtualPsbts call with this request_id has been recorded. + */ + COMMIT_VIRTUAL_PSBTS_STATUS_UNKNOWN = 0; + + /* + The call has been claimed and has not yet recorded a final response. + Leased outpoints are present only after funding has returned. A repeat + of CommitVirtualPsbts does not fund again while the call is in progress + or while lnd still holds its leases. After those leases expire, the + same request funds again. + */ + COMMIT_VIRTUAL_PSBTS_STATUS_PENDING = 1; + + /* + The call completed. Repeating CommitVirtualPsbts with the same request + returns the stored response while it is still inside the retention + window. Replay of request_id is only guaranteed within that window. + */ + COMMIT_VIRTUAL_PSBTS_STATUS_COMPLETED = 2; +} + +message GetCommitVirtualPsbtsStatusRequest { + /* + The request_id passed to CommitVirtualPsbts. Required, 1 to 64 bytes. + */ + bytes request_id = 1; +} + +message GetCommitVirtualPsbtsStatusResponse { + /* + Whether the commit is unknown, still in progress, or completed. + */ + CommitVirtualPsbtsStatus status = 1; + + /* + The lnd lock ID for the leases, when known. This is the request's + custom_lock_id (or the ID derived from request_id) until funding + returns, then the lock ID reported by lnd. + */ + bytes lock_id = 2; + + /* + Outpoints leased for this commit. Empty until funding has returned. + Only inputs added by CommitVirtualPsbts are included. + */ + repeated taprpc.OutPoint lnd_locked_utxos = 3; +} + message PublishAndLogRequest { /* The funded BTC level anchor transaction with all outputs updated to commit @@ -465,6 +562,18 @@ message PublishAndLogRequest { Multiple transfers can share the same label. */ string label = 7; + + /* + Optional caller-chosen idempotency key for this publish. A retry that + repeats the key with the same anchor transaction returns the transfer + already logged for that anchor. Reusing the key for a different anchor + transaction is rejected while that publish is in flight. The binding is + process-local and in-flight only: it is released when the publish + completes or fails and is not kept across a daemon restart. An empty + key still reconciles by the anchor transaction, so a lost response can + be retried safely. + */ + bytes request_id = 8; } message NextInternalKeyRequest { diff --git a/taprpc/assetwalletrpc/assetwallet.swagger.json b/taprpc/assetwalletrpc/assetwallet.swagger.json index 8caf9722e6..66d1b79523 100644 --- a/taprpc/assetwalletrpc/assetwallet.swagger.json +++ b/taprpc/assetwalletrpc/assetwallet.swagger.json @@ -412,6 +412,39 @@ ] } }, + "/v1/taproot-assets/wallet/virtual-psbt/commit/status": { + "post": { + "summary": "GetCommitVirtualPsbtsStatus reports the outcome of a CommitVirtualPsbts\ncall made with a request_id. It says whether that call is still in\nprogress or completed, and lists the lnd lock ID and locked outpoints\nrecorded for it. An unknown request_id is reported as unknown rather\nthan an error. Repeating CommitVirtualPsbts returns a completed or\nfailed stored response as-is while it is still inside the retention\nwindow. A repeat while the first call is still running, or while lnd\nstill holds its input leases, is rejected. After those leases expire,\nthe pending row is deleted and the same request funds again.", + "operationId": "AssetWallet_GetCommitVirtualPsbtsStatus", + "responses": { + "200": { + "description": "A successful response.", + "schema": { + "$ref": "#/definitions/assetwalletrpcGetCommitVirtualPsbtsStatusResponse" + } + }, + "default": { + "description": "An unexpected error response.", + "schema": { + "$ref": "#/definitions/rpcStatus" + } + } + }, + "parameters": [ + { + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/assetwalletrpcGetCommitVirtualPsbtsStatusRequest" + } + } + ], + "tags": [ + "AssetWallet" + ] + } + }, "/v1/taproot-assets/wallet/virtual-psbt/fund": { "post": { "summary": "FundVirtualPsbt selects inputs from the available asset commitments to fund\na virtual transaction matching the template.", @@ -448,6 +481,7 @@ "/v1/taproot-assets/wallet/virtual-psbt/log-transfer": { "post": { "summary": "PublishAndLogTransfer accepts a fully committed and signed anchor\ntransaction and publishes it to the Bitcoin network. It also logs the\ntransfer of the given active and passive assets in the database and ships\nany outgoing proofs to the counterparties.", + "description": "The RPC is safe to retry after a lost response. A repeat call whose\nfinal anchor transaction is already logged returns that transfer as the\nSendAssetResponse and does not insert another asset_transfers row or\npublish the anchor again. Callers reconcile by retrying this RPC (with\nthe same request_id when they set one) or by calling ListTransfers with\nthe anchor txid. An empty request_id still reconciles by the anchor\ntransaction. A request_id must not be reused for a different anchor\ntransaction while that publish is in flight. The binding is\nprocess-local and in-flight only: it is released when the publish\ncompletes or fails, and it is not kept across a daemon restart.", "operationId": "AssetWallet_PublishAndLogTransfer", "responses": { "200": { @@ -577,7 +611,7 @@ }, "add": { "type": "boolean", - "description": "Add a new P2TR change output to the PSBT if required." + "description": "Add a new P2TR change output to the PSBT if required. When set to\nfalse, tapd asks lnd not to add a new change output. Until lnd\nsupports that mode (see lightningnetwork/lnd#10967), funding may\nstill alter the anchor output set; tapd then fails closed with an\nerror (see lightninglabs/taproot-assets#2209). Use\nskip_funding=true with caller-supplied inputs or add=true instead." }, "target_conf": { "type": "integer", @@ -606,6 +640,11 @@ "transition_proof_version": { "$ref": "#/definitions/assetwalletrpcTransitionProofVersion", "description": "The version to use when generating the state transition proof suffixes.\nIf unset, the daemon's default proof version is used." + }, + "request_id": { + "type": "string", + "format": "byte", + "description": "Optional caller-chosen idempotency key, 1 to 64 bytes. When empty, the\nRPC is unchanged and nothing is stored. When set, tapd records the\noutcome under this key. Only a completed or failed stored response is\nreturned as-is, and only inside the retention window\n(wallet.commit-virtual-psbt-retention, 24h by default). After that\nwindow the stored response may be removed and the same request funds\nagain. The same key with a different request is rejected. A repeat\nwhile the first call is still running, or while lnd still holds its\ninput leases, is rejected; use GetCommitVirtualPsbtsStatus to read\nthe lock ID and leased outpoints. After those leases expire, the\npending row is deleted and the same request funds again. If\ncustom_lock_id is empty, tapd derives a 32-byte lock ID as\nSHA-256(request_id) and uses that for the lnd lease." } } }, @@ -648,6 +687,16 @@ } } }, + "assetwalletrpcCommitVirtualPsbtsStatus": { + "type": "string", + "enum": [ + "COMMIT_VIRTUAL_PSBTS_STATUS_UNKNOWN", + "COMMIT_VIRTUAL_PSBTS_STATUS_PENDING", + "COMMIT_VIRTUAL_PSBTS_STATUS_COMPLETED" + ], + "default": "COMMIT_VIRTUAL_PSBTS_STATUS_UNKNOWN", + "description": " - COMMIT_VIRTUAL_PSBTS_STATUS_UNKNOWN: No CommitVirtualPsbts call with this request_id has been recorded.\n - COMMIT_VIRTUAL_PSBTS_STATUS_PENDING: The call has been claimed and has not yet recorded a final response.\nLeased outpoints are present only after funding has returned. A repeat\nof CommitVirtualPsbts does not fund again while the call is in progress\nor while lnd still holds its leases. After those leases expire, the\nsame request funds again.\n - COMMIT_VIRTUAL_PSBTS_STATUS_COMPLETED: The call completed. Repeating CommitVirtualPsbts with the same request\nreturns the stored response while it is still inside the retention\nwindow. Replay of request_id is only guaranteed within that window." + }, "assetwalletrpcDeclareScriptKeyRequest": { "type": "object", "properties": { @@ -726,6 +775,38 @@ } } }, + "assetwalletrpcGetCommitVirtualPsbtsStatusRequest": { + "type": "object", + "properties": { + "request_id": { + "type": "string", + "format": "byte", + "description": "The request_id passed to CommitVirtualPsbts. Required, 1 to 64 bytes." + } + } + }, + "assetwalletrpcGetCommitVirtualPsbtsStatusResponse": { + "type": "object", + "properties": { + "status": { + "$ref": "#/definitions/assetwalletrpcCommitVirtualPsbtsStatus", + "description": "Whether the commit is unknown, still in progress, or completed." + }, + "lock_id": { + "type": "string", + "format": "byte", + "description": "The lnd lock ID for the leases, when known. This is the request's\ncustom_lock_id (or the ID derived from request_id) until funding\nreturns, then the lock ID reported by lnd." + }, + "lnd_locked_utxos": { + "type": "array", + "items": { + "type": "object", + "$ref": "#/definitions/taprpcOutPoint" + }, + "description": "Outpoints leased for this commit. Empty until funding has returned.\nOnly inputs added by CommitVirtualPsbts are included." + } + } + }, "assetwalletrpcImportAssetsFromBackupRequest": { "type": "object", "properties": { @@ -885,6 +966,11 @@ "label": { "type": "string", "description": "An optional short label for the transfer. This label can be used to track\nthe progress of the transfer via the logs or an event subscription.\nMultiple transfers can share the same label." + }, + "request_id": { + "type": "string", + "format": "byte", + "description": "Optional caller-chosen idempotency key for this publish. A retry that\nrepeats the key with the same anchor transaction returns the transfer\nalready logged for that anchor. Reusing the key for a different anchor\ntransaction is rejected while that publish is in flight. The binding is\nprocess-local and in-flight only: it is released when the publish\ncompletes or fails and is not kept across a daemon restart. An empty\nkey still reconciles by the anchor transaction, so a lost response can\nbe retried safely." } } }, diff --git a/taprpc/assetwalletrpc/assetwallet.yaml b/taprpc/assetwalletrpc/assetwallet.yaml index 6b509434d9..c87d105761 100644 --- a/taprpc/assetwalletrpc/assetwallet.yaml +++ b/taprpc/assetwalletrpc/assetwallet.yaml @@ -18,7 +18,11 @@ http: - selector: assetwalletrpc.AssetWallet.CommitVirtualPsbts post: "/v1/taproot-assets/wallet/virtual-psbt/commit" body: "*" - + + - selector: assetwalletrpc.AssetWallet.GetCommitVirtualPsbtsStatus + post: "/v1/taproot-assets/wallet/virtual-psbt/commit/status" + body: "*" + - selector: assetwalletrpc.AssetWallet.PublishAndLogTransfer post: "/v1/taproot-assets/wallet/virtual-psbt/log-transfer" body: "*" diff --git a/taprpc/assetwalletrpc/assetwallet_grpc.pb.go b/taprpc/assetwalletrpc/assetwallet_grpc.pb.go index 694290a099..cf456b3117 100644 --- a/taprpc/assetwalletrpc/assetwallet_grpc.pb.go +++ b/taprpc/assetwalletrpc/assetwallet_grpc.pb.go @@ -38,10 +38,31 @@ type AssetWalletClient interface { // In addition, the BTC level anchor transaction is funded and prepared up to // the point where it is ready to be signed. CommitVirtualPsbts(ctx context.Context, in *CommitVirtualPsbtsRequest, opts ...grpc.CallOption) (*CommitVirtualPsbtsResponse, error) + // GetCommitVirtualPsbtsStatus reports the outcome of a CommitVirtualPsbts + // call made with a request_id. It says whether that call is still in + // progress or completed, and lists the lnd lock ID and locked outpoints + // recorded for it. An unknown request_id is reported as unknown rather + // than an error. Repeating CommitVirtualPsbts returns a completed or + // failed stored response as-is while it is still inside the retention + // window. A repeat while the first call is still running, or while lnd + // still holds its input leases, is rejected. After those leases expire, + // the pending row is deleted and the same request funds again. + GetCommitVirtualPsbtsStatus(ctx context.Context, in *GetCommitVirtualPsbtsStatusRequest, opts ...grpc.CallOption) (*GetCommitVirtualPsbtsStatusResponse, error) // PublishAndLogTransfer accepts a fully committed and signed anchor // transaction and publishes it to the Bitcoin network. It also logs the // transfer of the given active and passive assets in the database and ships // any outgoing proofs to the counterparties. + // + // The RPC is safe to retry after a lost response. A repeat call whose + // final anchor transaction is already logged returns that transfer as the + // SendAssetResponse and does not insert another asset_transfers row or + // publish the anchor again. Callers reconcile by retrying this RPC (with + // the same request_id when they set one) or by calling ListTransfers with + // the anchor txid. An empty request_id still reconciles by the anchor + // transaction. A request_id must not be reused for a different anchor + // transaction while that publish is in flight. The binding is + // process-local and in-flight only: it is released when the publish + // completes or fails, and it is not kept across a daemon restart. PublishAndLogTransfer(ctx context.Context, in *PublishAndLogRequest, opts ...grpc.CallOption) (*taprpc.SendAssetResponse, error) // NextInternalKey derives the next internal key for the given key family and // stores it as an internal key in the database to make sure it is identified @@ -132,6 +153,15 @@ func (c *assetWalletClient) CommitVirtualPsbts(ctx context.Context, in *CommitVi return out, nil } +func (c *assetWalletClient) GetCommitVirtualPsbtsStatus(ctx context.Context, in *GetCommitVirtualPsbtsStatusRequest, opts ...grpc.CallOption) (*GetCommitVirtualPsbtsStatusResponse, error) { + out := new(GetCommitVirtualPsbtsStatusResponse) + err := c.cc.Invoke(ctx, "/assetwalletrpc.AssetWallet/GetCommitVirtualPsbtsStatus", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + func (c *assetWalletClient) PublishAndLogTransfer(ctx context.Context, in *PublishAndLogRequest, opts ...grpc.CallOption) (*taprpc.SendAssetResponse, error) { out := new(taprpc.SendAssetResponse) err := c.cc.Invoke(ctx, "/assetwalletrpc.AssetWallet/PublishAndLogTransfer", in, out, opts...) @@ -254,10 +284,31 @@ type AssetWalletServer interface { // In addition, the BTC level anchor transaction is funded and prepared up to // the point where it is ready to be signed. CommitVirtualPsbts(context.Context, *CommitVirtualPsbtsRequest) (*CommitVirtualPsbtsResponse, error) + // GetCommitVirtualPsbtsStatus reports the outcome of a CommitVirtualPsbts + // call made with a request_id. It says whether that call is still in + // progress or completed, and lists the lnd lock ID and locked outpoints + // recorded for it. An unknown request_id is reported as unknown rather + // than an error. Repeating CommitVirtualPsbts returns a completed or + // failed stored response as-is while it is still inside the retention + // window. A repeat while the first call is still running, or while lnd + // still holds its input leases, is rejected. After those leases expire, + // the pending row is deleted and the same request funds again. + GetCommitVirtualPsbtsStatus(context.Context, *GetCommitVirtualPsbtsStatusRequest) (*GetCommitVirtualPsbtsStatusResponse, error) // PublishAndLogTransfer accepts a fully committed and signed anchor // transaction and publishes it to the Bitcoin network. It also logs the // transfer of the given active and passive assets in the database and ships // any outgoing proofs to the counterparties. + // + // The RPC is safe to retry after a lost response. A repeat call whose + // final anchor transaction is already logged returns that transfer as the + // SendAssetResponse and does not insert another asset_transfers row or + // publish the anchor again. Callers reconcile by retrying this RPC (with + // the same request_id when they set one) or by calling ListTransfers with + // the anchor txid. An empty request_id still reconciles by the anchor + // transaction. A request_id must not be reused for a different anchor + // transaction while that publish is in flight. The binding is + // process-local and in-flight only: it is released when the publish + // completes or fails, and it is not kept across a daemon restart. PublishAndLogTransfer(context.Context, *PublishAndLogRequest) (*taprpc.SendAssetResponse, error) // NextInternalKey derives the next internal key for the given key family and // stores it as an internal key in the database to make sure it is identified @@ -321,6 +372,9 @@ func (UnimplementedAssetWalletServer) AnchorVirtualPsbts(context.Context, *Ancho func (UnimplementedAssetWalletServer) CommitVirtualPsbts(context.Context, *CommitVirtualPsbtsRequest) (*CommitVirtualPsbtsResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method CommitVirtualPsbts not implemented") } +func (UnimplementedAssetWalletServer) GetCommitVirtualPsbtsStatus(context.Context, *GetCommitVirtualPsbtsStatusRequest) (*GetCommitVirtualPsbtsStatusResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetCommitVirtualPsbtsStatus not implemented") +} func (UnimplementedAssetWalletServer) PublishAndLogTransfer(context.Context, *PublishAndLogRequest) (*taprpc.SendAssetResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method PublishAndLogTransfer not implemented") } @@ -439,6 +493,24 @@ func _AssetWallet_CommitVirtualPsbts_Handler(srv interface{}, ctx context.Contex return interceptor(ctx, in, info, handler) } +func _AssetWallet_GetCommitVirtualPsbtsStatus_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetCommitVirtualPsbtsStatusRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(AssetWalletServer).GetCommitVirtualPsbtsStatus(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/assetwalletrpc.AssetWallet/GetCommitVirtualPsbtsStatus", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(AssetWalletServer).GetCommitVirtualPsbtsStatus(ctx, req.(*GetCommitVirtualPsbtsStatusRequest)) + } + return interceptor(ctx, in, info, handler) +} + func _AssetWallet_PublishAndLogTransfer_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(PublishAndLogRequest) if err := dec(in); err != nil { @@ -660,6 +732,10 @@ var AssetWallet_ServiceDesc = grpc.ServiceDesc{ MethodName: "CommitVirtualPsbts", Handler: _AssetWallet_CommitVirtualPsbts_Handler, }, + { + MethodName: "GetCommitVirtualPsbtsStatus", + Handler: _AssetWallet_GetCommitVirtualPsbtsStatus_Handler, + }, { MethodName: "PublishAndLogTransfer", Handler: _AssetWallet_PublishAndLogTransfer_Handler, diff --git a/taprpc/mintrpc/mint.pb.go b/taprpc/mintrpc/mint.pb.go index bc5a471d7f..6cffa9a39f 100644 --- a/taprpc/mintrpc/mint.pb.go +++ b/taprpc/mintrpc/mint.pb.go @@ -634,9 +634,18 @@ type MintingBatch struct { HeightHint uint32 `protobuf:"varint,6,opt,name=height_hint,json=heightHint,proto3" json:"height_hint,omitempty"` // The genesis transaction as a PSBT packet. Only populated if the batch has // been committed. - BatchPsbt []byte `protobuf:"bytes,7,opt,name=batch_psbt,json=batchPsbt,proto3" json:"batch_psbt,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + BatchPsbt []byte `protobuf:"bytes,7,opt,name=batch_psbt,json=batchPsbt,proto3" json:"batch_psbt,omitempty"` + // The latest prepared or broadcast custom-anchor wallet lease renewal + // degradation. Empty after a successful renewal or wallet acceptance. + CustomAnchorLeaseError string `protobuf:"bytes,8,opt,name=custom_anchor_lease_error,json=customAnchorLeaseError,proto3" json:"custom_anchor_lease_error,omitempty"` + // The latest ambiguous publication error for a custom-anchor transaction + // that remains watched and retried byte-identically. + CustomAnchorPublishError string `protobuf:"bytes,9,opt,name=custom_anchor_publish_error,json=customAnchorPublishError,proto3" json:"custom_anchor_publish_error,omitempty"` + // Historical custom-anchor key health requiring operator intervention. + // Empty when the managed anchor key is healthy or was repaired. + CustomAnchorKeyError string `protobuf:"bytes,10,opt,name=custom_anchor_key_error,json=customAnchorKeyError,proto3" json:"custom_anchor_key_error,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *MintingBatch) Reset() { @@ -718,6 +727,27 @@ func (x *MintingBatch) GetBatchPsbt() []byte { return nil } +func (x *MintingBatch) GetCustomAnchorLeaseError() string { + if x != nil { + return x.CustomAnchorLeaseError + } + return "" +} + +func (x *MintingBatch) GetCustomAnchorPublishError() string { + if x != nil { + return x.CustomAnchorPublishError + } + return "" +} + +func (x *MintingBatch) GetCustomAnchorKeyError() string { + if x != nil { + return x.CustomAnchorKeyError + } + return "" +} + type VerboseBatch struct { state protoimpl.MessageState `protogen:"open.v1"` // The minting batch, without any assets. @@ -788,9 +818,23 @@ type FundBatchRequest struct { // // *FundBatchRequest_FullTree // *FundBatchRequest_Branch - BatchSibling isFundBatchRequest_BatchSibling `protobuf_oneof:"batch_sibling"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + BatchSibling isFundBatchRequest_BatchSibling `protobuf_oneof:"batch_sibling"` + // An optional caller-funded anchor PSBT. Input zero remains the asset + // genesis point and the packet must not contain signatures yet. The + // selected asset anchor output must not contain PSBT_OUT_TAP_TREE because + // PrepareBatch replaces its script tree with the asset commitment and the + // optional batch_sibling. + AnchorPsbt []byte `protobuf:"bytes,5,opt,name=anchor_psbt,json=anchorPsbt,proto3" json:"anchor_psbt,omitempty"` + // The output that will receive the Taproot Asset commitment. + AssetAnchorOutputIndex uint32 `protobuf:"varint,6,opt,name=asset_anchor_output_index,json=assetAnchorOutputIndex,proto3" json:"asset_anchor_output_index,omitempty"` + // The index of an existing change output in anchor_psbt. + ChangeOutputIndex int32 `protobuf:"varint,7,opt,name=change_output_index,json=changeOutputIndex,proto3" json:"change_output_index,omitempty"` + // Set when anchor_psbt has no change output. + NoChangeOutput bool `protobuf:"varint,8,opt,name=no_change_output,json=noChangeOutput,proto3" json:"no_change_output,omitempty"` + // The supply commitment output in anchor_psbt, when applicable. + PreCommitOutputIndex *uint32 `protobuf:"varint,9,opt,name=pre_commit_output_index,json=preCommitOutputIndex,proto3,oneof" json:"pre_commit_output_index,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *FundBatchRequest) Reset() { @@ -862,6 +906,41 @@ func (x *FundBatchRequest) GetBranch() *taprpc.TapBranch { return nil } +func (x *FundBatchRequest) GetAnchorPsbt() []byte { + if x != nil { + return x.AnchorPsbt + } + return nil +} + +func (x *FundBatchRequest) GetAssetAnchorOutputIndex() uint32 { + if x != nil { + return x.AssetAnchorOutputIndex + } + return 0 +} + +func (x *FundBatchRequest) GetChangeOutputIndex() int32 { + if x != nil { + return x.ChangeOutputIndex + } + return 0 +} + +func (x *FundBatchRequest) GetNoChangeOutput() bool { + if x != nil { + return x.NoChangeOutput + } + return false +} + +func (x *FundBatchRequest) GetPreCommitOutputIndex() uint32 { + if x != nil && x.PreCommitOutputIndex != nil { + return *x.PreCommitOutputIndex + } + return 0 +} + type isFundBatchRequest_BatchSibling interface { isFundBatchRequest_BatchSibling() } @@ -926,6 +1005,97 @@ func (x *FundBatchResponse) GetBatch() *VerboseBatch { return nil } +type PrepareBatchRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + // If true, then the assets currently in the batch won't be returned in the + // response. + ShortResponse bool `protobuf:"varint,1,opt,name=short_response,json=shortResponse,proto3" json:"short_response,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *PrepareBatchRequest) Reset() { + *x = PrepareBatchRequest{} + mi := &file_mintrpc_mint_proto_msgTypes[9] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *PrepareBatchRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*PrepareBatchRequest) ProtoMessage() {} + +func (x *PrepareBatchRequest) ProtoReflect() protoreflect.Message { + mi := &file_mintrpc_mint_proto_msgTypes[9] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use PrepareBatchRequest.ProtoReflect.Descriptor instead. +func (*PrepareBatchRequest) Descriptor() ([]byte, []int) { + return file_mintrpc_mint_proto_rawDescGZIP(), []int{9} +} + +func (x *PrepareBatchRequest) GetShortResponse() bool { + if x != nil { + return x.ShortResponse + } + return false +} + +type PrepareBatchResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + // The prepared batch, including the commitment-mutated anchor PSBT. + Batch *MintingBatch `protobuf:"bytes,1,opt,name=batch,proto3" json:"batch,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *PrepareBatchResponse) Reset() { + *x = PrepareBatchResponse{} + mi := &file_mintrpc_mint_proto_msgTypes[10] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *PrepareBatchResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*PrepareBatchResponse) ProtoMessage() {} + +func (x *PrepareBatchResponse) ProtoReflect() protoreflect.Message { + mi := &file_mintrpc_mint_proto_msgTypes[10] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use PrepareBatchResponse.ProtoReflect.Descriptor instead. +func (*PrepareBatchResponse) Descriptor() ([]byte, []int) { + return file_mintrpc_mint_proto_rawDescGZIP(), []int{10} +} + +func (x *PrepareBatchResponse) GetBatch() *MintingBatch { + if x != nil { + return x.Batch + } + return nil +} + type SealBatchRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // If true, then the assets currently in the batch won't be returned in the @@ -946,7 +1116,7 @@ type SealBatchRequest struct { func (x *SealBatchRequest) Reset() { *x = SealBatchRequest{} - mi := &file_mintrpc_mint_proto_msgTypes[9] + mi := &file_mintrpc_mint_proto_msgTypes[11] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -958,7 +1128,7 @@ func (x *SealBatchRequest) String() string { func (*SealBatchRequest) ProtoMessage() {} func (x *SealBatchRequest) ProtoReflect() protoreflect.Message { - mi := &file_mintrpc_mint_proto_msgTypes[9] + mi := &file_mintrpc_mint_proto_msgTypes[11] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -971,7 +1141,7 @@ func (x *SealBatchRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use SealBatchRequest.ProtoReflect.Descriptor instead. func (*SealBatchRequest) Descriptor() ([]byte, []int) { - return file_mintrpc_mint_proto_rawDescGZIP(), []int{9} + return file_mintrpc_mint_proto_rawDescGZIP(), []int{11} } func (x *SealBatchRequest) GetShortResponse() bool { @@ -1005,7 +1175,7 @@ type SealBatchResponse struct { func (x *SealBatchResponse) Reset() { *x = SealBatchResponse{} - mi := &file_mintrpc_mint_proto_msgTypes[10] + mi := &file_mintrpc_mint_proto_msgTypes[12] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1017,7 +1187,7 @@ func (x *SealBatchResponse) String() string { func (*SealBatchResponse) ProtoMessage() {} func (x *SealBatchResponse) ProtoReflect() protoreflect.Message { - mi := &file_mintrpc_mint_proto_msgTypes[10] + mi := &file_mintrpc_mint_proto_msgTypes[12] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1030,7 +1200,7 @@ func (x *SealBatchResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use SealBatchResponse.ProtoReflect.Descriptor instead. func (*SealBatchResponse) Descriptor() ([]byte, []int) { - return file_mintrpc_mint_proto_rawDescGZIP(), []int{10} + return file_mintrpc_mint_proto_rawDescGZIP(), []int{12} } func (x *SealBatchResponse) GetBatch() *MintingBatch { @@ -1056,14 +1226,17 @@ type FinalizeBatchRequest struct { // // *FinalizeBatchRequest_FullTree // *FinalizeBatchRequest_Branch - BatchSibling isFinalizeBatchRequest_BatchSibling `protobuf_oneof:"batch_sibling"` + BatchSibling isFinalizeBatchRequest_BatchSibling `protobuf_oneof:"batch_sibling"` + // The externally signed packet returned by PrepareBatch. All non-signing + // fields must be identical to the prepared packet. + SignedPsbt []byte `protobuf:"bytes,5,opt,name=signed_psbt,json=signedPsbt,proto3" json:"signed_psbt,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *FinalizeBatchRequest) Reset() { *x = FinalizeBatchRequest{} - mi := &file_mintrpc_mint_proto_msgTypes[11] + mi := &file_mintrpc_mint_proto_msgTypes[13] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1075,7 +1248,7 @@ func (x *FinalizeBatchRequest) String() string { func (*FinalizeBatchRequest) ProtoMessage() {} func (x *FinalizeBatchRequest) ProtoReflect() protoreflect.Message { - mi := &file_mintrpc_mint_proto_msgTypes[11] + mi := &file_mintrpc_mint_proto_msgTypes[13] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1088,7 +1261,7 @@ func (x *FinalizeBatchRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use FinalizeBatchRequest.ProtoReflect.Descriptor instead. func (*FinalizeBatchRequest) Descriptor() ([]byte, []int) { - return file_mintrpc_mint_proto_rawDescGZIP(), []int{11} + return file_mintrpc_mint_proto_rawDescGZIP(), []int{13} } func (x *FinalizeBatchRequest) GetShortResponse() bool { @@ -1130,6 +1303,13 @@ func (x *FinalizeBatchRequest) GetBranch() *taprpc.TapBranch { return nil } +func (x *FinalizeBatchRequest) GetSignedPsbt() []byte { + if x != nil { + return x.SignedPsbt + } + return nil +} + type isFinalizeBatchRequest_BatchSibling interface { isFinalizeBatchRequest_BatchSibling() } @@ -1159,7 +1339,7 @@ type FinalizeBatchResponse struct { func (x *FinalizeBatchResponse) Reset() { *x = FinalizeBatchResponse{} - mi := &file_mintrpc_mint_proto_msgTypes[12] + mi := &file_mintrpc_mint_proto_msgTypes[14] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1171,7 +1351,7 @@ func (x *FinalizeBatchResponse) String() string { func (*FinalizeBatchResponse) ProtoMessage() {} func (x *FinalizeBatchResponse) ProtoReflect() protoreflect.Message { - mi := &file_mintrpc_mint_proto_msgTypes[12] + mi := &file_mintrpc_mint_proto_msgTypes[14] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1184,7 +1364,7 @@ func (x *FinalizeBatchResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use FinalizeBatchResponse.ProtoReflect.Descriptor instead. func (*FinalizeBatchResponse) Descriptor() ([]byte, []int) { - return file_mintrpc_mint_proto_rawDescGZIP(), []int{12} + return file_mintrpc_mint_proto_rawDescGZIP(), []int{14} } func (x *FinalizeBatchResponse) GetBatch() *MintingBatch { @@ -1202,7 +1382,7 @@ type CancelBatchRequest struct { func (x *CancelBatchRequest) Reset() { *x = CancelBatchRequest{} - mi := &file_mintrpc_mint_proto_msgTypes[13] + mi := &file_mintrpc_mint_proto_msgTypes[15] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1214,7 +1394,7 @@ func (x *CancelBatchRequest) String() string { func (*CancelBatchRequest) ProtoMessage() {} func (x *CancelBatchRequest) ProtoReflect() protoreflect.Message { - mi := &file_mintrpc_mint_proto_msgTypes[13] + mi := &file_mintrpc_mint_proto_msgTypes[15] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1227,7 +1407,7 @@ func (x *CancelBatchRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use CancelBatchRequest.ProtoReflect.Descriptor instead. func (*CancelBatchRequest) Descriptor() ([]byte, []int) { - return file_mintrpc_mint_proto_rawDescGZIP(), []int{13} + return file_mintrpc_mint_proto_rawDescGZIP(), []int{15} } type CancelBatchResponse struct { @@ -1240,7 +1420,7 @@ type CancelBatchResponse struct { func (x *CancelBatchResponse) Reset() { *x = CancelBatchResponse{} - mi := &file_mintrpc_mint_proto_msgTypes[14] + mi := &file_mintrpc_mint_proto_msgTypes[16] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1252,7 +1432,7 @@ func (x *CancelBatchResponse) String() string { func (*CancelBatchResponse) ProtoMessage() {} func (x *CancelBatchResponse) ProtoReflect() protoreflect.Message { - mi := &file_mintrpc_mint_proto_msgTypes[14] + mi := &file_mintrpc_mint_proto_msgTypes[16] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1265,7 +1445,7 @@ func (x *CancelBatchResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use CancelBatchResponse.ProtoReflect.Descriptor instead. func (*CancelBatchResponse) Descriptor() ([]byte, []int) { - return file_mintrpc_mint_proto_rawDescGZIP(), []int{14} + return file_mintrpc_mint_proto_rawDescGZIP(), []int{16} } func (x *CancelBatchResponse) GetBatchKey() []byte { @@ -1293,7 +1473,7 @@ type ListBatchRequest struct { func (x *ListBatchRequest) Reset() { *x = ListBatchRequest{} - mi := &file_mintrpc_mint_proto_msgTypes[15] + mi := &file_mintrpc_mint_proto_msgTypes[17] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1305,7 +1485,7 @@ func (x *ListBatchRequest) String() string { func (*ListBatchRequest) ProtoMessage() {} func (x *ListBatchRequest) ProtoReflect() protoreflect.Message { - mi := &file_mintrpc_mint_proto_msgTypes[15] + mi := &file_mintrpc_mint_proto_msgTypes[17] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1318,7 +1498,7 @@ func (x *ListBatchRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListBatchRequest.ProtoReflect.Descriptor instead. func (*ListBatchRequest) Descriptor() ([]byte, []int) { - return file_mintrpc_mint_proto_rawDescGZIP(), []int{15} + return file_mintrpc_mint_proto_rawDescGZIP(), []int{17} } func (x *ListBatchRequest) GetFilter() isListBatchRequest_Filter { @@ -1382,7 +1562,7 @@ type ListBatchResponse struct { func (x *ListBatchResponse) Reset() { *x = ListBatchResponse{} - mi := &file_mintrpc_mint_proto_msgTypes[16] + mi := &file_mintrpc_mint_proto_msgTypes[18] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1394,7 +1574,7 @@ func (x *ListBatchResponse) String() string { func (*ListBatchResponse) ProtoMessage() {} func (x *ListBatchResponse) ProtoReflect() protoreflect.Message { - mi := &file_mintrpc_mint_proto_msgTypes[16] + mi := &file_mintrpc_mint_proto_msgTypes[18] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1407,7 +1587,7 @@ func (x *ListBatchResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListBatchResponse.ProtoReflect.Descriptor instead. func (*ListBatchResponse) Descriptor() ([]byte, []int) { - return file_mintrpc_mint_proto_rawDescGZIP(), []int{16} + return file_mintrpc_mint_proto_rawDescGZIP(), []int{18} } func (x *ListBatchResponse) GetBatches() []*VerboseBatch { @@ -1429,7 +1609,7 @@ type SubscribeMintEventsRequest struct { func (x *SubscribeMintEventsRequest) Reset() { *x = SubscribeMintEventsRequest{} - mi := &file_mintrpc_mint_proto_msgTypes[17] + mi := &file_mintrpc_mint_proto_msgTypes[19] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1441,7 +1621,7 @@ func (x *SubscribeMintEventsRequest) String() string { func (*SubscribeMintEventsRequest) ProtoMessage() {} func (x *SubscribeMintEventsRequest) ProtoReflect() protoreflect.Message { - mi := &file_mintrpc_mint_proto_msgTypes[17] + mi := &file_mintrpc_mint_proto_msgTypes[19] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1454,7 +1634,7 @@ func (x *SubscribeMintEventsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use SubscribeMintEventsRequest.ProtoReflect.Descriptor instead. func (*SubscribeMintEventsRequest) Descriptor() ([]byte, []int) { - return file_mintrpc_mint_proto_rawDescGZIP(), []int{17} + return file_mintrpc_mint_proto_rawDescGZIP(), []int{19} } func (x *SubscribeMintEventsRequest) GetShortResponse() bool { @@ -1482,7 +1662,7 @@ type MintEvent struct { func (x *MintEvent) Reset() { *x = MintEvent{} - mi := &file_mintrpc_mint_proto_msgTypes[18] + mi := &file_mintrpc_mint_proto_msgTypes[20] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1494,7 +1674,7 @@ func (x *MintEvent) String() string { func (*MintEvent) ProtoMessage() {} func (x *MintEvent) ProtoReflect() protoreflect.Message { - mi := &file_mintrpc_mint_proto_msgTypes[18] + mi := &file_mintrpc_mint_proto_msgTypes[20] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1507,7 +1687,7 @@ func (x *MintEvent) ProtoReflect() protoreflect.Message { // Deprecated: Use MintEvent.ProtoReflect.Descriptor instead. func (*MintEvent) Descriptor() ([]byte, []int) { - return file_mintrpc_mint_proto_rawDescGZIP(), []int{18} + return file_mintrpc_mint_proto_rawDescGZIP(), []int{20} } func (x *MintEvent) GetTimestamp() int64 { @@ -1588,7 +1768,7 @@ const file_mintrpc_mint_proto_rawDesc = "" + "\x05asset\x18\x01 \x01(\v2\x12.mintrpc.MintAssetR\x05asset\x12%\n" + "\x0eshort_response\x18\x02 \x01(\bR\rshortResponse\"O\n" + "\x11MintAssetResponse\x12:\n" + - "\rpending_batch\x18\x01 \x01(\v2\x15.mintrpc.MintingBatchR\fpendingBatch\"\x83\x02\n" + + "\rpending_batch\x18\x01 \x01(\v2\x15.mintrpc.MintingBatchR\fpendingBatch\"\xb4\x03\n" + "\fMintingBatch\x12\x1b\n" + "\tbatch_key\x18\x01 \x01(\fR\bbatchKey\x12\x1d\n" + "\n" + @@ -1600,29 +1780,46 @@ const file_mintrpc_mint_proto_rawDesc = "" + "\vheight_hint\x18\x06 \x01(\rR\n" + "heightHint\x12\x1d\n" + "\n" + - "batch_psbt\x18\a \x01(\fR\tbatchPsbt\"|\n" + + "batch_psbt\x18\a \x01(\fR\tbatchPsbt\x129\n" + + "\x19custom_anchor_lease_error\x18\b \x01(\tR\x16customAnchorLeaseError\x12=\n" + + "\x1bcustom_anchor_publish_error\x18\t \x01(\tR\x18customAnchorPublishError\x125\n" + + "\x17custom_anchor_key_error\x18\n" + + " \x01(\tR\x14customAnchorKeyError\"|\n" + "\fVerboseBatch\x12+\n" + "\x05batch\x18\x01 \x01(\v2\x15.mintrpc.MintingBatchR\x05batch\x12?\n" + - "\x0funsealed_assets\x18\x02 \x03(\v2\x16.mintrpc.UnsealedAssetR\x0eunsealedAssets\"\xcc\x01\n" + + "\x0funsealed_assets\x18\x02 \x03(\v2\x16.mintrpc.UnsealedAssetR\x0eunsealedAssets\"\xda\x03\n" + "\x10FundBatchRequest\x12%\n" + "\x0eshort_response\x18\x01 \x01(\bR\rshortResponse\x12\x19\n" + "\bfee_rate\x18\x02 \x01(\rR\afeeRate\x128\n" + "\tfull_tree\x18\x03 \x01(\v2\x19.taprpc.TapscriptFullTreeH\x00R\bfullTree\x12+\n" + - "\x06branch\x18\x04 \x01(\v2\x11.taprpc.TapBranchH\x00R\x06branchB\x0f\n" + - "\rbatch_sibling\"@\n" + + "\x06branch\x18\x04 \x01(\v2\x11.taprpc.TapBranchH\x00R\x06branch\x12\x1f\n" + + "\vanchor_psbt\x18\x05 \x01(\fR\n" + + "anchorPsbt\x129\n" + + "\x19asset_anchor_output_index\x18\x06 \x01(\rR\x16assetAnchorOutputIndex\x12.\n" + + "\x13change_output_index\x18\a \x01(\x05R\x11changeOutputIndex\x12(\n" + + "\x10no_change_output\x18\b \x01(\bR\x0enoChangeOutput\x12:\n" + + "\x17pre_commit_output_index\x18\t \x01(\rH\x01R\x14preCommitOutputIndex\x88\x01\x01B\x0f\n" + + "\rbatch_siblingB\x1a\n" + + "\x18_pre_commit_output_index\"@\n" + "\x11FundBatchResponse\x12+\n" + - "\x05batch\x18\x01 \x01(\v2\x15.mintrpc.VerboseBatchR\x05batch\"\xb5\x01\n" + + "\x05batch\x18\x01 \x01(\v2\x15.mintrpc.VerboseBatchR\x05batch\"<\n" + + "\x13PrepareBatchRequest\x12%\n" + + "\x0eshort_response\x18\x01 \x01(\bR\rshortResponse\"C\n" + + "\x14PrepareBatchResponse\x12+\n" + + "\x05batch\x18\x01 \x01(\v2\x15.mintrpc.MintingBatchR\x05batch\"\xb5\x01\n" + "\x10SealBatchRequest\x12%\n" + "\x0eshort_response\x18\x01 \x01(\bR\rshortResponse\x12=\n" + "\x0fgroup_witnesses\x18\x02 \x03(\v2\x14.taprpc.GroupWitnessR\x0egroupWitnesses\x12;\n" + "\x1asigned_group_virtual_psbts\x18\x03 \x03(\tR\x17signedGroupVirtualPsbts\"@\n" + "\x11SealBatchResponse\x12+\n" + - "\x05batch\x18\x01 \x01(\v2\x15.mintrpc.MintingBatchR\x05batch\"\xd0\x01\n" + + "\x05batch\x18\x01 \x01(\v2\x15.mintrpc.MintingBatchR\x05batch\"\xf1\x01\n" + "\x14FinalizeBatchRequest\x12%\n" + "\x0eshort_response\x18\x01 \x01(\bR\rshortResponse\x12\x19\n" + "\bfee_rate\x18\x02 \x01(\rR\afeeRate\x128\n" + "\tfull_tree\x18\x03 \x01(\v2\x19.taprpc.TapscriptFullTreeH\x00R\bfullTree\x12+\n" + - "\x06branch\x18\x04 \x01(\v2\x11.taprpc.TapBranchH\x00R\x06branchB\x0f\n" + + "\x06branch\x18\x04 \x01(\v2\x11.taprpc.TapBranchH\x00R\x06branch\x12\x1f\n" + + "\vsigned_psbt\x18\x05 \x01(\fR\n" + + "signedPsbtB\x0f\n" + "\rbatch_sibling\"D\n" + "\x15FinalizeBatchResponse\x12+\n" + "\x05batch\x18\x01 \x01(\v2\x15.mintrpc.MintingBatchR\x05batch\"\x14\n" + @@ -1654,11 +1851,12 @@ const file_mintrpc_mint_proto_rawDesc = "" + "\x15BATCH_STATE_CONFIRMED\x10\x05\x12\x19\n" + "\x15BATCH_STATE_FINALIZED\x10\x06\x12\"\n" + "\x1eBATCH_STATE_SEEDLING_CANCELLED\x10\a\x12 \n" + - "\x1cBATCH_STATE_SPROUT_CANCELLED\x10\b2\x84\x04\n" + + "\x1cBATCH_STATE_SPROUT_CANCELLED\x10\b2\xd1\x04\n" + "\x04Mint\x12B\n" + "\tMintAsset\x12\x19.mintrpc.MintAssetRequest\x1a\x1a.mintrpc.MintAssetResponse\x12B\n" + "\tFundBatch\x12\x19.mintrpc.FundBatchRequest\x1a\x1a.mintrpc.FundBatchResponse\x12B\n" + - "\tSealBatch\x12\x19.mintrpc.SealBatchRequest\x1a\x1a.mintrpc.SealBatchResponse\x12N\n" + + "\tSealBatch\x12\x19.mintrpc.SealBatchRequest\x1a\x1a.mintrpc.SealBatchResponse\x12K\n" + + "\fPrepareBatch\x12\x1c.mintrpc.PrepareBatchRequest\x1a\x1d.mintrpc.PrepareBatchResponse\x12N\n" + "\rFinalizeBatch\x12\x1d.mintrpc.FinalizeBatchRequest\x1a\x1e.mintrpc.FinalizeBatchResponse\x12H\n" + "\vCancelBatch\x12\x1b.mintrpc.CancelBatchRequest\x1a\x1c.mintrpc.CancelBatchResponse\x12D\n" + "\vListBatches\x12\x19.mintrpc.ListBatchRequest\x1a\x1a.mintrpc.ListBatchResponse\x12P\n" + @@ -1677,7 +1875,7 @@ func file_mintrpc_mint_proto_rawDescGZIP() []byte { } var file_mintrpc_mint_proto_enumTypes = make([]protoimpl.EnumInfo, 1) -var file_mintrpc_mint_proto_msgTypes = make([]protoimpl.MessageInfo, 19) +var file_mintrpc_mint_proto_msgTypes = make([]protoimpl.MessageInfo, 21) var file_mintrpc_mint_proto_goTypes = []any{ (BatchState)(0), // 0: mintrpc.BatchState (*PendingAsset)(nil), // 1: mintrpc.PendingAsset @@ -1689,79 +1887,84 @@ var file_mintrpc_mint_proto_goTypes = []any{ (*VerboseBatch)(nil), // 7: mintrpc.VerboseBatch (*FundBatchRequest)(nil), // 8: mintrpc.FundBatchRequest (*FundBatchResponse)(nil), // 9: mintrpc.FundBatchResponse - (*SealBatchRequest)(nil), // 10: mintrpc.SealBatchRequest - (*SealBatchResponse)(nil), // 11: mintrpc.SealBatchResponse - (*FinalizeBatchRequest)(nil), // 12: mintrpc.FinalizeBatchRequest - (*FinalizeBatchResponse)(nil), // 13: mintrpc.FinalizeBatchResponse - (*CancelBatchRequest)(nil), // 14: mintrpc.CancelBatchRequest - (*CancelBatchResponse)(nil), // 15: mintrpc.CancelBatchResponse - (*ListBatchRequest)(nil), // 16: mintrpc.ListBatchRequest - (*ListBatchResponse)(nil), // 17: mintrpc.ListBatchResponse - (*SubscribeMintEventsRequest)(nil), // 18: mintrpc.SubscribeMintEventsRequest - (*MintEvent)(nil), // 19: mintrpc.MintEvent - (taprpc.AssetVersion)(0), // 20: taprpc.AssetVersion - (taprpc.AssetType)(0), // 21: taprpc.AssetType - (*taprpc.AssetMeta)(nil), // 22: taprpc.AssetMeta - (*taprpc.KeyDescriptor)(nil), // 23: taprpc.KeyDescriptor - (*taprpc.ScriptKey)(nil), // 24: taprpc.ScriptKey - (*taprpc.GroupKeyRequest)(nil), // 25: taprpc.GroupKeyRequest - (*taprpc.GroupVirtualTx)(nil), // 26: taprpc.GroupVirtualTx - (*taprpc.ExternalKey)(nil), // 27: taprpc.ExternalKey - (*taprpc.TapscriptFullTree)(nil), // 28: taprpc.TapscriptFullTree - (*taprpc.TapBranch)(nil), // 29: taprpc.TapBranch - (*taprpc.GroupWitness)(nil), // 30: taprpc.GroupWitness + (*PrepareBatchRequest)(nil), // 10: mintrpc.PrepareBatchRequest + (*PrepareBatchResponse)(nil), // 11: mintrpc.PrepareBatchResponse + (*SealBatchRequest)(nil), // 12: mintrpc.SealBatchRequest + (*SealBatchResponse)(nil), // 13: mintrpc.SealBatchResponse + (*FinalizeBatchRequest)(nil), // 14: mintrpc.FinalizeBatchRequest + (*FinalizeBatchResponse)(nil), // 15: mintrpc.FinalizeBatchResponse + (*CancelBatchRequest)(nil), // 16: mintrpc.CancelBatchRequest + (*CancelBatchResponse)(nil), // 17: mintrpc.CancelBatchResponse + (*ListBatchRequest)(nil), // 18: mintrpc.ListBatchRequest + (*ListBatchResponse)(nil), // 19: mintrpc.ListBatchResponse + (*SubscribeMintEventsRequest)(nil), // 20: mintrpc.SubscribeMintEventsRequest + (*MintEvent)(nil), // 21: mintrpc.MintEvent + (taprpc.AssetVersion)(0), // 22: taprpc.AssetVersion + (taprpc.AssetType)(0), // 23: taprpc.AssetType + (*taprpc.AssetMeta)(nil), // 24: taprpc.AssetMeta + (*taprpc.KeyDescriptor)(nil), // 25: taprpc.KeyDescriptor + (*taprpc.ScriptKey)(nil), // 26: taprpc.ScriptKey + (*taprpc.GroupKeyRequest)(nil), // 27: taprpc.GroupKeyRequest + (*taprpc.GroupVirtualTx)(nil), // 28: taprpc.GroupVirtualTx + (*taprpc.ExternalKey)(nil), // 29: taprpc.ExternalKey + (*taprpc.TapscriptFullTree)(nil), // 30: taprpc.TapscriptFullTree + (*taprpc.TapBranch)(nil), // 31: taprpc.TapBranch + (*taprpc.GroupWitness)(nil), // 32: taprpc.GroupWitness } var file_mintrpc_mint_proto_depIdxs = []int32{ - 20, // 0: mintrpc.PendingAsset.asset_version:type_name -> taprpc.AssetVersion - 21, // 1: mintrpc.PendingAsset.asset_type:type_name -> taprpc.AssetType - 22, // 2: mintrpc.PendingAsset.asset_meta:type_name -> taprpc.AssetMeta - 23, // 3: mintrpc.PendingAsset.group_internal_key:type_name -> taprpc.KeyDescriptor - 24, // 4: mintrpc.PendingAsset.script_key:type_name -> taprpc.ScriptKey + 22, // 0: mintrpc.PendingAsset.asset_version:type_name -> taprpc.AssetVersion + 23, // 1: mintrpc.PendingAsset.asset_type:type_name -> taprpc.AssetType + 24, // 2: mintrpc.PendingAsset.asset_meta:type_name -> taprpc.AssetMeta + 25, // 3: mintrpc.PendingAsset.group_internal_key:type_name -> taprpc.KeyDescriptor + 26, // 4: mintrpc.PendingAsset.script_key:type_name -> taprpc.ScriptKey 1, // 5: mintrpc.UnsealedAsset.asset:type_name -> mintrpc.PendingAsset - 25, // 6: mintrpc.UnsealedAsset.group_key_request:type_name -> taprpc.GroupKeyRequest - 26, // 7: mintrpc.UnsealedAsset.group_virtual_tx:type_name -> taprpc.GroupVirtualTx - 20, // 8: mintrpc.MintAsset.asset_version:type_name -> taprpc.AssetVersion - 21, // 9: mintrpc.MintAsset.asset_type:type_name -> taprpc.AssetType - 22, // 10: mintrpc.MintAsset.asset_meta:type_name -> taprpc.AssetMeta - 23, // 11: mintrpc.MintAsset.group_internal_key:type_name -> taprpc.KeyDescriptor - 24, // 12: mintrpc.MintAsset.script_key:type_name -> taprpc.ScriptKey - 27, // 13: mintrpc.MintAsset.external_group_key:type_name -> taprpc.ExternalKey + 27, // 6: mintrpc.UnsealedAsset.group_key_request:type_name -> taprpc.GroupKeyRequest + 28, // 7: mintrpc.UnsealedAsset.group_virtual_tx:type_name -> taprpc.GroupVirtualTx + 22, // 8: mintrpc.MintAsset.asset_version:type_name -> taprpc.AssetVersion + 23, // 9: mintrpc.MintAsset.asset_type:type_name -> taprpc.AssetType + 24, // 10: mintrpc.MintAsset.asset_meta:type_name -> taprpc.AssetMeta + 25, // 11: mintrpc.MintAsset.group_internal_key:type_name -> taprpc.KeyDescriptor + 26, // 12: mintrpc.MintAsset.script_key:type_name -> taprpc.ScriptKey + 29, // 13: mintrpc.MintAsset.external_group_key:type_name -> taprpc.ExternalKey 3, // 14: mintrpc.MintAssetRequest.asset:type_name -> mintrpc.MintAsset 6, // 15: mintrpc.MintAssetResponse.pending_batch:type_name -> mintrpc.MintingBatch 0, // 16: mintrpc.MintingBatch.state:type_name -> mintrpc.BatchState 1, // 17: mintrpc.MintingBatch.assets:type_name -> mintrpc.PendingAsset 6, // 18: mintrpc.VerboseBatch.batch:type_name -> mintrpc.MintingBatch 2, // 19: mintrpc.VerboseBatch.unsealed_assets:type_name -> mintrpc.UnsealedAsset - 28, // 20: mintrpc.FundBatchRequest.full_tree:type_name -> taprpc.TapscriptFullTree - 29, // 21: mintrpc.FundBatchRequest.branch:type_name -> taprpc.TapBranch + 30, // 20: mintrpc.FundBatchRequest.full_tree:type_name -> taprpc.TapscriptFullTree + 31, // 21: mintrpc.FundBatchRequest.branch:type_name -> taprpc.TapBranch 7, // 22: mintrpc.FundBatchResponse.batch:type_name -> mintrpc.VerboseBatch - 30, // 23: mintrpc.SealBatchRequest.group_witnesses:type_name -> taprpc.GroupWitness - 6, // 24: mintrpc.SealBatchResponse.batch:type_name -> mintrpc.MintingBatch - 28, // 25: mintrpc.FinalizeBatchRequest.full_tree:type_name -> taprpc.TapscriptFullTree - 29, // 26: mintrpc.FinalizeBatchRequest.branch:type_name -> taprpc.TapBranch - 6, // 27: mintrpc.FinalizeBatchResponse.batch:type_name -> mintrpc.MintingBatch - 7, // 28: mintrpc.ListBatchResponse.batches:type_name -> mintrpc.VerboseBatch - 0, // 29: mintrpc.MintEvent.batch_state:type_name -> mintrpc.BatchState - 6, // 30: mintrpc.MintEvent.batch:type_name -> mintrpc.MintingBatch - 4, // 31: mintrpc.Mint.MintAsset:input_type -> mintrpc.MintAssetRequest - 8, // 32: mintrpc.Mint.FundBatch:input_type -> mintrpc.FundBatchRequest - 10, // 33: mintrpc.Mint.SealBatch:input_type -> mintrpc.SealBatchRequest - 12, // 34: mintrpc.Mint.FinalizeBatch:input_type -> mintrpc.FinalizeBatchRequest - 14, // 35: mintrpc.Mint.CancelBatch:input_type -> mintrpc.CancelBatchRequest - 16, // 36: mintrpc.Mint.ListBatches:input_type -> mintrpc.ListBatchRequest - 18, // 37: mintrpc.Mint.SubscribeMintEvents:input_type -> mintrpc.SubscribeMintEventsRequest - 5, // 38: mintrpc.Mint.MintAsset:output_type -> mintrpc.MintAssetResponse - 9, // 39: mintrpc.Mint.FundBatch:output_type -> mintrpc.FundBatchResponse - 11, // 40: mintrpc.Mint.SealBatch:output_type -> mintrpc.SealBatchResponse - 13, // 41: mintrpc.Mint.FinalizeBatch:output_type -> mintrpc.FinalizeBatchResponse - 15, // 42: mintrpc.Mint.CancelBatch:output_type -> mintrpc.CancelBatchResponse - 17, // 43: mintrpc.Mint.ListBatches:output_type -> mintrpc.ListBatchResponse - 19, // 44: mintrpc.Mint.SubscribeMintEvents:output_type -> mintrpc.MintEvent - 38, // [38:45] is the sub-list for method output_type - 31, // [31:38] is the sub-list for method input_type - 31, // [31:31] is the sub-list for extension type_name - 31, // [31:31] is the sub-list for extension extendee - 0, // [0:31] is the sub-list for field type_name + 6, // 23: mintrpc.PrepareBatchResponse.batch:type_name -> mintrpc.MintingBatch + 32, // 24: mintrpc.SealBatchRequest.group_witnesses:type_name -> taprpc.GroupWitness + 6, // 25: mintrpc.SealBatchResponse.batch:type_name -> mintrpc.MintingBatch + 30, // 26: mintrpc.FinalizeBatchRequest.full_tree:type_name -> taprpc.TapscriptFullTree + 31, // 27: mintrpc.FinalizeBatchRequest.branch:type_name -> taprpc.TapBranch + 6, // 28: mintrpc.FinalizeBatchResponse.batch:type_name -> mintrpc.MintingBatch + 7, // 29: mintrpc.ListBatchResponse.batches:type_name -> mintrpc.VerboseBatch + 0, // 30: mintrpc.MintEvent.batch_state:type_name -> mintrpc.BatchState + 6, // 31: mintrpc.MintEvent.batch:type_name -> mintrpc.MintingBatch + 4, // 32: mintrpc.Mint.MintAsset:input_type -> mintrpc.MintAssetRequest + 8, // 33: mintrpc.Mint.FundBatch:input_type -> mintrpc.FundBatchRequest + 12, // 34: mintrpc.Mint.SealBatch:input_type -> mintrpc.SealBatchRequest + 10, // 35: mintrpc.Mint.PrepareBatch:input_type -> mintrpc.PrepareBatchRequest + 14, // 36: mintrpc.Mint.FinalizeBatch:input_type -> mintrpc.FinalizeBatchRequest + 16, // 37: mintrpc.Mint.CancelBatch:input_type -> mintrpc.CancelBatchRequest + 18, // 38: mintrpc.Mint.ListBatches:input_type -> mintrpc.ListBatchRequest + 20, // 39: mintrpc.Mint.SubscribeMintEvents:input_type -> mintrpc.SubscribeMintEventsRequest + 5, // 40: mintrpc.Mint.MintAsset:output_type -> mintrpc.MintAssetResponse + 9, // 41: mintrpc.Mint.FundBatch:output_type -> mintrpc.FundBatchResponse + 13, // 42: mintrpc.Mint.SealBatch:output_type -> mintrpc.SealBatchResponse + 11, // 43: mintrpc.Mint.PrepareBatch:output_type -> mintrpc.PrepareBatchResponse + 15, // 44: mintrpc.Mint.FinalizeBatch:output_type -> mintrpc.FinalizeBatchResponse + 17, // 45: mintrpc.Mint.CancelBatch:output_type -> mintrpc.CancelBatchResponse + 19, // 46: mintrpc.Mint.ListBatches:output_type -> mintrpc.ListBatchResponse + 21, // 47: mintrpc.Mint.SubscribeMintEvents:output_type -> mintrpc.MintEvent + 40, // [40:48] is the sub-list for method output_type + 32, // [32:40] is the sub-list for method input_type + 32, // [32:32] is the sub-list for extension type_name + 32, // [32:32] is the sub-list for extension extendee + 0, // [0:32] is the sub-list for field type_name } func init() { file_mintrpc_mint_proto_init() } @@ -1773,11 +1976,11 @@ func file_mintrpc_mint_proto_init() { (*FundBatchRequest_FullTree)(nil), (*FundBatchRequest_Branch)(nil), } - file_mintrpc_mint_proto_msgTypes[11].OneofWrappers = []any{ + file_mintrpc_mint_proto_msgTypes[13].OneofWrappers = []any{ (*FinalizeBatchRequest_FullTree)(nil), (*FinalizeBatchRequest_Branch)(nil), } - file_mintrpc_mint_proto_msgTypes[15].OneofWrappers = []any{ + file_mintrpc_mint_proto_msgTypes[17].OneofWrappers = []any{ (*ListBatchRequest_BatchKey)(nil), (*ListBatchRequest_BatchKeyStr)(nil), } @@ -1787,7 +1990,7 @@ func file_mintrpc_mint_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_mintrpc_mint_proto_rawDesc), len(file_mintrpc_mint_proto_rawDesc)), NumEnums: 1, - NumMessages: 19, + NumMessages: 21, NumExtensions: 0, NumServices: 1, }, diff --git a/taprpc/mintrpc/mint.pb.gw.go b/taprpc/mintrpc/mint.pb.gw.go index 9cca70af22..0f493482f8 100644 --- a/taprpc/mintrpc/mint.pb.gw.go +++ b/taprpc/mintrpc/mint.pb.gw.go @@ -10,6 +10,7 @@ package mintrpc import ( "context" + "errors" "io" "net/http" @@ -24,163 +25,193 @@ import ( ) // Suppress "imported and not used" errors -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray -var _ = metadata.Join +var ( + _ codes.Code + _ io.Reader + _ status.Status + _ = errors.New + _ = runtime.String + _ = utilities.NewDoubleArray + _ = metadata.Join +) func request_Mint_MintAsset_0(ctx context.Context, marshaler runtime.Marshaler, client MintClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq MintAssetRequest - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq MintAssetRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - + if req.Body != nil { + _, _ = io.Copy(io.Discard, req.Body) + } msg, err := client.MintAsset(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err - } func local_request_Mint_MintAsset_0(ctx context.Context, marshaler runtime.Marshaler, server MintServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq MintAssetRequest - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq MintAssetRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - msg, err := server.MintAsset(ctx, &protoReq) return msg, metadata, err - } func request_Mint_FundBatch_0(ctx context.Context, marshaler runtime.Marshaler, client MintClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq FundBatchRequest - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq FundBatchRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - + if req.Body != nil { + _, _ = io.Copy(io.Discard, req.Body) + } msg, err := client.FundBatch(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err - } func local_request_Mint_FundBatch_0(ctx context.Context, marshaler runtime.Marshaler, server MintServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq FundBatchRequest - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq FundBatchRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - msg, err := server.FundBatch(ctx, &protoReq) return msg, metadata, err - } func request_Mint_SealBatch_0(ctx context.Context, marshaler runtime.Marshaler, client MintClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq SealBatchRequest - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq SealBatchRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - + if req.Body != nil { + _, _ = io.Copy(io.Discard, req.Body) + } msg, err := client.SealBatch(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err - } func local_request_Mint_SealBatch_0(ctx context.Context, marshaler runtime.Marshaler, server MintServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq SealBatchRequest - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq SealBatchRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - msg, err := server.SealBatch(ctx, &protoReq) return msg, metadata, err - } -func request_Mint_FinalizeBatch_0(ctx context.Context, marshaler runtime.Marshaler, client MintClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq FinalizeBatchRequest - var metadata runtime.ServerMetadata +func request_Mint_PrepareBatch_0(ctx context.Context, marshaler runtime.Marshaler, client MintClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var ( + protoReq PrepareBatchRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if req.Body != nil { + _, _ = io.Copy(io.Discard, req.Body) + } + msg, err := client.PrepareBatch(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err +} - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { +func local_request_Mint_PrepareBatch_0(ctx context.Context, marshaler runtime.Marshaler, server MintServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var ( + protoReq PrepareBatchRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } + msg, err := server.PrepareBatch(ctx, &protoReq) + return msg, metadata, err +} +func request_Mint_FinalizeBatch_0(ctx context.Context, marshaler runtime.Marshaler, client MintClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var ( + protoReq FinalizeBatchRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if req.Body != nil { + _, _ = io.Copy(io.Discard, req.Body) + } msg, err := client.FinalizeBatch(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err - } func local_request_Mint_FinalizeBatch_0(ctx context.Context, marshaler runtime.Marshaler, server MintServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq FinalizeBatchRequest - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq FinalizeBatchRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - msg, err := server.FinalizeBatch(ctx, &protoReq) return msg, metadata, err - } func request_Mint_CancelBatch_0(ctx context.Context, marshaler runtime.Marshaler, client MintClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq CancelBatchRequest - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq CancelBatchRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - + if req.Body != nil { + _, _ = io.Copy(io.Discard, req.Body) + } msg, err := client.CancelBatch(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err - } func local_request_Mint_CancelBatch_0(ctx context.Context, marshaler runtime.Marshaler, server MintServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq CancelBatchRequest - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq CancelBatchRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - msg, err := server.CancelBatch(ctx, &protoReq) return msg, metadata, err - } -var ( - filter_Mint_ListBatches_0 = &utilities.DoubleArray{Encoding: map[string]int{"batch_key": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} -) +var filter_Mint_ListBatches_0 = &utilities.DoubleArray{Encoding: map[string]int{"batch_key": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} func request_Mint_ListBatches_0(ctx context.Context, marshaler runtime.Marshaler, client MintClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq ListBatchRequest - var metadata runtime.ServerMetadata - var ( - val string - ok bool - err error - _ = err + protoReq ListBatchRequest + metadata runtime.ServerMetadata + err error ) - - val, ok = pathParams["batch_key"] + if req.Body != nil { + _, _ = io.Copy(io.Discard, req.Body) + } + val, ok := pathParams["batch_key"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "batch_key") } - if protoReq.Filter == nil { protoReq.Filter = &ListBatchRequest_BatchKey{} } else if _, ok := protoReq.Filter.(*ListBatchRequest_BatchKey); !ok { @@ -190,35 +221,26 @@ func request_Mint_ListBatches_0(ctx context.Context, marshaler runtime.Marshaler if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "batch_key", err) } - if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Mint_ListBatches_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - msg, err := client.ListBatches(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err - } func local_request_Mint_ListBatches_0(ctx context.Context, marshaler runtime.Marshaler, server MintServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq ListBatchRequest - var metadata runtime.ServerMetadata - var ( - val string - ok bool - err error - _ = err + protoReq ListBatchRequest + metadata runtime.ServerMetadata + err error ) - - val, ok = pathParams["batch_key"] + val, ok := pathParams["batch_key"] if !ok { return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "batch_key") } - if protoReq.Filter == nil { protoReq.Filter = &ListBatchRequest_BatchKey{} } else if _, ok := protoReq.Filter.(*ListBatchRequest_BatchKey); !ok { @@ -228,27 +250,27 @@ func local_request_Mint_ListBatches_0(ctx context.Context, marshaler runtime.Mar if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "batch_key", err) } - if err := req.ParseForm(); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Mint_ListBatches_0); err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - msg, err := server.ListBatches(ctx, &protoReq) return msg, metadata, err - } func request_Mint_SubscribeMintEvents_0(ctx context.Context, marshaler runtime.Marshaler, client MintClient, req *http.Request, pathParams map[string]string) (Mint_SubscribeMintEventsClient, runtime.ServerMetadata, error) { - var protoReq SubscribeMintEventsRequest - var metadata runtime.ServerMetadata - - if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && err != io.EOF { + var ( + protoReq SubscribeMintEventsRequest + metadata runtime.ServerMetadata + ) + if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) { return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) } - + if req.Body != nil { + _, _ = io.Copy(io.Discard, req.Body) + } stream, err := client.SubscribeMintEvents(ctx, &protoReq) if err != nil { return nil, metadata, err @@ -259,24 +281,21 @@ func request_Mint_SubscribeMintEvents_0(ctx context.Context, marshaler runtime.M } metadata.HeaderMD = header return stream, metadata, nil - } // RegisterMintHandlerServer registers the http handlers for service Mint to "mux". // UnaryRPC :call MintServer directly. // StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. // Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterMintHandlerFromEndpoint instead. +// GRPC interceptors will not work for this type of registration. To use interceptors, you must use the "runtime.WithMiddlewares" option in the "runtime.NewServeMux" call. func RegisterMintHandlerServer(ctx context.Context, mux *runtime.ServeMux, server MintServer) error { - - mux.Handle("POST", pattern_Mint_MintAsset_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_Mint_MintAsset_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/mintrpc.Mint/MintAsset", runtime.WithHTTPPathPattern("/v1/taproot-assets/assets")) + annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/mintrpc.Mint/MintAsset", runtime.WithHTTPPathPattern("/v1/taproot-assets/assets")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -288,20 +307,15 @@ func RegisterMintHandlerServer(ctx context.Context, mux *runtime.ServeMux, serve runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_Mint_MintAsset_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("POST", pattern_Mint_FundBatch_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_Mint_FundBatch_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/mintrpc.Mint/FundBatch", runtime.WithHTTPPathPattern("/v1/taproot-assets/assets/mint/fund")) + annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/mintrpc.Mint/FundBatch", runtime.WithHTTPPathPattern("/v1/taproot-assets/assets/mint/fund")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -313,20 +327,15 @@ func RegisterMintHandlerServer(ctx context.Context, mux *runtime.ServeMux, serve runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_Mint_FundBatch_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("POST", pattern_Mint_SealBatch_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_Mint_SealBatch_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/mintrpc.Mint/SealBatch", runtime.WithHTTPPathPattern("/v1/taproot-assets/assets/mint/seal")) + annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/mintrpc.Mint/SealBatch", runtime.WithHTTPPathPattern("/v1/taproot-assets/assets/mint/seal")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -338,20 +347,35 @@ func RegisterMintHandlerServer(ctx context.Context, mux *runtime.ServeMux, serve runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_Mint_SealBatch_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("POST", pattern_Mint_FinalizeBatch_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_Mint_PrepareBatch_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/mintrpc.Mint/FinalizeBatch", runtime.WithHTTPPathPattern("/v1/taproot-assets/assets/mint/finalize")) + annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/mintrpc.Mint/PrepareBatch", runtime.WithHTTPPathPattern("/v1/taproot-assets/assets/mint/prepare")) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Mint_PrepareBatch_0(annotatedContext, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) + if err != nil { + runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) + return + } + forward_Mint_PrepareBatch_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) + mux.Handle(http.MethodPost, pattern_Mint_FinalizeBatch_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/mintrpc.Mint/FinalizeBatch", runtime.WithHTTPPathPattern("/v1/taproot-assets/assets/mint/finalize")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -363,20 +387,15 @@ func RegisterMintHandlerServer(ctx context.Context, mux *runtime.ServeMux, serve runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_Mint_FinalizeBatch_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("POST", pattern_Mint_CancelBatch_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_Mint_CancelBatch_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/mintrpc.Mint/CancelBatch", runtime.WithHTTPPathPattern("/v1/taproot-assets/assets/mint/cancel")) + annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/mintrpc.Mint/CancelBatch", runtime.WithHTTPPathPattern("/v1/taproot-assets/assets/mint/cancel")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -388,20 +407,15 @@ func RegisterMintHandlerServer(ctx context.Context, mux *runtime.ServeMux, serve runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_Mint_CancelBatch_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Mint_ListBatches_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodGet, pattern_Mint_ListBatches_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateIncomingContext(ctx, mux, req, "/mintrpc.Mint/ListBatches", runtime.WithHTTPPathPattern("/v1/taproot-assets/assets/mint/batches/{batch_key}")) + annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/mintrpc.Mint/ListBatches", runtime.WithHTTPPathPattern("/v1/taproot-assets/assets/mint/batches/{batch_key}")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -413,12 +427,10 @@ func RegisterMintHandlerServer(ctx context.Context, mux *runtime.ServeMux, serve runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_Mint_ListBatches_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - mux.Handle("POST", pattern_Mint_SubscribeMintEvents_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_Mint_SubscribeMintEvents_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { err := status.Error(codes.Unimplemented, "streaming calls are not yet supported in the in-process transport") _, outboundMarshaler := runtime.MarshalerForRequest(mux, req) runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) @@ -449,7 +461,6 @@ func RegisterMintHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, } }() }() - return RegisterMintHandler(ctx, mux, conn) } @@ -463,16 +474,13 @@ func RegisterMintHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc. // to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "MintClient". // Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "MintClient" // doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "MintClient" to call the correct interceptors. +// "MintClient" to call the correct interceptors. This client ignores the HTTP middlewares. func RegisterMintHandlerClient(ctx context.Context, mux *runtime.ServeMux, client MintClient) error { - - mux.Handle("POST", pattern_Mint_MintAsset_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_Mint_MintAsset_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/mintrpc.Mint/MintAsset", runtime.WithHTTPPathPattern("/v1/taproot-assets/assets")) + annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/mintrpc.Mint/MintAsset", runtime.WithHTTPPathPattern("/v1/taproot-assets/assets")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -483,18 +491,13 @@ func RegisterMintHandlerClient(ctx context.Context, mux *runtime.ServeMux, clien runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_Mint_MintAsset_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("POST", pattern_Mint_FundBatch_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_Mint_FundBatch_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/mintrpc.Mint/FundBatch", runtime.WithHTTPPathPattern("/v1/taproot-assets/assets/mint/fund")) + annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/mintrpc.Mint/FundBatch", runtime.WithHTTPPathPattern("/v1/taproot-assets/assets/mint/fund")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -505,18 +508,13 @@ func RegisterMintHandlerClient(ctx context.Context, mux *runtime.ServeMux, clien runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_Mint_FundBatch_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("POST", pattern_Mint_SealBatch_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_Mint_SealBatch_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/mintrpc.Mint/SealBatch", runtime.WithHTTPPathPattern("/v1/taproot-assets/assets/mint/seal")) + annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/mintrpc.Mint/SealBatch", runtime.WithHTTPPathPattern("/v1/taproot-assets/assets/mint/seal")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -527,18 +525,30 @@ func RegisterMintHandlerClient(ctx context.Context, mux *runtime.ServeMux, clien runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_Mint_SealBatch_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("POST", pattern_Mint_FinalizeBatch_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_Mint_PrepareBatch_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/mintrpc.Mint/PrepareBatch", runtime.WithHTTPPathPattern("/v1/taproot-assets/assets/mint/prepare")) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Mint_PrepareBatch_0(annotatedContext, inboundMarshaler, client, req, pathParams) + annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md) + if err != nil { + runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) + return + } + forward_Mint_PrepareBatch_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) + mux.Handle(http.MethodPost, pattern_Mint_FinalizeBatch_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/mintrpc.Mint/FinalizeBatch", runtime.WithHTTPPathPattern("/v1/taproot-assets/assets/mint/finalize")) + annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/mintrpc.Mint/FinalizeBatch", runtime.WithHTTPPathPattern("/v1/taproot-assets/assets/mint/finalize")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -549,18 +559,13 @@ func RegisterMintHandlerClient(ctx context.Context, mux *runtime.ServeMux, clien runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_Mint_FinalizeBatch_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("POST", pattern_Mint_CancelBatch_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_Mint_CancelBatch_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/mintrpc.Mint/CancelBatch", runtime.WithHTTPPathPattern("/v1/taproot-assets/assets/mint/cancel")) + annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/mintrpc.Mint/CancelBatch", runtime.WithHTTPPathPattern("/v1/taproot-assets/assets/mint/cancel")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -571,18 +576,13 @@ func RegisterMintHandlerClient(ctx context.Context, mux *runtime.ServeMux, clien runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_Mint_CancelBatch_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Mint_ListBatches_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodGet, pattern_Mint_ListBatches_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/mintrpc.Mint/ListBatches", runtime.WithHTTPPathPattern("/v1/taproot-assets/assets/mint/batches/{batch_key}")) + annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/mintrpc.Mint/ListBatches", runtime.WithHTTPPathPattern("/v1/taproot-assets/assets/mint/batches/{batch_key}")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -593,18 +593,13 @@ func RegisterMintHandlerClient(ctx context.Context, mux *runtime.ServeMux, clien runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_Mint_ListBatches_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("POST", pattern_Mint_SubscribeMintEvents_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + mux.Handle(http.MethodPost, pattern_Mint_SubscribeMintEvents_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - var err error - var annotatedContext context.Context - annotatedContext, err = runtime.AnnotateContext(ctx, mux, req, "/mintrpc.Mint/SubscribeMintEvents", runtime.WithHTTPPathPattern("/v1/taproot-assets/events/asset-mint")) + annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/mintrpc.Mint/SubscribeMintEvents", runtime.WithHTTPPathPattern("/v1/taproot-assets/events/asset-mint")) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -615,42 +610,29 @@ func RegisterMintHandlerClient(ctx context.Context, mux *runtime.ServeMux, clien runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err) return } - forward_Mint_SubscribeMintEvents_0(annotatedContext, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...) - }) - return nil } var ( - pattern_Mint_MintAsset_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "taproot-assets", "assets"}, "")) - - pattern_Mint_FundBatch_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "taproot-assets", "assets", "mint", "fund"}, "")) - - pattern_Mint_SealBatch_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "taproot-assets", "assets", "mint", "seal"}, "")) - - pattern_Mint_FinalizeBatch_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "taproot-assets", "assets", "mint", "finalize"}, "")) - - pattern_Mint_CancelBatch_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "taproot-assets", "assets", "mint", "cancel"}, "")) - - pattern_Mint_ListBatches_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4, 1, 0, 4, 1, 5, 5}, []string{"v1", "taproot-assets", "assets", "mint", "batches", "batch_key"}, "")) - + pattern_Mint_MintAsset_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "taproot-assets", "assets"}, "")) + pattern_Mint_FundBatch_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "taproot-assets", "assets", "mint", "fund"}, "")) + pattern_Mint_SealBatch_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "taproot-assets", "assets", "mint", "seal"}, "")) + pattern_Mint_PrepareBatch_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "taproot-assets", "assets", "mint", "prepare"}, "")) + pattern_Mint_FinalizeBatch_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "taproot-assets", "assets", "mint", "finalize"}, "")) + pattern_Mint_CancelBatch_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"v1", "taproot-assets", "assets", "mint", "cancel"}, "")) + pattern_Mint_ListBatches_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4, 1, 0, 4, 1, 5, 5}, []string{"v1", "taproot-assets", "assets", "mint", "batches", "batch_key"}, "")) pattern_Mint_SubscribeMintEvents_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"v1", "taproot-assets", "events", "asset-mint"}, "")) ) var ( - forward_Mint_MintAsset_0 = runtime.ForwardResponseMessage - - forward_Mint_FundBatch_0 = runtime.ForwardResponseMessage - - forward_Mint_SealBatch_0 = runtime.ForwardResponseMessage - - forward_Mint_FinalizeBatch_0 = runtime.ForwardResponseMessage - - forward_Mint_CancelBatch_0 = runtime.ForwardResponseMessage - - forward_Mint_ListBatches_0 = runtime.ForwardResponseMessage - + forward_Mint_MintAsset_0 = runtime.ForwardResponseMessage + forward_Mint_FundBatch_0 = runtime.ForwardResponseMessage + forward_Mint_SealBatch_0 = runtime.ForwardResponseMessage + forward_Mint_PrepareBatch_0 = runtime.ForwardResponseMessage + forward_Mint_FinalizeBatch_0 = runtime.ForwardResponseMessage + forward_Mint_CancelBatch_0 = runtime.ForwardResponseMessage + forward_Mint_ListBatches_0 = runtime.ForwardResponseMessage forward_Mint_SubscribeMintEvents_0 = runtime.ForwardResponseStream ) diff --git a/taprpc/mintrpc/mint.pb.json.go b/taprpc/mintrpc/mint.pb.json.go index aa8e2b8245..7eaac8efaa 100644 --- a/taprpc/mintrpc/mint.pb.json.go +++ b/taprpc/mintrpc/mint.pb.json.go @@ -96,6 +96,31 @@ func RegisterMintJSONCallbacks(registry map[string]func(ctx context.Context, callback(string(respBytes), nil) } + registry["mintrpc.Mint.PrepareBatch"] = func(ctx context.Context, + conn *grpc.ClientConn, reqJSON string, callback func(string, error)) { + + req := &PrepareBatchRequest{} + err := marshaler.Unmarshal([]byte(reqJSON), req) + if err != nil { + callback("", err) + return + } + + client := NewMintClient(conn) + resp, err := client.PrepareBatch(ctx, req) + if err != nil { + callback("", err) + return + } + + respBytes, err := marshaler.Marshal(resp) + if err != nil { + callback("", err) + return + } + callback(string(respBytes), nil) + } + registry["mintrpc.Mint.FinalizeBatch"] = func(ctx context.Context, conn *grpc.ClientConn, reqJSON string, callback func(string, error)) { diff --git a/taprpc/mintrpc/mint.proto b/taprpc/mintrpc/mint.proto index 3268e93ef1..b1634178f0 100644 --- a/taprpc/mintrpc/mint.proto +++ b/taprpc/mintrpc/mint.proto @@ -34,6 +34,13 @@ service Mint { */ rpc SealBatch (SealBatchRequest) returns (SealBatchResponse); + /* tapcli `assets mint prepare` + PrepareBatch commits the assets into a caller-authored anchor PSBT and + returns the packet for external signing. The batch remains paused until + FinalizeBatch is called with the signed packet. + */ + rpc PrepareBatch (PrepareBatchRequest) returns (PrepareBatchResponse); + /* tapcli: `assets mint finalize` FinalizeBatch will attempt to finalize the current pending batch. */ @@ -285,6 +292,18 @@ message MintingBatch { // The genesis transaction as a PSBT packet. Only populated if the batch has // been committed. bytes batch_psbt = 7; + + // The latest prepared or broadcast custom-anchor wallet lease renewal + // degradation. Empty after a successful renewal or wallet acceptance. + string custom_anchor_lease_error = 8; + + // The latest ambiguous publication error for a custom-anchor transaction + // that remains watched and retried byte-identically. + string custom_anchor_publish_error = 9; + + // Historical custom-anchor key health requiring operator intervention. + // Empty when the managed anchor key is healthy or was repaired. + string custom_anchor_key_error = 10; } message VerboseBatch { @@ -333,6 +352,25 @@ message FundBatchRequest { // A TapBranch that represents a Tapscript tree managed externally. taprpc.TapBranch branch = 4; } + + // An optional caller-funded anchor PSBT. Input zero remains the asset + // genesis point and the packet must not contain signatures yet. The + // selected asset anchor output must not contain PSBT_OUT_TAP_TREE because + // PrepareBatch replaces its script tree with the asset commitment and the + // optional batch_sibling. + bytes anchor_psbt = 5; + + // The output that will receive the Taproot Asset commitment. + uint32 asset_anchor_output_index = 6; + + // The index of an existing change output in anchor_psbt. + int32 change_output_index = 7; + + // Set when anchor_psbt has no change output. + bool no_change_output = 8; + + // The supply commitment output in anchor_psbt, when applicable. + optional uint32 pre_commit_output_index = 9; } message FundBatchResponse { @@ -340,6 +378,19 @@ message FundBatchResponse { VerboseBatch batch = 1; } +message PrepareBatchRequest { + /* + If true, then the assets currently in the batch won't be returned in the + response. + */ + bool short_response = 1; +} + +message PrepareBatchResponse { + // The prepared batch, including the commitment-mutated anchor PSBT. + MintingBatch batch = 1; +} + message SealBatchRequest { /* If true, then the assets currently in the batch won't be returned in the @@ -390,6 +441,10 @@ message FinalizeBatchRequest { // A TapBranch that represents a Tapscript tree managed externally. taprpc.TapBranch branch = 4; } + + // The externally signed packet returned by PrepareBatch. All non-signing + // fields must be identical to the prepared packet. + bytes signed_psbt = 5; } message FinalizeBatchResponse { diff --git a/taprpc/mintrpc/mint.swagger.json b/taprpc/mintrpc/mint.swagger.json index 6d76db5ed0..2d80ee0053 100644 --- a/taprpc/mintrpc/mint.swagger.json +++ b/taprpc/mintrpc/mint.swagger.json @@ -195,6 +195,39 @@ ] } }, + "/v1/taproot-assets/assets/mint/prepare": { + "post": { + "summary": "tapcli `assets mint prepare`\nPrepareBatch commits the assets into a caller-authored anchor PSBT and\nreturns the packet for external signing. The batch remains paused until\nFinalizeBatch is called with the signed packet.", + "operationId": "Mint_PrepareBatch", + "responses": { + "200": { + "description": "A successful response.", + "schema": { + "$ref": "#/definitions/mintrpcPrepareBatchResponse" + } + }, + "default": { + "description": "An unexpected error response.", + "schema": { + "$ref": "#/definitions/rpcStatus" + } + } + }, + "parameters": [ + { + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/mintrpcPrepareBatchRequest" + } + } + ], + "tags": [ + "Mint" + ] + } + }, "/v1/taproot-assets/assets/mint/seal": { "post": { "summary": "tapcli `assets mint seal`\nSealBatch will attempt to seal the current pending batch by creating and\nvalidating asset group witness for all assets in the batch. If a witness\nis not provided, a signature will be derived to serve as the witness. This\nRPC is only needed if any assets in the batch have a custom asset group key\nthat require an external signer. Otherwise, FinalizeBatch can be called\ndirectly.", @@ -319,6 +352,11 @@ "branch": { "$ref": "#/definitions/taprpcTapBranch", "description": "A TapBranch that represents a Tapscript tree managed externally." + }, + "signed_psbt": { + "type": "string", + "format": "byte", + "description": "The externally signed packet returned by PrepareBatch. All non-signing\nfields must be identical to the prepared packet." } } }, @@ -350,6 +388,30 @@ "branch": { "$ref": "#/definitions/taprpcTapBranch", "description": "A TapBranch that represents a Tapscript tree managed externally." + }, + "anchor_psbt": { + "type": "string", + "format": "byte", + "description": "An optional caller-funded anchor PSBT. Input zero remains the asset\ngenesis point and the packet must not contain signatures yet. The\nselected asset anchor output must not contain PSBT_OUT_TAP_TREE because\nPrepareBatch replaces its script tree with the asset commitment and the\noptional batch_sibling." + }, + "asset_anchor_output_index": { + "type": "integer", + "format": "int64", + "description": "The output that will receive the Taproot Asset commitment." + }, + "change_output_index": { + "type": "integer", + "format": "int32", + "description": "The index of an existing change output in anchor_psbt." + }, + "no_change_output": { + "type": "boolean", + "description": "Set when anchor_psbt has no change output." + }, + "pre_commit_output_index": { + "type": "integer", + "format": "int64", + "description": "The supply commitment output in anchor_psbt, when applicable." } } }, @@ -525,6 +587,18 @@ "type": "string", "format": "byte", "description": "The genesis transaction as a PSBT packet. Only populated if the batch has\nbeen committed." + }, + "custom_anchor_lease_error": { + "type": "string", + "description": "The latest prepared or broadcast custom-anchor wallet lease renewal\ndegradation. Empty after a successful renewal or wallet acceptance." + }, + "custom_anchor_publish_error": { + "type": "string", + "description": "The latest ambiguous publication error for a custom-anchor transaction\nthat remains watched and retried byte-identically." + }, + "custom_anchor_key_error": { + "type": "string", + "description": "Historical custom-anchor key health requiring operator intervention.\nEmpty when the managed anchor key is healthy or was repaired." } } }, @@ -580,6 +654,24 @@ } } }, + "mintrpcPrepareBatchRequest": { + "type": "object", + "properties": { + "short_response": { + "type": "boolean", + "description": "If true, then the assets currently in the batch won't be returned in the\nresponse." + } + } + }, + "mintrpcPrepareBatchResponse": { + "type": "object", + "properties": { + "batch": { + "$ref": "#/definitions/mintrpcMintingBatch", + "description": "The prepared batch, including the commitment-mutated anchor PSBT." + } + } + }, "mintrpcSealBatchRequest": { "type": "object", "properties": { diff --git a/taprpc/mintrpc/mint.yaml b/taprpc/mintrpc/mint.yaml index 0ec2db4a97..09848e8f5f 100644 --- a/taprpc/mintrpc/mint.yaml +++ b/taprpc/mintrpc/mint.yaml @@ -15,6 +15,10 @@ http: post: "/v1/taproot-assets/assets/mint/seal" body: "*" + - selector: mintrpc.Mint.PrepareBatch + post: "/v1/taproot-assets/assets/mint/prepare" + body: "*" + - selector: mintrpc.Mint.FinalizeBatch post: "/v1/taproot-assets/assets/mint/finalize" body: "*" diff --git a/taprpc/mintrpc/mint_grpc.pb.go b/taprpc/mintrpc/mint_grpc.pb.go index b3ee711ab1..a02e4858f9 100644 --- a/taprpc/mintrpc/mint_grpc.pb.go +++ b/taprpc/mintrpc/mint_grpc.pb.go @@ -39,6 +39,11 @@ type MintClient interface { // that require an external signer. Otherwise, FinalizeBatch can be called // directly. SealBatch(ctx context.Context, in *SealBatchRequest, opts ...grpc.CallOption) (*SealBatchResponse, error) + // tapcli `assets mint prepare` + // PrepareBatch commits the assets into a caller-authored anchor PSBT and + // returns the packet for external signing. The batch remains paused until + // FinalizeBatch is called with the signed packet. + PrepareBatch(ctx context.Context, in *PrepareBatchRequest, opts ...grpc.CallOption) (*PrepareBatchResponse, error) // tapcli: `assets mint finalize` // FinalizeBatch will attempt to finalize the current pending batch. FinalizeBatch(ctx context.Context, in *FinalizeBatchRequest, opts ...grpc.CallOption) (*FinalizeBatchResponse, error) @@ -90,6 +95,15 @@ func (c *mintClient) SealBatch(ctx context.Context, in *SealBatchRequest, opts . return out, nil } +func (c *mintClient) PrepareBatch(ctx context.Context, in *PrepareBatchRequest, opts ...grpc.CallOption) (*PrepareBatchResponse, error) { + out := new(PrepareBatchResponse) + err := c.cc.Invoke(ctx, "/mintrpc.Mint/PrepareBatch", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + func (c *mintClient) FinalizeBatch(ctx context.Context, in *FinalizeBatchRequest, opts ...grpc.CallOption) (*FinalizeBatchResponse, error) { out := new(FinalizeBatchResponse) err := c.cc.Invoke(ctx, "/mintrpc.Mint/FinalizeBatch", in, out, opts...) @@ -174,6 +188,11 @@ type MintServer interface { // that require an external signer. Otherwise, FinalizeBatch can be called // directly. SealBatch(context.Context, *SealBatchRequest) (*SealBatchResponse, error) + // tapcli `assets mint prepare` + // PrepareBatch commits the assets into a caller-authored anchor PSBT and + // returns the packet for external signing. The batch remains paused until + // FinalizeBatch is called with the signed packet. + PrepareBatch(context.Context, *PrepareBatchRequest) (*PrepareBatchResponse, error) // tapcli: `assets mint finalize` // FinalizeBatch will attempt to finalize the current pending batch. FinalizeBatch(context.Context, *FinalizeBatchRequest) (*FinalizeBatchResponse, error) @@ -204,6 +223,9 @@ func (UnimplementedMintServer) FundBatch(context.Context, *FundBatchRequest) (*F func (UnimplementedMintServer) SealBatch(context.Context, *SealBatchRequest) (*SealBatchResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method SealBatch not implemented") } +func (UnimplementedMintServer) PrepareBatch(context.Context, *PrepareBatchRequest) (*PrepareBatchResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method PrepareBatch not implemented") +} func (UnimplementedMintServer) FinalizeBatch(context.Context, *FinalizeBatchRequest) (*FinalizeBatchResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method FinalizeBatch not implemented") } @@ -283,6 +305,24 @@ func _Mint_SealBatch_Handler(srv interface{}, ctx context.Context, dec func(inte return interceptor(ctx, in, info, handler) } +func _Mint_PrepareBatch_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(PrepareBatchRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MintServer).PrepareBatch(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/mintrpc.Mint/PrepareBatch", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MintServer).PrepareBatch(ctx, req.(*PrepareBatchRequest)) + } + return interceptor(ctx, in, info, handler) +} + func _Mint_FinalizeBatch_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(FinalizeBatchRequest) if err := dec(in); err != nil { @@ -377,6 +417,10 @@ var Mint_ServiceDesc = grpc.ServiceDesc{ MethodName: "SealBatch", Handler: _Mint_SealBatch_Handler, }, + { + MethodName: "PrepareBatch", + Handler: _Mint_PrepareBatch_Handler, + }, { MethodName: "FinalizeBatch", Handler: _Mint_FinalizeBatch_Handler, diff --git a/taprpc/perms.go b/taprpc/perms.go index b9e30bc4c9..84093de8ff 100644 --- a/taprpc/perms.go +++ b/taprpc/perms.go @@ -127,6 +127,10 @@ var ( Entity: "assets", Action: "write", }}, + "/assetwalletrpc.AssetWallet/GetCommitVirtualPsbtsStatus": {{ + Entity: "assets", + Action: "read", + }}, "/assetwalletrpc.AssetWallet/PublishAndLogTransfer": {{ Entity: "assets", Action: "write", @@ -183,6 +187,10 @@ var ( Entity: "mint", Action: "write", }}, + "/mintrpc.Mint/PrepareBatch": {{ + Entity: "mint", + Action: "write", + }}, "/mintrpc.Mint/FinalizeBatch": {{ Entity: "mint", Action: "write", diff --git a/universe/supplycommit/README.md b/universe/supplycommit/README.md index d64e7654c0..d0b19bb82a 100644 --- a/universe/supplycommit/README.md +++ b/universe/supplycommit/README.md @@ -77,6 +77,16 @@ triggers the commitment process, moving through states for tree creation finalization (`CommitFinalizeState`) upon confirmation, before returning to the `DefaultState`. +**Idle ticks:** when `universe.supply-idle-commit-interval` is non-zero, the +manager sends an `IdleTickEvent{BlockHeight}` to the state machine of every +locally controlled supply commitment on each new block. In `DefaultState`, if +the latest commitment is confirmed and at least `interval` blocks old, the +machine begins a frozen transition that spends the latest commitment (binding +any dangling updates) and runs the normal commitment cycle, even with no +updates. This keeps the on-chain commitment fresh. In `UpdatesPendingState` the +event publishes staged updates when `universe.supply-auto-publish-pending` is +set, or resumes an interrupted empty transition. + ### States and Transitions ```mermaid @@ -86,6 +96,7 @@ stateDiagram-v2 [*] --> DefaultState: Initialize DefaultState --> UpdatesPendingState: SupplyUpdateEvent + DefaultState --> CommitTreeCreateState: IdleTickEvent
(commitment older than interval) UpdatesPendingState --> CommitTreeCreateState: CommitTickEvent state CommitmentCycle { diff --git a/universe/supplycommit/broadcast_recovery.go b/universe/supplycommit/broadcast_recovery.go new file mode 100644 index 0000000000..a5390c1142 --- /dev/null +++ b/universe/supplycommit/broadcast_recovery.go @@ -0,0 +1,107 @@ +package supplycommit + +import ( + "context" + "fmt" + + "github.com/btcsuite/btcd/wire" + "github.com/lightninglabs/taproot-assets/fn" + "github.com/lightninglabs/taproot-assets/tapgarden" +) + +const ( + // maxCommitConfLookback limits how far back we scan for a commitment + // transaction that confirmed while tapd was down. + maxCommitConfLookback = 512 +) + +// findCommitConfirmation scans recent chain history for a commitment +// transaction. This covers restarts that miss the RegisterConf notification +// because the transaction confirmed while the daemon was stopped. +func findCommitConfirmation(ctx context.Context, + chain tapgarden.ChainBridge, commitTx *wire.MsgTx) (fn.Option[*ConfEvent], + error) { + + if commitTx == nil { + return fn.None[*ConfEvent](), nil + } + + txid := commitTx.TxHash() + tip, err := chain.CurrentHeight(ctx) + if err != nil { + return fn.None[*ConfEvent](), fmt.Errorf("unable to get chain "+ + "tip: %w", err) + } + + start := uint32(1) + if tip > maxCommitConfLookback { + start = tip - maxCommitConfLookback + 1 + } + + for height := tip; height >= start; height-- { + block, err := chain.GetBlockByHeight(ctx, int64(height)) + if err != nil { + return fn.None[*ConfEvent](), fmt.Errorf( + "unable to fetch block %d: %w", height, err, + ) + } + + for idx, blockTx := range block.Transactions { + if blockTx.TxHash() != txid { + continue + } + + return fn.Some(&ConfEvent{ + Tx: blockTx, + TxIndex: uint32(idx), + BlockHeight: height, + Block: block, + }), nil + } + } + + return fn.None[*ConfEvent](), nil +} + +// tryRecoverBuriedBroadcast finalizes an in-flight broadcast when its +// commitment transaction is already buried on chain. +func tryRecoverBuriedBroadcast(ctx context.Context, + c *CommitBroadcastState, env *Environment) (*StateTransition, bool, + error) { + + commitTx := c.SupplyTransition.NewCommitment.Txn + if commitTx == nil { + return nil, false, nil + } + + confOpt, err := findCommitConfirmation(ctx, env.Chain, commitTx) + if err != nil { + return nil, false, err + } + if confOpt.IsNone() { + return nil, false, nil + } + conf, err := confOpt.UnwrapOrErr(fmt.Errorf("missing confirmation")) + if err != nil { + return nil, false, nil + } + + tip, err := env.Chain.CurrentHeight(ctx) + if err != nil { + return nil, false, fmt.Errorf("unable to get chain tip: %w", err) + } + + burialDepth := commitBurialDepth(env) + if !isCommitBuried(tip, conf.BlockHeight, burialDepth) { + return nil, false, nil + } + + transition, err := transitionForBuriedConf( + ctx, env, c.SupplyTransition, conf, + ) + if err != nil { + return nil, false, err + } + + return transition, true, nil +} diff --git a/universe/supplycommit/broadcast_recovery_test.go b/universe/supplycommit/broadcast_recovery_test.go new file mode 100644 index 0000000000..94c67dd585 --- /dev/null +++ b/universe/supplycommit/broadcast_recovery_test.go @@ -0,0 +1,155 @@ +package supplycommit + +import ( + "context" + "fmt" + "testing" + + "github.com/btcsuite/btcd/wire" + "github.com/lightninglabs/taproot-assets/tapgarden" + "github.com/stretchr/testify/require" +) + +func TestFindCommitConfirmation(t *testing.T) { + commitTx := wire.NewMsgTx(2) + commitTx.AddTxOut(&wire.TxOut{Value: 1000, PkScript: []byte{0x51}}) + + header := wire.BlockHeader{} + block := wire.NewMsgBlock(&header) + block.AddTransaction(wire.NewMsgTx(2)) + block.AddTransaction(commitTx) + + chain := tapgarden.NewMockChainBridge() + chain.BlocksByHeight = map[int64]*wire.MsgBlock{} + for height := int64(1); height <= 5; height++ { + if height == 5 { + chain.BlocksByHeight[height] = block + continue + } + + empty := wire.NewMsgBlock(&header) + chain.BlocksByHeight[height] = empty + } + chain.TipHeight = 5 + + conf, err := findCommitConfirmation( + context.Background(), chain, commitTx, + ) + require.NoError(t, err) + confEvent, err := conf.UnwrapOrErr(fmt.Errorf("missing")) + require.NoError(t, err) + require.Equal(t, uint32(5), confEvent.BlockHeight) + + otherTx := wire.NewMsgTx(2) + otherTx.AddTxOut(&wire.TxOut{Value: 1, PkScript: []byte{0x52}}) + + missing, err := findCommitConfirmation( + context.Background(), chain, otherTx, + ) + require.NoError(t, err) + require.False(t, missing.IsSome()) + + delete(chain.BlocksByHeight, 5) + _, err = findCommitConfirmation( + context.Background(), chain, commitTx, + ) + require.Error(t, err) +} + +func TestIsCommitBuried(t *testing.T) { + depth := uint32(DefaultCommitConfTarget) + + require.False(t, isCommitBuried(12, 10, depth)) + require.True(t, isCommitBuried(15, 10, depth)) +} + +func TestTryRecoverBuriedBroadcastNotBuried(t *testing.T) { + commitTx := wire.NewMsgTx(2) + commitTx.AddTxOut(&wire.TxOut{Value: 1000, PkScript: []byte{0x51}}) + + header := wire.BlockHeader{} + block := wire.NewMsgBlock(&header) + block.AddTransaction(commitTx) + + chain := tapgarden.NewMockChainBridge() + chain.BlocksByHeight = map[int64]*wire.MsgBlock{} + for height := int64(1); height <= 12; height++ { + if height == 10 { + chain.BlocksByHeight[height] = block + continue + } + chain.BlocksByHeight[height] = wire.NewMsgBlock(&header) + } + chain.TipHeight = 12 + + env := &Environment{ + Chain: chain, + CommitConfTarget: DefaultCommitConfTarget, + } + + state := &CommitBroadcastState{ + SupplyTransition: SupplyStateTransition{ + NewCommitment: RootCommitment{Txn: commitTx}, + }, + } + + transition, recovered, err := tryRecoverBuriedBroadcast( + context.Background(), state, env, + ) + require.NoError(t, err) + require.False(t, recovered) + require.Nil(t, transition) +} + +func TestTryRecoverBuriedBroadcastReorgBeforeBurial(t *testing.T) { + commitTx := wire.NewMsgTx(2) + commitTx.AddTxOut(&wire.TxOut{Value: 1000, PkScript: []byte{0x51}}) + + header := wire.BlockHeader{} + + chain := tapgarden.NewMockChainBridge() + chain.BlocksByHeight = map[int64]*wire.MsgBlock{} + for height := int64(1); height <= 20; height++ { + chain.BlocksByHeight[height] = wire.NewMsgBlock(&header) + } + // Commitment was seen at height 10 but re-orged away before burial. + chain.TipHeight = 20 + + env := &Environment{ + Chain: chain, + CommitConfTarget: DefaultCommitConfTarget, + } + state := &CommitBroadcastState{ + SupplyTransition: SupplyStateTransition{ + NewCommitment: RootCommitment{Txn: commitTx}, + }, + } + + transition, recovered, err := tryRecoverBuriedBroadcast( + context.Background(), state, env, + ) + require.NoError(t, err) + require.False(t, recovered) + require.Nil(t, transition) +} + +func TestTryRecoverBuriedBroadcastScanError(t *testing.T) { + commitTx := wire.NewMsgTx(2) + commitTx.AddTxOut(&wire.TxOut{Value: 1000, PkScript: []byte{0x51}}) + + chain := tapgarden.NewMockChainBridge() + chain.TipHeight = 5 + chain.BlocksByHeight = map[int64]*wire.MsgBlock{} + + env := &Environment{Chain: chain} + state := &CommitBroadcastState{ + SupplyTransition: SupplyStateTransition{ + NewCommitment: RootCommitment{Txn: commitTx}, + }, + } + + _, _, err := tryRecoverBuriedBroadcast( + context.Background(), state, env, + ) + require.Error(t, err) +} diff --git a/universe/supplycommit/conf_finalize.go b/universe/supplycommit/conf_finalize.go new file mode 100644 index 0000000000..cd776b88cc --- /dev/null +++ b/universe/supplycommit/conf_finalize.go @@ -0,0 +1,91 @@ +package supplycommit + +import ( + "context" + "fmt" + + "github.com/lightninglabs/taproot-assets/proof" + lfn "github.com/lightningnetwork/lnd/fn/v2" +) + +// commitBurialDepth returns the confirmation depth at which a supply +// commitment is buried and may be finalized. +func commitBurialDepth(env *Environment) uint32 { + if env.CommitConfTarget == 0 { + return DefaultCommitConfTarget + } + + return env.CommitConfTarget +} + +// isCommitBuried returns true when the chain tip is deep enough for the +// commitment transaction at confHeight to be considered buried. +func isCommitBuried(tipHeight, confHeight uint32, burialDepth uint32) bool { + if burialDepth == 0 { + return false + } + + // The transaction has burialDepth confirmations when the tip is at + // least confHeight + burialDepth - 1. + return tipHeight+1 >= confHeight+burialDepth +} + +// applyConfToTransition attaches chain proof data from a confirmation event +// to the pending supply transition. +func applyConfToTransition(transition SupplyStateTransition, + conf *ConfEvent) (SupplyStateTransition, error) { + + merkleProof, err := proof.NewTxMerkleProof( + conf.Block.Transactions, int(conf.TxIndex), + ) + if err != nil { + return transition, fmt.Errorf("unable to create merkle "+ + "proof: %w", err) + } + + transition.ChainProof = lfn.Some(ChainProof{ + Header: conf.Block.Header, + BlockHeight: conf.BlockHeight, + MerkleProof: *merkleProof, + TxIndex: conf.TxIndex, + }) + + return transition, nil +} + +// transitionToCommitFinalize persists and returns the state transition that +// hands off to CommitFinalizeState for universe push and tree updates. +func transitionToCommitFinalize(ctx context.Context, env *Environment, + transition SupplyStateTransition) (*StateTransition, error) { + + err := env.StateLog.CommitState( + ctx, env.AssetSpec, &CommitFinalizeState{}, + ) + if err != nil { + return nil, fmt.Errorf("unable to commit state transition: %w", + err) + } + + return &StateTransition{ + NextState: &CommitFinalizeState{ + SupplyTransition: transition, + }, + NewEvents: lfn.Some(FsmEvent{ + InternalEvent: []Event{&FinalizeEvent{}}, + }), + }, nil +} + +// transitionForBuriedConf builds the finalize transition once a commitment +// transaction is buried on chain. +func transitionForBuriedConf(ctx context.Context, env *Environment, + transition SupplyStateTransition, conf *ConfEvent) (*StateTransition, + error) { + + transition, err := applyConfToTransition(transition, conf) + if err != nil { + return nil, err + } + + return transitionToCommitFinalize(ctx, env, transition) +} diff --git a/universe/supplycommit/conf_finalize_test.go b/universe/supplycommit/conf_finalize_test.go new file mode 100644 index 0000000000..76ecda1bf8 --- /dev/null +++ b/universe/supplycommit/conf_finalize_test.go @@ -0,0 +1,65 @@ +package supplycommit + +import ( + "context" + "errors" + "testing" + + "github.com/btcsuite/btcd/wire" + "github.com/lightninglabs/taproot-assets/asset" + "github.com/lightninglabs/taproot-assets/internal/test" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" +) + +// TestTransitionForBuriedConfEntersFinalizeState pins review item 2: a buried +// confirmation must hand off to CommitFinalizeState (universe push / tree +// finalize), not before burial depth is met (see TestIsCommitBuried). +func TestTransitionForBuriedConfEntersFinalizeState(t *testing.T) { + ctx := context.Background() + + header := wire.BlockHeader{} + block := wire.NewMsgBlock(&header) + commitTx := wire.NewMsgTx(2) + commitTx.AddTxOut(&wire.TxOut{Value: 1000, PkScript: []byte{0x51}}) + block.AddTransaction(commitTx) + + conf := &ConfEvent{ + BlockHeight: 10, + Block: block, + TxIndex: 0, + } + + transition := SupplyStateTransition{ + NewCommitment: RootCommitment{Txn: commitTx}, + } + + groupKey := test.RandPubKey(t) + spec := asset.NewSpecifierFromGroupKey(*groupKey) + + stateLog := &mockStateMachineStore{} + stateLog.On( + "CommitState", mock.Anything, spec, mock.Anything, + ).Return(nil) + + env := &Environment{ + StateLog: stateLog, + AssetSpec: spec, + } + + result, err := transitionForBuriedConf(ctx, env, transition, conf) + require.NoError(t, err) + require.NotNil(t, result) + require.IsType(t, &CommitFinalizeState{}, result.NextState) + + finalizeState, ok := result.NextState.(*CommitFinalizeState) + require.True(t, ok) + require.True(t, finalizeState.SupplyTransition.ChainProof.IsSome()) + + events, err := result.NewEvents.UnwrapOrErr( + errors.New("missing emitted events"), + ) + require.NoError(t, err) + require.Len(t, events.InternalEvent, 1) + require.IsType(t, &FinalizeEvent{}, events.InternalEvent[0]) +} diff --git a/universe/supplycommit/env.go b/universe/supplycommit/env.go index de772d5dc0..68f6687c68 100644 --- a/universe/supplycommit/env.go +++ b/universe/supplycommit/env.go @@ -858,6 +858,16 @@ type StateMachineStore interface { // group key as frozen. FreezePendingTransition(context.Context, asset.Specifier) error + // BeginIdleTransition starts a new, frozen transition that spends the + // latest confirmed supply commitment, without requiring any new supply + // update. Dangling updates are bound to it and returned. The state + // machine must be in the default state, have a latest commitment and + // no pending transition, otherwise an error is returned. The persisted + // state becomes the updates pending state, so that the cycle resumes + // after a restart. + BeginIdleTransition(context.Context, asset.Specifier) ( + []SupplyUpdateEvent, error) + // BindDanglingUpdatesToTransition finds any supply update events for // the given asset specifier that are not yet associated with a // transition, creates a new transition for them, and links them. It @@ -941,6 +951,17 @@ type Environment struct { // Log is the prefixed logger for this supply commitment state machine. Log btclog.Logger + + // IdleCommitInterval is the number of blocks after which an idle + // state machine publishes an ancestry-linked successor commitment to + // its latest confirmed commitment, even if there are no new supply + // updates. Zero disables idle successors. + IdleCommitInterval uint32 + + // AutoPublishPending, if true, publishes pending supply updates + // automatically when the next block arrives, instead of waiting for a + // manual UpdateSupplyCommit call. + AutoPublishPending bool } // SupplyCommitTxn encapsulates the details of the transaction that creates a diff --git a/universe/supplycommit/idle_tick_test.go b/universe/supplycommit/idle_tick_test.go new file mode 100644 index 0000000000..ee870437e9 --- /dev/null +++ b/universe/supplycommit/idle_tick_test.go @@ -0,0 +1,997 @@ +package supplycommit + +import ( + "context" + "errors" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/chaincfg/chainhash" + "github.com/btcsuite/btcd/wire" + "github.com/lightninglabs/taproot-assets/asset" + "github.com/lightninglabs/taproot-assets/fn" + "github.com/lightninglabs/taproot-assets/internal/test" + "github.com/lightninglabs/taproot-assets/mssmt" + "github.com/lightninglabs/taproot-assets/proof" + lfn "github.com/lightningnetwork/lnd/fn/v2" + "github.com/lightningnetwork/lnd/keychain" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" +) + +// newTestLatestCommitment creates a confirmed root commitment at the given +// height that can be used as the predecessor of an idle successor. +func newTestLatestCommitment(t *testing.T, confirmed bool, + height uint32) RootCommitment { + + t.Helper() + + internalKey, _ := test.RandKeyDesc(t) + supplyRoot := mssmt.NewBranch( + mssmt.NewLeafNode([]byte("idle-left"), 0), + mssmt.NewLeafNode([]byte("idle-right"), 0), + ) + + txOut, outputKey, err := RootCommitTxOut( + internalKey.PubKey, nil, supplyRoot.NodeHash(), + ) + require.NoError(t, err) + + tx := wire.NewMsgTx(2) + tx.AddTxIn(&wire.TxIn{PreviousOutPoint: randOutPoint(t)}) + tx.AddTxOut(txOut) + + commit := RootCommitment{ + Txn: tx, + TxOutIdx: 0, + InternalKey: internalKey, + OutputKey: outputKey, + SupplyRoot: supplyRoot, + } + if confirmed { + commit.CommitmentBlock = fn.Some(CommitmentBlock{ + Height: height, + Hash: chainhash.Hash{1}, + BlockHeader: &wire.BlockHeader{}, + MerkleProof: &proof.TxMerkleProof{}, + }) + } + + return commit +} + +func (h *supplyCommitTestHarness) expectLatestCommit( + commit lfn.Option[RootCommitment], times int) { + + h.t.Helper() + + h.mockCommits.On("SupplyCommit", mock.Anything, mock.Anything).Return( + lfn.Ok(commit), + ).Times(times) +} + +func newIdleHarness(t *testing.T, initial State, interval uint32, + autoPublish bool) *supplyCommitTestHarness { + + t.Helper() + + randGroupKey := test.RandPubKey(t) + h := newSupplyCommitTestHarness(t, &harnessCfg{ + initialState: initial, + assetSpec: asset.NewSpecifierFromGroupKey(*randGroupKey), + }) + h.env.IdleCommitInterval = interval + h.env.AutoPublishPending = autoPublish + + return h +} + +// TestIdleTickDefaultState tests the idle tick handling of the DefaultState, +// which is what makes idle successor commitments happen. +func TestIdleTickDefaultState(t *testing.T) { + t.Parallel() + + const ( + interval = uint32(144) + confirmed = uint32(1000) + ) + + // With idle commits disabled (the default) the tick is a no-op and no + // dependency is touched at all. + t.Run("disabled", func(t *testing.T) { + h := newIdleHarness(t, &DefaultState{}, 0, false) + h.start() + defer h.stopAndAssert() + + h.sendEvent(&IdleTickEvent{BlockHeight: confirmed + 10_000}) + h.assertStateTransitions(&DefaultState{}) + }) + + // Without any commitment there is nothing to succeed. + t.Run("no_commitment", func(t *testing.T) { + h := newIdleHarness(t, &DefaultState{}, interval, false) + h.start() + defer h.stopAndAssert() + + h.expectLatestCommit(lfn.None[RootCommitment](), 1) + + h.sendEvent(&IdleTickEvent{BlockHeight: confirmed + 10_000}) + h.assertStateTransitions(&DefaultState{}) + }) + + // An unconfirmed latest commitment can't be old enough. + t.Run("unconfirmed_commitment", func(t *testing.T) { + h := newIdleHarness(t, &DefaultState{}, interval, false) + h.start() + defer h.stopAndAssert() + + h.expectLatestCommit(lfn.Some( + newTestLatestCommitment(t, false, 0), + ), 1) + + h.sendEvent(&IdleTickEvent{BlockHeight: confirmed + 10_000}) + h.assertStateTransitions(&DefaultState{}) + }) + + // One block before the deadline nothing happens. + t.Run("not_yet_due", func(t *testing.T) { + h := newIdleHarness(t, &DefaultState{}, interval, false) + h.start() + defer h.stopAndAssert() + + h.expectLatestCommit(lfn.Some( + newTestLatestCommitment(t, true, confirmed), + ), 1) + + h.sendEvent(&IdleTickEvent{BlockHeight: confirmed + interval - 1}) + h.assertStateTransitions(&DefaultState{}) + }) + + // Exactly at confirmation height + interval the idle successor starts + // and runs through the full commitment cycle with no pending updates. + t.Run("due_starts_successor", func(t *testing.T) { + h := newIdleHarness(t, &DefaultState{}, interval, false) + h.start() + defer h.stopAndAssert() + + latest := newTestLatestCommitment(t, true, confirmed) + + // One SupplyCommit call for the idle check, one for the tx + // creation, which must spend the latest commitment. + h.expectLatestCommit(lfn.Some(latest), 2) + h.mockStateLog.On( + "BeginIdleTransition", mock.Anything, mock.Anything, + ).Return(nil, nil).Once() + + h.expectTreeFetches() + h.mockCommits.On( + "UnspentPrecommits", mock.Anything, mock.Anything, + mock.Anything, + ).Return(lfn.Ok[PreCommits](nil)).Once() + h.expectFeeEstimation() + h.expectPsbtFunding() + h.expectPsbtSigning() + h.expectInsertSignedCommitTx() + h.expectAssetLookup() + h.expectSupplySyncer() + h.expectBroadcastAndConfRegistration() + + h.sendEvent(&IdleTickEvent{BlockHeight: confirmed + interval}) + h.assertStateTransitions( + &CommitTreeCreateState{}, + &CommitTxCreateState{}, + &CommitTxSignState{}, + &CommitBroadcastState{}, + &CommitBroadcastState{}, + ) + + // The successor commits no updates and is ancestry linked to + // the latest commitment. + state := assertAndGetCurrentState[*CommitBroadcastState](h) + transition := state.SupplyTransition + require.Empty(t, transition.PendingUpdates) + require.Equal( + t, fn.Some(latest.CommitPoint()), + transition.NewCommitment.SpentCommitment, + ) + }) + + // Dangling updates that were bound to the idle transition are + // committed together with the idle successor. + t.Run("due_with_dangling_updates", func(t *testing.T) { + h := newIdleHarness(t, &DefaultState{}, interval, false) + h.start() + defer h.stopAndAssert() + + dangling := newTestMintEvent( + t, test.RandPubKey(t), randOutPoint(t), + ) + latest := newTestLatestCommitment(t, true, confirmed) + h.expectLatestCommit(lfn.Some(latest), 2) + h.mockStateLog.On( + "BeginIdleTransition", mock.Anything, mock.Anything, + ).Return([]SupplyUpdateEvent{dangling}, nil).Once() + + h.expectTreeFetches() + h.mockCommits.On( + "UnspentPrecommits", mock.Anything, mock.Anything, + mock.Anything, + ).Return(lfn.Ok[PreCommits](nil)).Once() + h.expectFeeEstimation() + h.expectPsbtFunding() + h.expectPsbtSigning() + h.expectInsertSignedCommitTx() + h.expectAssetLookup() + h.expectSupplySyncer() + h.expectBroadcastAndConfRegistration() + + h.sendEvent(&IdleTickEvent{BlockHeight: confirmed + interval*2}) + h.assertStateTransitions( + &CommitTreeCreateState{}, + &CommitTxCreateState{}, + &CommitTxSignState{}, + &CommitBroadcastState{}, + &CommitBroadcastState{}, + ) + + state := assertAndGetCurrentState[*CommitBroadcastState](h) + require.Equal( + t, []SupplyUpdateEvent{dangling}, + state.SupplyTransition.PendingUpdates, + ) + }) + + // A failure to persist the idle transition is an error that is + // reported (the machine is torn down, like for other storage errors). + t.Run("begin_transition_error", func(t *testing.T) { + h := newIdleHarness(t, &DefaultState{}, interval, false) + h.start() + defer h.stopAndAssert() + + beginErr := errors.New("db down") + h.expectLatestCommit(lfn.Some( + newTestLatestCommitment(t, true, confirmed), + ), 1) + h.mockStateLog.On( + "BeginIdleTransition", mock.Anything, mock.Anything, + ).Return(nil, beginErr).Once() + h.expectFailure(beginErr) + + h.sendEvent(&IdleTickEvent{BlockHeight: confirmed + interval}) + h.assertNoStateTransitions() + require.ErrorIs(t, h.mockErrReporter.GetReportedError(), beginErr) + }) +} + +// TestIdleTickOtherStates makes sure an idle tick never disturbs a commitment +// cycle that is in flight. +func TestIdleTickOtherStates(t *testing.T) { + t.Parallel() + + dummyTx := wire.NewMsgTx(2) + dummyTx.AddTxOut(&wire.TxOut{PkScript: []byte("test"), Value: 1}) + transition := SupplyStateTransition{ + NewCommitment: RootCommitment{Txn: dummyTx}, + } + + states := []State{ + &CommitTreeCreateState{}, + &CommitTxCreateState{SupplyTransition: transition}, + &CommitTxSignState{SupplyTransition: transition}, + &CommitBroadcastState{SupplyTransition: transition}, + &CommitFinalizeState{SupplyTransition: transition}, + } + for _, state := range states { + t.Run(state.String(), func(t *testing.T) { + h := newIdleHarness(t, state, 144, true) + h.start() + defer h.stopAndAssert() + + h.sendEvent(&IdleTickEvent{BlockHeight: 10_000}) + h.assertStateTransitions(state) + }) + } +} + +// TestIdleTickUpdatesPendingState tests the opt-in handling of idle ticks while +// updates are staged. +func TestIdleTickUpdatesPendingState(t *testing.T) { + t.Parallel() + + mint := newTestMintEvent(t, test.RandPubKey(t), randOutPoint(t)) + pending := func() State { + return &UpdatesPendingState{ + pendingUpdates: []SupplyUpdateEvent{mint}, + } + } + + // By default pending updates are left alone (manual publishing). + t.Run("idle_only_keeps_pending_updates", func(t *testing.T) { + h := newIdleHarness(t, pending(), 144, false) + h.start() + defer h.stopAndAssert() + + h.sendEvent(&IdleTickEvent{BlockHeight: 10_000}) + h.assertStateTransitions(&UpdatesPendingState{}) + state := assertAndGetCurrentState[*UpdatesPendingState](h) + require.Len(t, state.pendingUpdates, 1) + }) + + // Fully disabled: a no-op. + t.Run("disabled", func(t *testing.T) { + h := newIdleHarness(t, pending(), 0, false) + h.start() + defer h.stopAndAssert() + + h.sendEvent(&IdleTickEvent{BlockHeight: 10_000}) + h.assertStateTransitions(&UpdatesPendingState{}) + }) + + // With auto publishing the next block commits the staged updates. + t.Run("auto_publish", func(t *testing.T) { + h := newIdleHarness(t, pending(), 0, true) + h.start() + defer h.stopAndAssert() + + h.expectFreezePendingTransition() + h.expectFullCommitmentCycleMocks(true) + + h.sendEvent(&IdleTickEvent{BlockHeight: 10_000}) + h.assertStateTransitions( + &CommitTreeCreateState{}, + &CommitTxCreateState{}, + &CommitTxSignState{}, + &CommitBroadcastState{}, + &CommitBroadcastState{}, + ) + }) + + // An idle transition without updates that was persisted before a + // restart resumes on the next idle tick. + t.Run("resume_interrupted_idle_transition", func(t *testing.T) { + h := newIdleHarness(t, &UpdatesPendingState{}, 144, false) + h.start() + defer h.stopAndAssert() + + h.mockStateLog.On("FetchState", mock.Anything, mock.Anything).Return( + &UpdatesPendingState{}, + lfn.Some(SupplyStateTransition{}), nil, + ).Once() + h.expectFreezePendingTransition() + h.expectFullCommitmentCycleMocks(true) + + h.sendEvent(&IdleTickEvent{BlockHeight: 10_000}) + h.assertStateTransitions( + &CommitTreeCreateState{}, + &CommitTxCreateState{}, + &CommitTxSignState{}, + &CommitBroadcastState{}, + &CommitBroadcastState{}, + ) + }) + + // With no transition on disk, a manual tick after a restart returns to + // the default state instead of committing an empty batch. + t.Run("manual_tick_nothing_to_commit", func(t *testing.T) { + h := newIdleHarness(t, &UpdatesPendingState{}, 0, false) + h.start() + defer h.stopAndAssert() + + h.mockStateLog.On("FetchState", mock.Anything, mock.Anything).Return( + &DefaultState{}, lfn.None[SupplyStateTransition](), nil, + ).Once() + h.expectCommitState() + + h.sendEvent(&CommitTickEvent{}) + h.assertStateTransitions(&DefaultState{}) + }) +} + +// TestManagerIdleTickLoop makes sure the manager turns block epochs into idle +// ticks for locally controlled supply commit groups, and only if enabled. +func TestManagerIdleTickLoop(t *testing.T) { + t.Parallel() + + groupKey := test.RandPubKey(t) + + // regErr, when set, is returned by the first epoch registration. + // A later registration succeeds. Subtests run sequentially. + var regErr error + + setup := func(t *testing.T, cfg ManagerCfg) (*Manager, chan int32, + chan struct{}) { + + t.Helper() + + chain := &mockChainBridge{} + lookup := &MockAssetLookup{} + stateLog := &mockStateMachineStore{} + commits := &MockCommitmentTracker{} + + blocks := make(chan int32) + errs := make(chan error) + if regErr != nil { + chain.On( + "RegisterBlockEpochNtfn", mock.Anything, + ).Return(nil, nil, regErr).Once() + } + chain.On( + "RegisterBlockEpochNtfn", mock.Anything, + ).Return(blocks, errs, nil).Maybe() + + lookup.On("FetchSupplyCommitAssets", mock.Anything, true).Return( + []btcec.PublicKey{*groupKey}, nil, + ).Maybe() + lookup.On( + "QueryAssetGroupByGroupKey", mock.Anything, + mock.Anything, + ).Return(&asset.AssetGroup{ + Genesis: &asset.Genesis{Tag: "idle"}, + }, nil).Maybe() + lookup.On( + "FetchAssetMetaForAsset", mock.Anything, mock.Anything, + ).Return(&proof.MetaReveal{ + UniverseCommitments: true, + DelegationKey: fn.Some(*test.RandPubKey(t)), + }, nil).Maybe() + lookup.On( + "FetchInternalKeyLocator", mock.Anything, mock.Anything, + ).Return(keychain.KeyLocator{}, nil).Maybe() + + stateLog.On("FetchState", mock.Anything, mock.Anything).Return( + &DefaultState{}, lfn.None[SupplyStateTransition](), nil, + ).Maybe() + + // The state machine reaches out for the latest commitment when + // it processes the tick, signal that we got there. + ticked := make(chan struct{}, 4) + commits.On("SupplyCommit", mock.Anything, mock.Anything).Run( + func(mock.Arguments) { ticked <- struct{}{} }, + ).Return(lfn.Ok(lfn.None[RootCommitment]())).Maybe() + + cfg.Chain = chain + cfg.AssetLookup = lookup + cfg.StateLog = stateLog + cfg.Commitments = commits + cfg.DaemonAdapters = nil + + return NewManager(cfg), blocks, ticked + } + + t.Run("enabled", func(t *testing.T) { + m, blocks, ticked := setup(t, ManagerCfg{IdleCommitInterval: 6}) + require.NoError(t, m.Start()) + defer func() { require.NoError(t, m.Stop()) }() + + blocks <- 1000 + + select { + case <-ticked: + case <-time.After(testTimeout): + t.Fatal("no idle tick reached the state machine") + } + }) + + t.Run("disabled", func(t *testing.T) { + m, _, _ := setup(t, ManagerCfg{}) + require.NoError(t, m.Start()) + // A second start must not subscribe after the first + // decided the ticker is disabled. + require.NoError(t, m.Start()) + defer func() { require.NoError(t, m.Stop()) }() + + // No epoch registration happens, and nothing ticks. + chain := m.cfg.Chain.(*mockChainBridge) + chain.AssertNotCalled( + t, "RegisterBlockEpochNtfn", mock.Anything, + ) + }) + + t.Run("epoch_registration_error", func(t *testing.T) { + cfg := ManagerCfg{IdleCommitInterval: 6} + chain := &mockChainBridge{} + chain.On( + "RegisterBlockEpochNtfn", mock.Anything, + ).Return(nil, nil, errors.New("no chain")).Twice() + cfg.Chain = chain + + m := NewManager(cfg) + require.ErrorContains(t, m.Start(), "no chain") + // The failed attempt must not latch. A later Start keeps + // reporting the error and tries to subscribe again. + require.ErrorContains(t, m.Start(), "no chain") + chain.AssertNumberOfCalls( + t, "RegisterBlockEpochNtfn", 2, + ) + require.NoError(t, m.Stop()) + }) + + t.Run("retries_after_registration_error", func(t *testing.T) { + regErr = errors.New("no chain") + t.Cleanup(func() { regErr = nil }) + + m, blocks, ticked := setup(t, ManagerCfg{ + IdleCommitInterval: 6, + }) + require.ErrorContains(t, m.Start(), "no chain") + require.NoError(t, m.Start()) + // Success latches. A further Start does not subscribe + // again. + require.NoError(t, m.Start()) + defer func() { require.NoError(t, m.Stop()) }() + + chain := m.cfg.Chain.(*mockChainBridge) + registered := chain.AssertNumberOfCalls( + t, "RegisterBlockEpochNtfn", 2, + ) + if !registered { + return + } + + blocks <- 1000 + + select { + case <-ticked: + case <-time.After(testTimeout): + t.Fatal("no idle tick after registration retry") + } + }) +} + +// idleLoopHarness is a manager whose only job is the block-epoch loop. +// Fetch counts show whether a tick was dispatched. +type idleLoopHarness struct { + m *Manager + blocks chan int32 + errs chan error + fetches *atomic.Int32 +} + +func newIdleLoopHarness(t *testing.T) *idleLoopHarness { + t.Helper() + + chain := &mockChainBridge{} + lookup := &MockAssetLookup{} + blocks := make(chan int32) + errs := make(chan error) + chain.On( + "RegisterBlockEpochNtfn", mock.Anything, + ).Return(blocks, errs, nil).Once() + + fetches := new(atomic.Int32) + lookup.On( + "FetchSupplyCommitAssets", mock.Anything, true, + ).Run(func(mock.Arguments) { + fetches.Add(1) + }).Return([]btcec.PublicKey{}, nil).Maybe() + + m := NewManager(ManagerCfg{ + IdleCommitInterval: 6, + Chain: chain, + AssetLookup: lookup, + }) + require.NoError(t, m.Start()) + t.Cleanup(func() { + require.NoError(t, m.Stop()) + }) + + return &idleLoopHarness{ + m: m, + blocks: blocks, + errs: errs, + fetches: fetches, + } +} + +// waitIdleLoopExit blocks until the ticker goroutine and its context +// watcher have both left. +func waitIdleLoopExit(t *testing.T, h *idleLoopHarness) { + t.Helper() + + done := make(chan struct{}) + go func() { + h.m.Wg.Wait() + close(done) + }() + + select { + case <-done: + case <-time.After(2 * time.Second): + t.Fatalf("idle tick loop did not exit, fetches=%d", + h.fetches.Load()) + } +} + +// TestIdleTickLoopBlockStream checks that a closed epoch stream is not +// read as a stream of height-0 blocks, while a real height of zero is +// still delivered, and that quit still stops the loop. +func TestIdleTickLoopBlockStream(t *testing.T) { + t.Parallel() + + t.Run("closed stream", func(t *testing.T) { + h := newIdleLoopHarness(t) + + // Closing the stream must not be read as height 0. + // The ticker backs off before resubscribing, so this + // window observes the hot loop if that check is lost. + close(h.blocks) + time.Sleep(idleEpochRetryInitial / 2) + require.Zero(t, h.fetches.Load()) + require.NoError(t, h.m.Stop()) + waitIdleLoopExit(t, h) + }) + + t.Run("height zero", func(t *testing.T) { + h := newIdleLoopHarness(t) + + h.blocks <- 0 + require.Eventually(t, func() bool { + return h.fetches.Load() == 1 + }, time.Second, 5*time.Millisecond) + require.EqualValues(t, 1, h.fetches.Load()) + }) + + t.Run("quit", func(t *testing.T) { + h := newIdleLoopHarness(t) + + require.NoError(t, h.m.Stop()) + waitIdleLoopExit(t, h) + require.Zero(t, h.fetches.Load()) + }) + + t.Run("epoch error", func(t *testing.T) { + h := newIdleLoopHarness(t) + + // An error ends the subscription. It must not be read + // as a block, and the ticker must still shut down. + h.errs <- errors.New("lost chain") + time.Sleep(idleEpochRetryInitial / 2) + require.Zero(t, h.fetches.Load()) + require.NoError(t, h.m.Stop()) + waitIdleLoopExit(t, h) + }) +} + +// TestIdleEpochResubscribe checks that a finished block-epoch +// subscription is opened again, that a failed registration waits, and +// that shutdown during that wait leaves the ticker. +func TestIdleEpochResubscribe(t *testing.T) { + t.Parallel() + + t.Run("resumes after close", func(t *testing.T) { + assertIdleEpochResumes(t, func(blocks chan int32, + _ chan error) { + + close(blocks) + }) + }) + + t.Run("resumes after error", func(t *testing.T) { + assertIdleEpochResumes(t, func(_ chan int32, errs chan error) { + errs <- errors.New("lost chain") + }) + }) + + t.Run("resumes after error stream close", func(t *testing.T) { + assertIdleEpochResumes(t, func(_ chan int32, errs chan error) { + close(errs) + }) + }) + + t.Run("backoff after register failure", func(t *testing.T) { + chain := &mockChainBridge{} + lookup := &MockAssetLookup{} + fetches := new(atomic.Int32) + lookup.On( + "FetchSupplyCommitAssets", mock.Anything, true, + ).Run(func(mock.Arguments) { + fetches.Add(1) + }).Return([]btcec.PublicKey{}, nil).Maybe() + + firstBlocks := make(chan int32) + firstErrs := make(chan error) + chain.On( + "RegisterBlockEpochNtfn", mock.Anything, + ).Return(firstBlocks, firstErrs, nil).Once() + + var attempts []time.Time + var mu sync.Mutex + record := func(mock.Arguments) { + mu.Lock() + attempts = append(attempts, time.Now()) + mu.Unlock() + } + chain.On( + "RegisterBlockEpochNtfn", mock.Anything, + ).Run(record).Return( + nil, nil, errors.New("notifier down"), + ).Once() + + resumed := make(chan int32) + resumedErrs := make(chan error) + chain.On( + "RegisterBlockEpochNtfn", mock.Anything, + ).Run(record).Return(resumed, resumedErrs, nil).Once() + + m := NewManager(ManagerCfg{ + IdleCommitInterval: 6, + Chain: chain, + AssetLookup: lookup, + }) + require.NoError(t, m.Start()) + defer func() { require.NoError(t, m.Stop()) }() + + closedAt := time.Now() + close(firstBlocks) + + require.Eventually(t, func() bool { + mu.Lock() + defer mu.Unlock() + return len(attempts) >= 2 + }, 5*time.Second, 10*time.Millisecond) + + mu.Lock() + first := attempts[0] + second := attempts[1] + mu.Unlock() + + // The failed registration and the successful retry are + // separated by the grown backoff, and the first attempt + // itself waits out the initial delay. A retry that keeps + // the initial delay stays under this gap. + require.GreaterOrEqual(t, first.Sub(closedAt), + idleEpochRetryInitial/2) + gap := second.Sub(first) + require.GreaterOrEqual(t, gap, + idleEpochRetryInitial+idleEpochRetryInitial/2) + require.Less(t, gap, idleEpochRetryMax) + + resumed <- 40 + require.Eventually(t, func() bool { + return fetches.Load() == 1 + }, time.Second, 5*time.Millisecond) + }) + + t.Run("quit during backoff", func(t *testing.T) { + h := newIdleLoopHarness(t) + + exited := make(chan struct{}) + go func() { + h.m.Wg.Wait() + close(exited) + }() + + close(h.blocks) + select { + case <-exited: + t.Fatal("ticker exited when the epoch stream closed") + case <-time.After(idleEpochRetryInitial / 2): + } + + require.NoError(t, h.m.Stop()) + select { + case <-exited: + case <-time.After(2 * time.Second): + t.Fatal("ticker did not exit on quit during backoff") + } + require.Zero(t, h.fetches.Load()) + }) + + t.Run("ctx during backoff", func(t *testing.T) { + chain := &mockChainBridge{} + chain.On( + "RegisterBlockEpochNtfn", mock.Anything, + ).Run(func(mock.Arguments) { + t.Errorf("resubscribed after the ticker context " + + "was cancelled") + }).Return(nil, nil, errors.New("should not run")).Maybe() + + m := NewManager(ManagerCfg{ + IdleCommitInterval: 6, + Chain: chain, + }) + ctx, cancel := context.WithCancel(context.Background()) + blocks := make(chan int32) + errs := make(chan error) + + done := make(chan struct{}) + go func() { + defer close(done) + m.idleTickLoop(ctx, blocks, errs, func() {}) + }() + + close(blocks) + select { + case <-done: + t.Fatal("ticker exited when the epoch stream closed") + case <-time.After(idleEpochRetryInitial / 2): + } + + cancel() + select { + case <-done: + case <-time.After(2 * time.Second): + t.Fatal("ticker did not exit on ctx cancel during " + + "backoff") + } + }) +} + +// assertIdleEpochResumes ends the first epoch subscription and checks +// that a later block on the replacement subscription is ticked. +func assertIdleEpochResumes(t *testing.T, endStream func(chan int32, + chan error)) { + + t.Helper() + + chain := &mockChainBridge{} + lookup := &MockAssetLookup{} + fetches := new(atomic.Int32) + regs := new(atomic.Int32) + lookup.On( + "FetchSupplyCommitAssets", mock.Anything, true, + ).Run(func(mock.Arguments) { + fetches.Add(1) + }).Return([]btcec.PublicKey{}, nil).Maybe() + + firstBlocks := make(chan int32) + firstErrs := make(chan error) + chain.On( + "RegisterBlockEpochNtfn", mock.Anything, + ).Run(func(mock.Arguments) { + regs.Add(1) + }).Return(firstBlocks, firstErrs, nil).Once() + + nextBlocks := make(chan int32) + nextErrs := make(chan error) + chain.On( + "RegisterBlockEpochNtfn", mock.Anything, + ).Run(func(mock.Arguments) { + regs.Add(1) + }).Return(nextBlocks, nextErrs, nil).Once() + + m := NewManager(ManagerCfg{ + IdleCommitInterval: 6, + Chain: chain, + AssetLookup: lookup, + }) + require.NoError(t, m.Start()) + defer func() { require.NoError(t, m.Stop()) }() + + endStream(firstBlocks, firstErrs) + + require.Eventually(t, func() bool { + return regs.Load() >= 2 + }, 5*time.Second, 10*time.Millisecond) + + nextBlocks <- 25 + require.Eventually(t, func() bool { + return fetches.Load() == 1 + }, time.Second, 5*time.Millisecond) +} + +// TestIdleEpochBackoffCap checks that a resubscribe delay grows and then +// stays at the cap. +func TestIdleEpochBackoffCap(t *testing.T) { + t.Parallel() + + delay := time.Duration(0) + for i := 0; i < 40; i++ { + delay = nextIdleEpochBackoff(delay) + require.LessOrEqual(t, delay, idleEpochRetryMax) + } + require.Equal(t, idleEpochRetryMax, delay) +} + +// gateStateLog counts FetchState calls and blocks each one until +// release is closed. The block sits inside creation, before the +// machine is cached. +type gateStateLog struct { + mockStateMachineStore + + calls atomic.Int32 + release <-chan struct{} +} + +// FetchState implements StateMachineStore. +func (g *gateStateLog) FetchState(context.Context, asset.Specifier) (State, + lfn.Option[SupplyStateTransition], error) { + + g.calls.Add(1) + <-g.release + + return &DefaultState{}, lfn.None[SupplyStateTransition](), nil +} + +// TestFetchStateMachineCreatedOnce checks that two callers asking for +// an uncached group start one state machine. The idle ticker and +// SendEvent share this path. Two callers already raced on main; the +// cache mutex only covers a single Get or Set. +func TestFetchStateMachineCreatedOnce(t *testing.T) { + t.Parallel() + + release := make(chan struct{}) + var closed sync.Once + closeRelease := func() { + closed.Do(func() { close(release) }) + } + defer closeRelease() + + groupKey := test.RandPubKey(t) + spec := asset.NewSpecifierFromGroupKey(*groupKey) + + lookup := &MockAssetLookup{} + lookup.On( + "QueryAssetGroupByGroupKey", mock.Anything, mock.Anything, + ).Return(&asset.AssetGroup{ + Genesis: &asset.Genesis{Tag: "once"}, + }, nil).Maybe() + lookup.On( + "FetchAssetMetaForAsset", mock.Anything, mock.Anything, + ).Return(&proof.MetaReveal{ + UniverseCommitments: true, + DelegationKey: fn.Some(*test.RandPubKey(t)), + }, nil).Maybe() + lookup.On( + "FetchInternalKeyLocator", mock.Anything, mock.Anything, + ).Return(keychain.KeyLocator{}, nil).Maybe() + + stateLog := &gateStateLog{release: release} + m := NewManager(ManagerCfg{ + AssetLookup: lookup, + StateLog: stateLog, + DaemonAdapters: newMockDaemonAdapters(), + }) + require.NoError(t, m.Start()) + defer func() { require.NoError(t, m.Stop()) }() + + var ( + wg sync.WaitGroup + sm1, sm2 *StateMachine + err1, err2 error + ) + wg.Add(2) + go func() { + defer wg.Done() + sm1, err1 = m.fetchStateMachine(spec) + }() + + // The first caller is held inside creation, before the cache + // insert. Only then start the second, so it observes the miss. + require.Eventually(t, func() bool { + return stateLog.calls.Load() >= 1 + }, time.Second, 5*time.Millisecond) + + go func() { + defer wg.Done() + sm2, err2 = m.fetchStateMachine(spec) + }() + + // Give the second caller time to pass the cache check. It + // shares the in-flight create, so it must not start another + // machine. Without that, it calls FetchState too. + deadline := time.Now().Add(500 * time.Millisecond) + for time.Now().Before(deadline) { + if stateLog.calls.Load() > 1 { + t.Fatalf("created %d state machines while the "+ + "first was still starting", + stateLog.calls.Load()) + } + time.Sleep(5 * time.Millisecond) + } + + closeRelease() + wg.Wait() + + require.NoError(t, err1) + require.NoError(t, err2) + require.EqualValues(t, 1, stateLog.calls.Load()) + require.Same(t, sm1, sm2) + + cached, ok := m.smCache.Get(*groupKey) + require.True(t, ok) + require.Same(t, sm1, cached) +} diff --git a/universe/supplycommit/manager.go b/universe/supplycommit/manager.go index a8ed0a9741..873d8e8c39 100644 --- a/universe/supplycommit/manager.go +++ b/universe/supplycommit/manager.go @@ -18,11 +18,22 @@ import ( "github.com/lightninglabs/taproot-assets/universe" "github.com/lightningnetwork/lnd/msgmux" "github.com/lightningnetwork/lnd/protofsm" + "golang.org/x/sync/singleflight" ) const ( // DefaultTimeout is the context guard default timeout. DefaultTimeout = 30 * time.Second + + // idleEpochRetryInitial is the delay before the first attempt to + // resubscribe after a block-epoch stream ends, and the base delay + // after a failed resubscribe. It keeps a dead notifier from turning + // into a hot loop. + idleEpochRetryInitial = 200 * time.Millisecond + + // idleEpochRetryMax caps the resubscribe delay. A down notifier + // backs off, and a later recovery is still picked up. + idleEpochRetryMax = 30 * time.Second ) // DaemonAdapters is a wrapper around the protofsm.DaemonAdapters interface @@ -89,6 +100,28 @@ type ManagerCfg struct { // IgnoreCheckerCache is used to invalidate the ignore cache when a new // supply commitment is created. IgnoreCheckerCache IgnoreCheckerCache + + // IdleCommitInterval is the number of blocks after which a locally + // controlled asset group with a confirmed supply commitment + // automatically publishes an ancestry-linked successor commitment, even + // if there are no new supply updates. Zero disables idle successors. + IdleCommitInterval uint32 + + // AutoPublishPending, if true, automatically publishes pending supply + // updates when the next block arrives, instead of waiting for a manual + // UpdateSupplyCommit call. + AutoPublishPending bool + + // ResumeInterruptedOnStart, if true, loads local supply-commit state + // machines during Start so in-flight commitments can finalize without + // waiting for the next block epoch. + ResumeInterruptedOnStart bool +} + +// autoCommitEnabled returns true if the manager should emit an idle tick for +// every new block. +func (c *ManagerCfg) autoCommitEnabled() bool { + return c.IdleCommitInterval > 0 || c.AutoPublishPending } // Manager is a manager for multiple supply commitment state @@ -106,8 +139,22 @@ type Manager struct { // used to create guarded contexts. *fn.ContextGuard - startOnce sync.Once - stopOnce sync.Once + // startMu serializes Start. Registration failure must stay + // retryable: a sync.Once would consume the attempt, and a later + // Start would report success without subscribing. + startMu sync.Mutex + + // started is true once Start has completed without error. Further + // Start calls are then a no-op. + started bool + + stopOnce sync.Once + + // smFlight collapses concurrent creates of one group into a single + // call. The cache mutex covers one map operation, so two callers + // can otherwise both miss and start a machine from the same + // durable state. Different groups still create in parallel. + smFlight singleflight.Group } // NewManager creates a new multi state machine manager. @@ -121,16 +168,276 @@ func NewManager(cfg ManagerCfg) *Manager { } } -// Start starts the multi state machine manager. +// Start starts the multi state machine manager. When idle successors or +// automatic publishing is enabled, Start registers for block epochs and +// launches the idle ticker. A failed registration is returned and is not +// latched, so a later Start retries it. Once Start has succeeded, further +// calls are a no-op. A stream that later closes or errors is resubscribed +// from that same goroutine, with a capped backoff. func (m *Manager) Start() error { - m.startOnce.Do(func() { - // Initialize the state machine cache. + m.startMu.Lock() + defer m.startMu.Unlock() + + if m.started { + return nil + } + + // The cache is created even when registration fails, so Stop can + // run after a failed Start. A retry must not replace it: a caller + // may already have stored a machine there. + if m.smCache == nil { m.smCache = newStateMachineCache() - }) + } + + // If idle successors or automatic publishing is enabled, we need + // to tick the state machines as new blocks arrive. + if !m.cfg.autoCommitEnabled() { + m.started = true + return nil + } + ctx, cancel := m.WithCtxQuitNoTimeout() + blockChan, errChan, subCancel, err := m.registerBlockEpoch(ctx) + if err != nil { + cancel() + return fmt.Errorf("unable to register for block epochs: %w", + err) + } + + log.Infof("Supply commit idle ticker enabled "+ + "(idle_commit_interval=%d blocks, "+ + "auto_publish_pending=%v)", m.cfg.IdleCommitInterval, + m.cfg.AutoPublishPending) + + m.Wg.Add(1) + go func() { + defer m.Wg.Done() + defer cancel() + + m.idleTickLoop(ctx, blockChan, errChan, subCancel) + }() + + if m.cfg.ResumeInterruptedOnStart { + m.resumeLocalStateMachines(ctx) + } + + m.started = true return nil } +// resumeLocalStateMachines starts or resumes state machines for every +// locally controlled supply-commit asset group. +func (m *Manager) resumeLocalStateMachines(ctx context.Context) { + groupKeys, err := m.cfg.AssetLookup.FetchSupplyCommitAssets(ctx, true) + if err != nil { + log.Errorf("Unable to fetch supply commit assets to "+ + "resume state machines: %v", err) + + return + } + + for idx := range groupKeys { + groupKey := groupKeys[idx] + assetSpec := asset.NewSpecifierFromGroupKey(groupKey) + + _, err := m.fetchStateMachine(assetSpec) + if err != nil { + log.Errorf("Unable to resume supply commit state "+ + "machine for asset %s: %v", + assetSpec.String(), err) + } + } +} + +// registerBlockEpoch subscribes to block epochs with a child context so +// the subscription can be dropped without stopping the ticker. +func (m *Manager) registerBlockEpoch(ctx context.Context) ( + chan int32, chan error, func(), error) { + + subCtx, subCancel := context.WithCancel(ctx) + blockChan, errChan, err := m.cfg.Chain.RegisterBlockEpochNtfn(subCtx) + if err != nil { + subCancel() + return nil, nil, nil, err + } + + return blockChan, errChan, subCancel, nil +} + +// idleTickLoop sends an IdleTickEvent for every new block. When the epoch +// stream ends it resubscribes until the manager is shutting down. The +// same goroutine owns every subscription, so a restart cannot start a +// second ticker. +func (m *Manager) idleTickLoop(ctx context.Context, blockChan chan int32, + errChan chan error, subCancel func()) { + + // subCancel is reassigned as subscriptions are replaced. The defer + // must call whatever cancel is current when the loop leaves. + defer func() { subCancel() }() + + for { + if !m.serveIdleEpoch(ctx, blockChan, errChan) { + return + } + + // The stream is dead. Drop it before opening another so + // two subscriptions are not live together. + subCancel() + + var err error + blockChan, errChan, subCancel, err = m.resubscribeBlockEpoch( + ctx, + ) + if err != nil { + return + } + } +} + +// serveIdleEpoch reads one block-epoch subscription. It returns true +// when that subscription ended and the ticker should resubscribe, and +// false when the manager is shutting down. A closed channel is a single +// end-of-stream signal, not a series of height-0 blocks. +func (m *Manager) serveIdleEpoch(ctx context.Context, blockChan chan int32, + errChan chan error) bool { + + for { + select { + case height, ok := <-blockChan: + if !ok { + log.Infof("Supply commit idle ticker block " + + "epoch stream closed, resubscribing") + return true + } + if height < 0 { + continue + } + + m.sendIdleTicks(ctx, uint32(height)) + + case err, ok := <-errChan: + // A closed error stream is the same end-of-stream + // signal as a closed block stream. One receive + // leaves the loop; it must not spin. + if !ok { + log.Infof("Supply commit idle ticker block " + + "epoch error stream closed, " + + "resubscribing") + return true + } + if err != nil { + log.Errorf("Supply commit idle ticker block "+ + "epoch subscription failed, "+ + "resubscribing: %v", err) + } + + return true + + case <-ctx.Done(): + return false + + case <-m.Quit: + return false + } + } +} + +// resubscribeBlockEpoch opens a new block-epoch subscription. Each +// attempt waits with a capped backoff so a notifier that is still down +// cannot be polled in a loop. The wait returns when the manager shuts +// down. +func (m *Manager) resubscribeBlockEpoch(ctx context.Context) ( + chan int32, chan error, func(), error) { + + backoff := idleEpochRetryInitial + for { + if err := m.waitIdleEpochRetry(ctx, backoff); err != nil { + return nil, nil, func() {}, err + } + + blockChan, errChan, subCancel, err := m.registerBlockEpoch(ctx) + if err != nil { + log.Errorf("Supply commit idle ticker failed to "+ + "resubscribe for block epochs: %v", err) + backoff = nextIdleEpochBackoff(backoff) + continue + } + + log.Infof("Supply commit idle ticker resubscribed for " + + "block epochs") + + return blockChan, errChan, subCancel, nil + } +} + +// waitIdleEpochRetry blocks for delay, or until the ticker context or +// the manager quit signal fires. +func (m *Manager) waitIdleEpochRetry(ctx context.Context, + delay time.Duration) error { + + timer := time.NewTimer(delay) + defer timer.Stop() + + select { + case <-timer.C: + return nil + + case <-ctx.Done(): + return ctx.Err() + + case <-m.Quit: + return errors.New("supply commit idle ticker shutting down") + } +} + +// nextIdleEpochBackoff grows a resubscribe delay and caps it so the +// wait cannot run away. +func nextIdleEpochBackoff(current time.Duration) time.Duration { + if current < idleEpochRetryInitial { + return idleEpochRetryInitial + } + + next := current * 2 + if next > idleEpochRetryMax || next < current { + return idleEpochRetryMax + } + + return next +} + +// sendIdleTicks sends an idle tick for the given block height to all locally +// controlled supply commit asset groups. Errors are logged, a single failing +// group must not stop the others. +func (m *Manager) sendIdleTicks(ctx context.Context, height uint32) { + groupKeys, err := m.cfg.AssetLookup.FetchSupplyCommitAssets(ctx, true) + if err != nil { + log.Errorf("Unable to fetch supply commit assets for idle "+ + "tick at height %d: %v", height, err) + + return + } + + for idx := range groupKeys { + groupKey := groupKeys[idx] + assetSpec := asset.NewSpecifierFromGroupKey(groupKey) + + sm, err := m.fetchStateMachine(assetSpec) + if err != nil { + log.Errorf("Unable to get state machine for idle "+ + "tick (asset=%s, height=%d): %v", + assetSpec.String(), height, err) + + continue + } + + // SendEvent blocks while the state machine is busy, so make + // sure we don't hang forever. + sendCtx, cancel := context.WithTimeout(ctx, DefaultTimeout) + sm.SendEvent(sendCtx, &IdleTickEvent{BlockHeight: height}) + cancel() + } +} + // Stop stops the multi state machine manager, which in turn stops all asset // group key specific supply commitment state machines. func (m *Manager) Stop() error { @@ -164,15 +471,30 @@ func (m *Manager) startAssetSM(ctx context.Context, CommitConfTarget: DefaultCommitConfTarget, ChainParams: m.cfg.ChainParams, IgnoreCheckerCache: m.cfg.IgnoreCheckerCache, + IdleCommitInterval: m.cfg.IdleCommitInterval, + AutoPublishPending: m.cfg.AutoPublishPending, } // Before we start the state machine, we'll need to fetch the current // state from disk, to see if we need to emit any new events. - initialState, _, err := m.cfg.StateLog.FetchState(ctx, assetSpec) + initialState, initialTransition, err := m.cfg.StateLog.FetchState( + ctx, assetSpec, + ) if err != nil { return nil, fmt.Errorf("unable to fetch current state: %w", err) } + // The durable record keeps the state name and the pending + // transition apart. A resumed state that carries the transition in + // memory is rehydrated from it; its handlers would otherwise run + // against an empty transition, and a broadcast state's first event + // would kill the machine over a nil commitment transaction. + initialTransition.WhenSome(func(transition SupplyStateTransition) { + if state, ok := initialState.(*CommitBroadcastState); ok { + state.SupplyTransition = transition + } + }) + // Create a new error reporter for the state machine. errorReporter := NewErrorReporter(assetSpec) @@ -198,19 +520,32 @@ func (m *Manager) startAssetSM(ctx context.Context, // If specific initial states are provided, we send the corresponding // events to the state machine to ensure it begins ticking as expected. - switch initialState.(type) { + switch state := initialState.(type) { // Once we write the commitment transaction to disk in CommitTxSign, - // then on restart, we'll be in the broadcast state. From this point, - // we'll trigger the broadcast event so we can resume the state machine. + // then on restart, we'll be in the broadcast state. The broadcast + // event re-publishes the persisted transaction: the record is + // written before the publish, so a crash between the two, or a + // publish the wallet rejected, would otherwise leave a signed + // transaction nobody broadcasts and a group that can never + // advance. Publishing a transaction the network already has is + // harmless. A tick may also recover burial-finalization when the + // commitment confirmed while tapd was down. case *CommitBroadcastState: - newSm.SendEvent(ctx, &BroadcastEvent{}) + if state.SupplyTransition.NewCommitment.Txn != nil { + newSm.SendEvent(ctx, &BroadcastEvent{}) + } + newSm.SendEvent(ctx, &CommitTickEvent{}) - // Once we get a confirmation, then we'll transition to the + // Once we get a burial confirmation, then we'll transition to the // CommitFinalizeState. If we crashed right after that, then // we'll also send the finalize event so we can apply // everything, and transition back to the normal default state. case *CommitFinalizeState: newSm.SendEvent(ctx, &FinalizeEvent{}) + + // Parked updates resume on tick after an interrupted cycle. + case *UpdatesPendingState: + newSm.SendEvent(ctx, &CommitTickEvent{}) } return &newSm, nil @@ -228,26 +563,47 @@ func (m *Manager) fetchStateMachine( err) } - // Check if the state machine for the asset group already exists in the - // cache. - sm, ok := m.smCache.Get(*groupKey) - if ok { - // If the state machine is found and is running, return it. - if sm.IsRunning() { - return sm, nil - } + // Fast path: the usual case is a machine that is already running. + if sm, ok := m.runningMachine(*groupKey); ok { + return sm, nil + } - // If the state machine exists but is not running, replace it in - // the cache with a new running instance. + // Creation reads the durable state and starts a goroutine. Share + // that work per group so a second caller, including the idle + // ticker, adopts the machine instead of starting another from the + // same state. + flightKey := string(groupKey.SerializeCompressed()) + created, err, _ := m.smFlight.Do(flightKey, func() (any, error) { + return m.createStateMachine(assetSpec, groupKey) + }) + if err != nil { + return nil, err } - // Before we can create a state machine, we need to ensure that the - // asset group supports supply commitments. If it doesn't, then we - // return an error. + return created.(*StateMachine), nil +} + +// createStateMachine returns the running machine for the group, creating +// and caching one when none is running. Callers must already be inside +// smFlight for this group so two creates cannot overlap. +func (m *Manager) createStateMachine(assetSpec asset.Specifier, + groupKey *btcec.PublicKey) (*StateMachine, error) { + + // Re-check under the flight. A caller that lost the race finds + // the winner's machine here. + if sm, ok := m.runningMachine(*groupKey); ok { + return sm, nil + } + + // Nothing running is cached (a stopped machine falls through). + // Before creating one, ensure that the asset group supports supply + // commitments. If it doesn't, then we return an error. ctx, cancel := m.WithCtxQuitNoTimeout() defer cancel() - err = CheckSupplyCommitSupport(ctx, m.cfg.AssetLookup, assetSpec, true) + err := CheckSupplyCommitSupport( + ctx, m.cfg.AssetLookup, assetSpec, true, + ) if err != nil { return nil, fmt.Errorf("failed to ensure supply commit "+ "support for asset: %w", err) @@ -256,7 +612,8 @@ func (m *Manager) fetchStateMachine( // Start the state machine and add it to the cache. newSm, err := m.startAssetSM(ctx, assetSpec) if err != nil { - return nil, fmt.Errorf("unable to start state machine: %w", err) + return nil, fmt.Errorf("unable to start state machine: %w", + err) } m.smCache.Set(*groupKey, newSm) @@ -264,6 +621,19 @@ func (m *Manager) fetchStateMachine( return newSm, nil } +// runningMachine returns the cached state machine for the group when it +// exists and is running. +func (m *Manager) runningMachine(groupKey btcec.PublicKey) (*StateMachine, + bool) { + + sm, ok := m.smCache.Get(groupKey) + if !ok || !sm.IsRunning() { + return nil, false + } + + return sm, true +} + // SendEvent sends an event to the state machine associated with the given asset // specifier. If a state machine for the asset group does not exist, it will be // created and started. @@ -441,7 +811,8 @@ func (m *Manager) SendEventSync(ctx context.Context, assetSpec asset.Specifier, // SendMintEvent sends a mint event to the supply commitment state machine. // -// NOTE: This implements the tapgarden.MintSupplyCommitter interface. +// NOTE: This is consumed by the GenesisAugmenter at batch confirmation +// time via the MintEventEmitter interface. func (m *Manager) SendMintEvent(ctx context.Context, assetSpec asset.Specifier, leafKey universe.UniqueLeafKey, issuanceProof universe.Leaf, mintBlockHeight uint32) error { diff --git a/universe/supplycommit/mock.go b/universe/supplycommit/mock.go index c8b8c5c879..ad28051f38 100644 --- a/universe/supplycommit/mock.go +++ b/universe/supplycommit/mock.go @@ -362,6 +362,16 @@ func (m *mockStateMachineStore) FreezePendingTransition(ctx context.Context, return args.Error(0) } +func (m *mockStateMachineStore) BeginIdleTransition(ctx context.Context, + spec asset.Specifier) ([]SupplyUpdateEvent, error) { + + args := m.Called(ctx, spec) + if args.Get(0) == nil { + return nil, args.Error(1) + } + return args.Get(0).([]SupplyUpdateEvent), args.Error(1) +} + func (m *mockStateMachineStore) BindDanglingUpdatesToTransition( ctx context.Context, spec asset.Specifier) ([]SupplyUpdateEvent, error) { @@ -389,6 +399,14 @@ func newMockDaemonAdapters() *mockDaemonAdapters { } } +func (m *mockDaemonAdapters) Start() error { + return nil +} + +func (m *mockDaemonAdapters) Stop() error { + return nil +} + func (m *mockDaemonAdapters) BroadcastTransaction( tx *wire.MsgTx, label string) error { diff --git a/universe/supplycommit/state_machine_test.go b/universe/supplycommit/state_machine_test.go index f027df3015..364df73902 100644 --- a/universe/supplycommit/state_machine_test.go +++ b/universe/supplycommit/state_machine_test.go @@ -490,7 +490,11 @@ func (h *supplyCommitTestHarness) expectBroadcastAndConfRegistration() { h.mockChain.On("CurrentHeight", mock.Anything).Return( uint32(123), nil, - ).Once() + ) + + h.mockChain.On( + "GetBlockByHeight", mock.Anything, mock.Anything, + ).Return(wire.NewMsgBlock(&wire.BlockHeader{}), nil).Maybe() h.mockDaemon.On( "RegisterConfirmationsNtfn", mock.Anything, mock.Anything, @@ -1251,6 +1255,37 @@ func TestSupplyCommitBroadcastStateTransitions(t *testing.T) { // TestSupplyCommitFinalizeStateTransitions tests the transitions from the // CommitFinalizeState. +func TestCommitFinalizeStateResumeFinalizeEvent(t *testing.T) { + t.Parallel() + + randGroupKey := test.RandPubKey(t) + defaultAssetSpec := asset.NewSpecifierFromGroupKey(*randGroupKey) + initialTransition := SupplyStateTransition{ + NewCommitment: RootCommitment{ + Txn: wire.NewMsgTx(2), + }, + ChainProof: lfn.Some(ChainProof{}), + } + + h := newSupplyCommitTestHarness(t, &harnessCfg{ + initialState: &CommitFinalizeState{ + SupplyTransition: initialTransition, + }, + assetSpec: defaultAssetSpec, + }) + h.start() + defer h.stopAndAssert() + + h.expectAssetLookup() + h.expectSupplySyncer() + h.expectApplyStateTransition() + h.expectBindDanglingUpdatesWithEvents([]SupplyUpdateEvent{}) + h.expectIgnoreCheckerCacheInvalidation() + + h.sendEvent(&FinalizeEvent{}) + h.assertStateTransitions(&DefaultState{}) +} + func TestSupplyCommitFinalizeStateTransitions(t *testing.T) { t.Parallel() diff --git a/universe/supplycommit/states.go b/universe/supplycommit/states.go index 18dc22fe98..803312d039 100644 --- a/universe/supplycommit/states.go +++ b/universe/supplycommit/states.go @@ -434,6 +434,20 @@ type CommitTickEvent struct { // eventSealed is a special method that is used to seal the interface. func (c *CommitTickEvent) eventSealed() {} +// IdleTickEvent is emitted periodically (once per new block) by the manager +// when an idle commit interval is configured. If the state machine is idle +// and the latest confirmed supply commitment is at least the configured number +// of blocks old, the state machine publishes an ancestry-linked successor +// commitment, even if there are no new supply updates. In any other state the +// event is a no-op. +type IdleTickEvent struct { + // BlockHeight is the current best block height. + BlockHeight uint32 +} + +// eventSealed is a special method that is used to seal the interface. +func (i *IdleTickEvent) eventSealed() {} + // UpdatesPendingState is the state of the state machine when we have. From this // state, we can queue/accept new supply commit events. Periodically, we'll rely // on a new incoming Commit event, that'll be used as a trigger to progress the diff --git a/universe/supplycommit/transitions.go b/universe/supplycommit/transitions.go index b70fb66b2b..f7f2fe2966 100644 --- a/universe/supplycommit/transitions.go +++ b/universe/supplycommit/transitions.go @@ -13,7 +13,6 @@ import ( "github.com/lightninglabs/taproot-assets/asset" "github.com/lightninglabs/taproot-assets/fn" "github.com/lightninglabs/taproot-assets/mssmt" - "github.com/lightninglabs/taproot-assets/proof" "github.com/lightninglabs/taproot-assets/tappsbt" "github.com/lightninglabs/taproot-assets/tapsend" "github.com/lightningnetwork/lnd/chainntnfs" @@ -114,6 +113,11 @@ func (d *DefaultState) ProcessEvent(event Event, NextState: d, }, nil + // An idle tick either starts an ancestry-linked successor commitment + // if the latest commitment is old enough, or it's a no-op. + case *IdleTickEvent: + return d.processIdleTick(supplyEvent, env) + // Any other messages in this state will result in an error, as this is // an undefined state transition. default: @@ -122,6 +126,170 @@ func (d *DefaultState) ProcessEvent(event Event, } } +// processIdleTick handles an IdleTickEvent in the DefaultState. If idle +// commits are enabled, there is a confirmed latest supply commitment, and that +// commitment is at least env.IdleCommitInterval blocks old at the height of +// the tick, a new transition is started that commits to the current supply +// trees (plus any dangling updates), so that a successor commitment that spends +// the latest one is published automatically, without any new supply update. +func (d *DefaultState) processIdleTick(tick *IdleTickEvent, + env *Environment) (*StateTransition, error) { + + noop := &StateTransition{NextState: d} + + // Idle commits are opt-in. + if env.IdleCommitInterval == 0 { + return noop, nil + } + + prefixedLog := env.Logger() + ctx := context.Background() + + // Without a confirmed commitment there is nothing to succeed, the first + // commitment is always driven by supply updates. + latest, err := env.Commitments.SupplyCommit(ctx, env.AssetSpec).Unpack() + if err != nil { + return nil, fmt.Errorf("unable to fetch latest supply "+ + "commitment: %w", err) + } + if latest.IsNone() { + return noop, nil + } + commit := latest.UnwrapOr(RootCommitment{}) + block, err := commit.CommitmentBlock.UnwrapOrErr(ErrNoBlockInfo) + if err != nil { + // The latest commitment isn't confirmed yet, so it can't be + // old enough. + return noop, nil + } + + // Compare in 64 bits to avoid overflowing for very large intervals. + dueHeight := uint64(block.Height) + uint64(env.IdleCommitInterval) + if uint64(tick.BlockHeight) < dueHeight { + return noop, nil + } + + prefixedLog.Infof("Latest supply commitment confirmed at height %d "+ + "is older than the idle interval of %d blocks (current "+ + "height %d), starting idle successor commitment", + block.Height, env.IdleCommitInterval, tick.BlockHeight) + + // Persist a frozen transition first, so a restart or a failure resumes + // this cycle, and any update arriving from now on is stored as a + // dangling update for the next one. + updates, err := env.StateLog.BeginIdleTransition(ctx, env.AssetSpec) + if err != nil { + return nil, fmt.Errorf("unable to begin idle transition: %w", + err) + } + + return &StateTransition{ + NextState: &CommitTreeCreateState{}, + NewEvents: lfn.Some(FsmEvent{ + InternalEvent: []Event{&CreateTreeEvent{ + updatesToCommit: updates, + }}, + }), + }, nil +} + +// collectUpdates returns the updates a commit from this state should include. +// If we hold updates in memory, those are used. Otherwise (after a restart) the +// updates are re-derived from the durable pending transition. The second return +// value is true if a pending transition exists on disk. +func (u *UpdatesPendingState) collectUpdates(ctx context.Context, + env *Environment) ([]SupplyUpdateEvent, bool, error) { + + if len(u.pendingUpdates) > 0 { + return u.pendingUpdates, true, nil + } + + _, diskTransition, err := env.StateLog.FetchState(ctx, env.AssetSpec) + if err != nil { + return nil, false, fmt.Errorf("unable to fetch durable "+ + "state: %w", err) + } + + var updates []SupplyUpdateEvent + diskTransition.WhenSome(func(t SupplyStateTransition) { + updates = t.PendingUpdates + }) + + return updates, diskTransition.IsSome(), nil +} + +// backToDefault persists and returns the transition back to the DefaultState. +func (u *UpdatesPendingState) backToDefault(ctx context.Context, + env *Environment) (*StateTransition, error) { + + err := env.StateLog.CommitState(ctx, env.AssetSpec, &DefaultState{}) + if err != nil { + return nil, fmt.Errorf("unable to commit state "+ + "transition: %w", err) + } + + return &StateTransition{ + NextState: &DefaultState{}, + }, nil +} + +// startCommit freezes the pending transition (no new updates can be added to +// the batch after this) and starts the commitment cycle for the given updates. +func (u *UpdatesPendingState) startCommit(ctx context.Context, + env *Environment, updates []SupplyUpdateEvent) (*StateTransition, + error) { + + err := env.StateLog.FreezePendingTransition(ctx, env.AssetSpec) + if err != nil { + return nil, fmt.Errorf("unable to freeze pending "+ + "transition: %w", err) + } + + env.Logger().Infof("Committing %d supply updates", len(updates)) + + return &StateTransition{ + NextState: &CommitTreeCreateState{}, + NewEvents: lfn.Some(FsmEvent{ + InternalEvent: []Event{&CreateTreeEvent{ + updatesToCommit: updates, + }}, + }), + }, nil +} + +// processIdleTick handles an IdleTickEvent in the UpdatesPendingState. +func (u *UpdatesPendingState) processIdleTick(env *Environment) ( + *StateTransition, error) { + + noop := &StateTransition{NextState: u} + + // Both behaviors are opt-in. + if !env.AutoPublishPending && env.IdleCommitInterval == 0 { + return noop, nil + } + + ctx := context.Background() + updates, hasTransition, err := u.collectUpdates(ctx, env) + if err != nil { + return nil, err + } + + switch { + // Real pending updates are only published automatically if asked, the + // operator may be batching them for a manual update otherwise. + case len(updates) > 0 && env.AutoPublishPending: + return u.startCommit(ctx, env, updates) + + // An empty, durable transition is an idle successor transition that + // was interrupted (by a restart for example), resume it. + case len(updates) == 0 && hasTransition && env.IdleCommitInterval > 0: + return u.startCommit(ctx, env, nil) + + default: + return noop, nil + } +} + // ProcessEvent processes incoming events for the UpdatesPendingState. From // here, we'll either be staging new events, or we'll attempt to start the // commitment update process once a new commitment is received. @@ -166,27 +334,31 @@ func (u *UpdatesPendingState) ProcessEvent(event Event, env *Environment) ( // the new set of supply commitments. We'll emit the CreateTxEvent to // the next state will begin the process of making the new commitment. case *CommitTickEvent: - // Before we transition, we'll freeze the current pending - // transition. This ensures that no new updates can be added - // to this batch. ctx := context.Background() - err := env.StateLog.FreezePendingTransition(ctx, env.AssetSpec) + + // A machine resumed from disk rests here with no in-memory + // updates, the durable record is authoritative. + updates, hasTransition, err := u.collectUpdates(ctx, env) if err != nil { - return nil, fmt.Errorf("unable to freeze "+ - "pending transition: %w", err) + return nil, err } - prefixedLog.Infof("Received tick event, committing %d "+ - "supply updates", len(u.pendingUpdates)) + // With nothing to commit and no durable transition, ticking is + // vacuous: return to the default state rather than committing + // an empty batch. A durable transition without updates is an + // interrupted idle successor, which we resume. + if len(updates) == 0 && !hasTransition { + return u.backToDefault(ctx, env) + } - return &StateTransition{ - NextState: &CommitTreeCreateState{}, - NewEvents: lfn.Some(FsmEvent{ - InternalEvent: []Event{&CreateTreeEvent{ - updatesToCommit: u.pendingUpdates, - }}, - }), - }, nil + return u.startCommit(ctx, env, updates) + + // An idle tick only starts a commit if the operator opted in: either + // to publish pending updates automatically once a block arrives, or to + // resume an idle successor transition that was interrupted (by a + // restart for example). + case *IdleTickEvent: + return u.processIdleTick(env) // Any other messages in this state will result in an error, as this is // an undefined state transition. @@ -354,6 +526,12 @@ func (c *CommitTreeCreateState) ProcessEvent(event Event, NextState: c, }, nil + // An idle tick is a no-op while a commitment cycle is in flight. + case *IdleTickEvent: + return &StateTransition{ + NextState: c, + }, nil + // Otherwise, if we got a CreateTreeEvent, then we'll being to create // the new set of supply root sub-trees based on the pending updates we // have. @@ -779,6 +957,12 @@ func (c *CommitTxCreateState) ProcessEvent(event Event, }), }, nil + // An idle tick is a no-op while a commitment cycle is in flight. + case *IdleTickEvent: + return &StateTransition{ + NextState: c, + }, nil + // Any other messages in this state will result in an error, as this is // an undefined state transition. default: @@ -881,6 +1065,12 @@ func (s *CommitTxSignState) ProcessEvent(event Event, }), }, nil + // An idle tick is a no-op while a commitment cycle is in flight. + case *IdleTickEvent: + return &StateTransition{ + NextState: s, + }, nil + // Any other messages in this state will result in an error, as this is // an undefined state transition. default: @@ -925,11 +1115,36 @@ func (c *CommitBroadcastState) ProcessEvent(event Event, // We're at the final step of the state machine. We'll broadcast the // signed commit tx, then register for a confirmation for when it // confirms. + case *CommitTickEvent: + ctx := context.Background() + transition, recovered, err := tryRecoverBuriedBroadcast( + ctx, c, env, + ) + if err != nil { + return nil, err + } + if recovered { + return transition, nil + } + + return &StateTransition{NextState: c}, nil + case *BroadcastEvent: if c.SupplyTransition.NewCommitment.Txn == nil { return nil, fmt.Errorf("commitment transaction is nil") } + recCtx := context.Background() + transition, recovered, err := tryRecoverBuriedBroadcast( + recCtx, c, env, + ) + if err != nil { + return nil, err + } + if recovered { + return transition, nil + } + commitTxid := c.SupplyTransition.NewCommitment.Txn.TxHash() prefixedLog.Tracef("Broadcasting supply commitment "+ "txn (txid=%v): %v", commitTxid, @@ -977,7 +1192,7 @@ func (c *CommitBroadcastState) ProcessEvent(event Event, Txid: commitTx.TxHash(), PkScript: pkScript, HeightHint: currentHeight, - NumConfs: lfn.Some(uint32(1)), + NumConfs: lfn.Some(commitBurialDepth(env)), FullBlock: true, PostConfMapper: lfn.Some[protofsm.ConfMapper[Event]]( confMapper, @@ -1002,50 +1217,20 @@ func (c *CommitBroadcastState) ProcessEvent(event Event, // the CommitFinalizeState, which will finalize our supply transition // with the new root and sub-tree information. case *ConfEvent: - stateTransition := c.SupplyTransition - - merkleProof, err := proof.NewTxMerkleProof( - newEvent.Block.Transactions, int(newEvent.TxIndex), - ) - if err != nil { - return nil, fmt.Errorf("unable to create merkle "+ - "proof: %w", err) - } - - // Now that the transaction has been confirmed, we'll construct - // a merkle proof for the commitment transaction. This'll be - // used to prove that the supply commit is canonical. - stateTransition.ChainProof = lfn.Some(ChainProof{ - Header: newEvent.Block.Header, - BlockHeight: newEvent.BlockHeight, - MerkleProof: *merkleProof, - TxIndex: newEvent.TxIndex, - }) - - prefixedLog.Tracef("Supply commitment txn confirmed "+ + prefixedLog.Tracef("Supply commitment txn buried "+ "in block %d (hash=%v): %v", newEvent.BlockHeight, newEvent.Block.Header.BlockHash(), limitSpewer.Sdump(c.SupplyTransition.NewCommitment.Txn)) - // The commitment has been confirmed, so we'll transition to the - // finalize state, but also log on disk that we no longer need - // to request confirmations on restart. ctx := context.Background() - err = env.StateLog.CommitState( - ctx, env.AssetSpec, &CommitFinalizeState{}, + return transitionForBuriedConf( + ctx, env, c.SupplyTransition, newEvent, ) - if err != nil { - return nil, fmt.Errorf("unable to commit "+ - "state transition: %w", err) - } + // An idle tick is a no-op while a commitment cycle is in flight. + case *IdleTickEvent: return &StateTransition{ - NextState: &CommitFinalizeState{ - SupplyTransition: stateTransition, - }, - NewEvents: lfn.Some(FsmEvent{ - InternalEvent: []Event{&FinalizeEvent{}}}, - ), + NextState: c, }, nil // Any other messages in this state will result in an error, as this is @@ -1220,6 +1405,12 @@ func (c *CommitFinalizeState) ProcessEvent(event Event, }), }, nil + // An idle tick is a no-op while a commitment cycle is in flight. + case *IdleTickEvent: + return &StateTransition{ + NextState: c, + }, nil + // Any other messages in this state will result in an error, as this is // an undefined state transition. default: diff --git a/universe/supplyverifier/manager.go b/universe/supplyverifier/manager.go index 3cafb543c7..168dfd6645 100644 --- a/universe/supplyverifier/manager.go +++ b/universe/supplyverifier/manager.go @@ -2,6 +2,7 @@ package supplyverifier import ( "context" + "errors" "fmt" "sync" "time" @@ -550,6 +551,21 @@ func (m *Manager) InsertSupplyCommit(ctx context.Context, "commitment_outpoint=%s", assetSpec.String(), commitment.CommitPoint().String()) + // A legitimate re-push of a commitment we already stored must be + // absorbed before verification. Re-applying the leaves would mutate + // the supply tree a second time and fail spuriously. + existing, err := m.cfg.SupplyCommitView.FetchCommitmentByOutpoint( + ctx, assetSpec, commitment.CommitPoint(), + ) + switch { + case err == nil && existing != nil: + return nil + + case err != nil && !errors.Is(err, ErrCommitmentNotFound): + return fmt.Errorf("unable to look up existing commitment: %w", + err) + } + // Fetch all known unspent pre-commitment outputs for the asset group. preCommits, err := FetchPreCommits(ctx, m.cfg.AssetLookup, m.cfg.SupplyCommitView, assetSpec, diff --git a/universe/supplyverifier/syncer.go b/universe/supplyverifier/syncer.go index df02df63a7..4ced6abc1c 100644 --- a/universe/supplyverifier/syncer.go +++ b/universe/supplyverifier/syncer.go @@ -2,6 +2,7 @@ package supplyverifier import ( "context" + "errors" "fmt" "net/url" "sync" @@ -16,9 +17,28 @@ import ( const ( // defaultPullTimeout is the default timeout for a supply commitment + // pull. Fetch retries run under this deadline. defaultPullTimeout = 30 * time.Second + + // maxAncestorChain is the most predecessor supply commitments one + // push will load and insert. The walk also stops on a repeated + // outpoint and on context cancellation. A longer gap is not + // partially inserted: the push fails and a later attempt retries + // the same chain from the start. + maxAncestorChain = 256 ) +// errSupplyChainRemainder is returned when a gap is longer than +// maxAncestorChain. It is not inserted as a prefix: the server is left +// unchanged by this repair, and the caller's retry walks the same chain. +var errSupplyChainRemainder = errors.New("supply commitment predecessor " + + "chain exceeds the repair limit") + +// errNoSupplySyncAttempt is returned when a retry budget admits no +// call. Callers treat a nil error as a completed sync, so skipping the +// call must not report success. +var errNoSupplySyncAttempt = errors.New("supply sync retry made no attempt") + // UniverseClient is an interface that represents a client connection to a // remote universe server. type UniverseClient interface { @@ -52,6 +72,12 @@ type SupplySyncerStore interface { assetSpec asset.Specifier, commitment supplycommit.RootCommitment, leaves supplycommit.SupplyLeaves) error + + // FetchPushedServers returns the addresses of the servers the + // given supply commitment has already been pushed to, as + // recorded by LogSupplyCommitPush. + FetchPushedServers(ctx context.Context, assetSpec asset.Specifier, + commitment supplycommit.RootCommitment) ([]string, error) } // UniverseFederationView is an interface that provides a view of the @@ -62,6 +88,17 @@ type UniverseFederationView interface { UniverseServers(ctx context.Context) ([]universe.ServerAddr, error) } +// SupplyCommitHistory loads a supply commitment this node already +// stores, including the leaves and chain proof needed to push it. The +// outpoint is the commitment output a successor spends. +type SupplyCommitHistory interface { + // FetchSupplyCommitPush returns the push payload for the supply + // commitment that created outpoint. + FetchSupplyCommitPush(ctx context.Context, assetSpec asset.Specifier, + outpoint wire.OutPoint) (supplycommit.RootCommitment, + supplycommit.SupplyLeaves, supplycommit.ChainProof, error) +} + // SupplySyncerConfig is a configuration struct for creating a new // SupplySyncer instance. type SupplySyncerConfig struct { @@ -75,6 +112,20 @@ type SupplySyncerConfig struct { // UniverseFederationView is used to fetch the list of known // universe servers in the federation. UniverseFederationView UniverseFederationView + + // History loads predecessor supply commitments when a server + // rejects an insert because it has not seen the spent commitment. + // A nil History leaves that rejection unrepaired. + History SupplyCommitHistory + + // Retry overrides backoff for universe dial, fetch, and insert. + // Nil selects fn.DefaultRetryConfig: 10 retries after the first + // attempt, starting at 100ms and doubling up to 5s. Cancellation + // of the context ends the sequence. ErrCommitmentNotFound and + // ErrPrevCommitmentNotFound are returned on the first occurrence + // instead of being retried. A negative MaxRetries is clamped to + // zero so the first attempt still runs. + Retry *fn.RetryConfig } // SupplySyncer is a struct that is responsible for retrieving supply leaves @@ -92,7 +143,261 @@ func NewSupplySyncer(cfg SupplySyncerConfig) SupplySyncer { } } -// pushUniServer pushes the supply commitment to a specific universe server. +// retryConfig returns the backoff for universe dial, fetch, and insert. +// MaxRetries counts retries after the initial attempt. A negative value +// is clamped to zero so that attempt still runs. +func (s *SupplySyncer) retryConfig() fn.RetryConfig { + cfg := fn.DefaultRetryConfig() + if s.cfg.Retry != nil { + cfg = *s.cfg.Retry + } + + if cfg.MaxRetries < 0 { + cfg.MaxRetries = 0 + } + + return cfg +} + +// terminalSyncErr reports errors that must not be retried. A missing +// commitment is a definitive answer. A missing predecessor is repaired +// by inserting earlier commitments, not by repeating the same insert. +// Cancellation stops the sequence immediately. +func terminalSyncErr(ctx context.Context, err error) bool { + if ctx.Err() != nil { + return true + } + + return errors.Is(err, context.Canceled) || + errors.Is(err, context.DeadlineExceeded) || + errors.Is(err, ErrCommitmentNotFound) || + errors.Is(err, ErrPrevCommitmentNotFound) +} + +// retrySupplyOp calls op until it succeeds, the context is cancelled, a +// definitive supply-commit error is returned, or the retry budget is +// spent. The wait between attempts is capped and select-bound to ctx. +// Success is never returned without op having run. +func (s *SupplySyncer) retrySupplyOp(ctx context.Context, + op func() error) error { + + cfg := s.retryConfig() + backoff := cfg.InitialBackoff + + var ( + err error + attempted bool + ) + for attempt := 0; attempt <= cfg.MaxRetries; attempt++ { + if ctx.Err() != nil { + return ctx.Err() + } + + attempted = true + err = op() + if err == nil { + return nil + } + + if ctx.Err() != nil { + return ctx.Err() + } + + if terminalSyncErr(ctx, err) || attempt == cfg.MaxRetries { + return err + } + + if cfg.MaxBackoff > 0 && backoff > cfg.MaxBackoff { + backoff = cfg.MaxBackoff + } + + log.Debugf("Supply sync attempt %d failed; retrying in %s: "+ + "%v", attempt+1, backoff, err) + + timer := time.NewTimer(backoff) + select { + case <-ctx.Done(): + timer.Stop() + + return ctx.Err() + + case <-timer.C: + } + + next := time.Duration(float64(backoff) * cfg.BackoffMultiplier) + if cfg.BackoffMultiplier <= 0 { + next = backoff + } + if cfg.MaxBackoff > 0 && next > cfg.MaxBackoff { + next = cfg.MaxBackoff + } + backoff = next + } + + // The loop returns on every attempt. Reaching here means the + // budget admitted no call. That is a failed sync, not a delivery. + if !attempted { + return errNoSupplySyncAttempt + } + + return err +} + +// insertOnce dials the server and inserts one supply commitment. A +// missing-predecessor error is returned as soon as it is observed so +// the caller can repair the chain. The dial and the insert share one +// retry budget: a fresh client is opened on every attempt. +func (s *SupplySyncer) insertOnce(ctx context.Context, + serverAddr universe.ServerAddr, assetSpec asset.Specifier, + commitment supplycommit.RootCommitment, + leaves supplycommit.SupplyLeaves, + chainProof supplycommit.ChainProof) error { + + return s.retrySupplyOp(ctx, func() error { + client, err := s.cfg.ClientFactory(serverAddr) + if err != nil { + return fmt.Errorf("unable to create universe "+ + "client: %w", err) + } + + defer func() { + if closeErr := client.Close(); closeErr != nil { + log.Errorf("unable to close universe "+ + "client: %v", closeErr) + } + }() + + err = client.InsertSupplyCommit( + ctx, assetSpec, commitment, leaves, chainProof, + ) + if err != nil { + return fmt.Errorf("unable to insert supply "+ + "leaves: %w", err) + } + + return nil + }) +} + +// ancestorPush is one predecessor loaded from local history. +type ancestorPush struct { + commitment supplycommit.RootCommitment + leaves supplycommit.SupplyLeaves + chainProof supplycommit.ChainProof +} + +// loadAncestors walks the spent-commitment links of commitment back to +// the first commitment that spends nothing. The returned slice is +// oldest first and does not include commitment itself. +func (s *SupplySyncer) loadAncestors(ctx context.Context, + assetSpec asset.Specifier, commitment supplycommit.RootCommitment) ( + []ancestorPush, error) { + + if s.cfg.History == nil { + return nil, fmt.Errorf("unable to load missing supply "+ + "commitments: no local history: %w", + ErrPrevCommitmentNotFound) + } + + var newestFirst []ancestorPush + seen := make(map[wire.OutPoint]struct{}) + current := commitment + + for { + if err := ctx.Err(); err != nil { + return nil, err + } + + if current.SpentCommitment.IsNone() { + break + } + + spent, err := current.SpentCommitment.UnwrapOrErr( + fmt.Errorf("supply commitment %s was rejected for "+ + "a missing predecessor but does not spend "+ + "one", current.CommitPoint()), + ) + if err != nil { + return nil, err + } + + if _, dup := seen[spent]; dup { + return nil, fmt.Errorf("supply commitment "+ + "predecessor cycle at %s", spent) + } + seen[spent] = struct{}{} + + if len(seen) > maxAncestorChain { + return nil, fmt.Errorf("%w: more than %d predecessors", + errSupplyChainRemainder, maxAncestorChain) + } + + priorCommit, priorLeaves, priorProof, err := + s.cfg.History.FetchSupplyCommitPush( + ctx, assetSpec, spent, + ) + if err != nil { + return nil, fmt.Errorf("unable to load missing "+ + "supply commitment %s: %w", spent, err) + } + + if priorCommit.CommitPoint() != spent { + return nil, fmt.Errorf("local supply commitment "+ + "for %s has outpoint %s", spent, + priorCommit.CommitPoint()) + } + + newestFirst = append(newestFirst, ancestorPush{ + commitment: priorCommit, + leaves: priorLeaves, + chainProof: priorProof, + }) + current = priorCommit + } + + for i, j := 0, len(newestFirst)-1; i < j; i, j = i+1, j-1 { + newestFirst[i], newestFirst[j] = newestFirst[j], newestFirst[i] + } + + return newestFirst, nil +} + +// insertMissingAncestors inserts the predecessors of commitment, oldest +// first, so a server that has not seen the spent outpoint can accept +// the original commitment afterwards. +func (s *SupplySyncer) insertMissingAncestors(ctx context.Context, + serverAddr universe.ServerAddr, assetSpec asset.Specifier, + commitment supplycommit.RootCommitment) error { + + ancestors, err := s.loadAncestors(ctx, assetSpec, commitment) + if err != nil { + return err + } + + for idx := range ancestors { + ancestor := ancestors[idx] + log.Infof("Universe server %s is missing supply commitment "+ + "%s; inserting it before %s", serverAddr.HostStr(), + ancestor.commitment.CommitPoint(), + commitment.CommitPoint()) + + err = s.insertOnce( + ctx, serverAddr, assetSpec, ancestor.commitment, + ancestor.leaves, ancestor.chainProof, + ) + if err != nil { + return fmt.Errorf("unable to insert missing supply "+ + "commitment %s: %w", + ancestor.commitment.CommitPoint(), err) + } + } + + return nil +} + +// pushUniServer pushes the supply commitment to a specific universe +// server. A rejection for a missing predecessor inserts the earlier +// commitments this node has, oldest first, and then retries the insert. func (s *SupplySyncer) pushUniServer(ctx context.Context, assetSpec asset.Specifier, commitment supplycommit.RootCommitment, updateLeaves supplycommit.SupplyLeaves, @@ -102,25 +407,26 @@ func (s *SupplySyncer) pushUniServer(ctx context.Context, log.Debugf("Pushing supply commitment to server: %s, asset: %s", serverAddr.HostStr(), assetSpec.String()) - // Create a client for the specific universe server address. - client, err := s.cfg.ClientFactory(serverAddr) - if err != nil { - return fmt.Errorf("unable to create universe client: %w", err) - } - - // Ensure the client is properly closed when we're done. - defer func() { - if closeErr := client.Close(); closeErr != nil { - log.Errorf("unable to close universe client: %v", - closeErr) + err := s.insertOnce( + ctx, serverAddr, assetSpec, commitment, updateLeaves, + chainProof, + ) + if errors.Is(err, ErrPrevCommitmentNotFound) { + repairErr := s.insertMissingAncestors( + ctx, serverAddr, assetSpec, commitment, + ) + if repairErr != nil { + return repairErr } - }() - err = client.InsertSupplyCommit( - ctx, assetSpec, commitment, updateLeaves, chainProof, - ) + err = s.insertOnce( + ctx, serverAddr, assetSpec, commitment, updateLeaves, + chainProof, + ) + } + if err != nil { - return fmt.Errorf("unable to insert supply leaves: %w", err) + return err } // Log the successful insertion to the remote universe. @@ -199,6 +505,41 @@ func (s *SupplySyncer) PushSupplyCommitment(ctx context.Context, "server addresses: %w", err) } + // Skip servers that already hold this commitment. The push log + // records every successful remote insert, and the caller retries + // the whole dispatch whenever any one server fails — so without + // the skip, a retry re-pushes to servers that already integrated + // the commitment, and one persistently failing server keeps + // every healthy one in the target set forever. + pushed, err := s.cfg.Store.FetchPushedServers( + ctx, assetSpec, commitment, + ) + if err != nil { + return nil, fmt.Errorf("unable to fetch pushed servers: %w", + err) + } + if len(pushed) > 0 { + pushedSet := make(map[string]struct{}, len(pushed)) + for _, host := range pushed { + pushedSet[host] = struct{}{} + } + + remaining := make( + []universe.ServerAddr, 0, len(targetAddrs), + ) + for _, addr := range targetAddrs { + if _, ok := pushedSet[addr.HostStr()]; ok { + continue + } + remaining = append(remaining, addr) + } + + log.Infof("Skipping %d server(s) already holding supply "+ + "commitment for asset %s", + len(targetAddrs)-len(remaining), assetSpec.String()) + targetAddrs = remaining + } + log.Infof("Starting push of supply commitment for asset: %s to "+ "%d servers", assetSpec.String(), len(targetAddrs)) @@ -260,27 +601,35 @@ func (s *SupplySyncer) pullUniServer(ctx context.Context, "spent_outpoint=%v", serverAddr.HostStr(), assetSpec.String(), spentCommitOutpoint.IsSome()) - // Create a client for the specific universe server address. - client, err := s.cfg.ClientFactory(serverAddr) - if err != nil { - return zero, fmt.Errorf("unable to create universe client: %w", - err) - } + var result supplycommit.FetchSupplyCommitResult + err := s.retrySupplyOp(ctx, func() error { + client, err := s.cfg.ClientFactory(serverAddr) + if err != nil { + return fmt.Errorf("unable to create universe "+ + "client: %w", err) + } + + defer func() { + if closeErr := client.Close(); closeErr != nil { + log.Errorf("Unable to close supply syncer "+ + "pull universe client: %v", closeErr) + } + }() - // Ensure the client is properly closed when we're done. - defer func() { - if closeErr := client.Close(); closeErr != nil { - log.Errorf("Unable to close supply syncer pull "+ - "universe client: %v", closeErr) + fetched, err := client.FetchSupplyCommit( + ctx, assetSpec, spentCommitOutpoint, + ) + if err != nil { + return fmt.Errorf("unable to fetch supply "+ + "commitment: %w", err) } - }() - result, err := client.FetchSupplyCommit( - ctx, assetSpec, spentCommitOutpoint, - ) + result = fetched + + return nil + }) if err != nil { - return zero, fmt.Errorf("unable to fetch supply commitment: %w", - err) + return zero, err } log.Infof("Successfully pulled supply commitment from server: %s, "+ diff --git a/universe/supplyverifier/syncer_test.go b/universe/supplyverifier/syncer_test.go new file mode 100644 index 0000000000..542d2244bb --- /dev/null +++ b/universe/supplyverifier/syncer_test.go @@ -0,0 +1,1068 @@ +package supplyverifier + +import ( + "context" + "errors" + "fmt" + "math" + "sync" + "testing" + "time" + + "github.com/btcsuite/btcd/wire" + "github.com/lightninglabs/taproot-assets/asset" + "github.com/lightninglabs/taproot-assets/fn" + "github.com/lightninglabs/taproot-assets/internal/test" + "github.com/lightninglabs/taproot-assets/mssmt" + "github.com/lightninglabs/taproot-assets/universe" + "github.com/lightninglabs/taproot-assets/universe/supplycommit" + "github.com/stretchr/testify/require" +) + +// singleAttemptRetry disables backoff so tests that pin other +// contracts are not multiplied by the default retry budget. +func singleAttemptRetry() *fn.RetryConfig { + return &fn.RetryConfig{MaxRetries: 0} +} + +// fastRetry retries with no delay. maxRetries is the number of retries +// after the first attempt. +func fastRetry(maxRetries int) *fn.RetryConfig { + return &fn.RetryConfig{ + MaxRetries: maxRetries, + InitialBackoff: 0, + BackoffMultiplier: 1, + MaxBackoff: 0, + } +} + +// recordingUniverseClient counts inserts, optionally failing them. +type recordingUniverseClient struct { + inserts int + fail error +} + +func (c *recordingUniverseClient) InsertSupplyCommit(_ context.Context, + _ asset.Specifier, _ supplycommit.RootCommitment, + _ supplycommit.SupplyLeaves, _ supplycommit.ChainProof) error { + + c.inserts++ + + return c.fail +} + +func (c *recordingUniverseClient) FetchSupplyCommit(_ context.Context, + _ asset.Specifier, _ fn.Option[wire.OutPoint]) ( + supplycommit.FetchSupplyCommitResult, error) { + + return supplycommit.FetchSupplyCommitResult{}, errors.New("unused") +} + +func (c *recordingUniverseClient) Close() error { + return nil +} + +// recordingSyncerStore records logged pushes and serves them back as +// the pushed-servers view, the way the durable push log does. +type recordingSyncerStore struct { + mu sync.Mutex + logged []string +} + +func (s *recordingSyncerStore) LogSupplyCommitPush(_ context.Context, + serverAddr universe.ServerAddr, _ asset.Specifier, + _ supplycommit.RootCommitment, _ supplycommit.SupplyLeaves) error { + + s.mu.Lock() + defer s.mu.Unlock() + s.logged = append(s.logged, serverAddr.HostStr()) + + return nil +} + +func (s *recordingSyncerStore) FetchPushedServers(_ context.Context, + _ asset.Specifier, _ supplycommit.RootCommitment) ([]string, error) { + + s.mu.Lock() + defer s.mu.Unlock() + + return append([]string(nil), s.logged...), nil +} + +// staticFederationView serves a fixed server list. +type staticFederationView struct { + servers []universe.ServerAddr +} + +func (f *staticFederationView) UniverseServers( + _ context.Context) ([]universe.ServerAddr, error) { + + return f.servers, nil +} + +// TestPushSupplyCommitmentSkipsPushed pins the retry contract of the +// commitment push: a server the push log records as delivered is not +// pushed to again. The dispatcher retries the whole effect whenever +// any one server fails, so without the skip every retry re-presents +// the commitment to servers that already integrated it — and a +// receiver without the re-push absorb answers that with its outpoint +// uniqueness violation, keeping the dispatch's error set non-empty +// and its bookkeeping open forever. +func TestPushSupplyCommitmentSkipsPushed(t *testing.T) { + t.Parallel() + + ctx := context.Background() + + addrA := universe.NewServerAddrFromStr("a.example:10029") + addrB := universe.NewServerAddrFromStr("b.example:10029") + + clients := map[string]*recordingUniverseClient{ + addrA.HostStr(): {}, + addrB.HostStr(): {fail: errors.New("refused")}, + } + store := &recordingSyncerStore{} + syncer := NewSupplySyncer(SupplySyncerConfig{ + ClientFactory: func( + sa universe.ServerAddr) (UniverseClient, error) { + + return clients[sa.HostStr()], nil + }, + Store: store, + UniverseFederationView: &staticFederationView{ + servers: []universe.ServerAddr{addrA, addrB}, + }, + Retry: singleAttemptRetry(), + }) + + spec := asset.NewSpecifierFromGroupKey(*test.RandPubKey(t)) + commitment := supplycommit.RootCommitment{Txn: wire.NewMsgTx(2)} + + push := func() map[string]error { + errMap, err := syncer.PushSupplyCommitment( + ctx, spec, commitment, supplycommit.SupplyLeaves{}, + supplycommit.ChainProof{}, nil, + ) + require.NoError(t, err) + + return errMap + } + + // First attempt: both servers are targeted; A succeeds and is + // logged, B fails and is reported. + errMap := push() + require.Len(t, errMap, 1) + require.Contains(t, errMap, addrB.HostStr()) + require.Equal(t, 1, clients[addrA.HostStr()].inserts) + require.Equal(t, 1, clients[addrB.HostStr()].inserts) + require.Equal(t, []string{addrA.HostStr()}, store.logged) + + // The retry consults the push log and targets only the server + // still missing the commitment; once it accepts, the error set + // is empty and the dispatch can finally report success. + clients[addrB.HostStr()].fail = nil + + errMap = push() + require.Empty(t, errMap) + require.Equal(t, 1, clients[addrA.HostStr()].inserts) + require.Equal(t, 2, clients[addrB.HostStr()].inserts) + + // A further redelivery, with every server already logged, pushes + // to nobody. + errMap = push() + require.Empty(t, errMap) + require.Equal(t, 1, clients[addrA.HostStr()].inserts) + require.Equal(t, 2, clients[addrB.HostStr()].inserts) +} + +// TestManagerInsertSupplyCommitAbsorbsRePush pins the receiver half of +// the same contract: a pushed commitment already stored under its +// outpoint is absorbed before verification. Re-verifying would apply +// the leaves against the already-updated supply tree and fail, turning +// every legitimate re-push into a spurious error. +func TestManagerInsertSupplyCommitAbsorbsRePush(t *testing.T) { + t.Parallel() + + ctx := context.Background() + + view := &MockSupplyCommitView{} + spec := asset.NewSpecifierFromGroupKey(*test.RandPubKey(t)) + commitment := supplycommit.RootCommitment{ + Txn: wire.NewMsgTx(2), + TxOutIdx: 0, + } + + view.On( + "FetchCommitmentByOutpoint", ctx, spec, + commitment.CommitPoint(), + ).Return(&supplycommit.RootCommitment{}, nil) + + m := &Manager{cfg: ManagerCfg{SupplyCommitView: view}} + err := m.InsertSupplyCommit( + ctx, spec, commitment, supplycommit.SupplyLeaves{}, + ) + require.NoError(t, err) + + // The absorb happens before verification and before any insert. + view.AssertNotCalled(t, "InsertSupplyCommit") + + // An unexpected lookup failure propagates rather than being + // mistaken for absence. + view2 := &MockSupplyCommitView{} + view2.On( + "FetchCommitmentByOutpoint", ctx, spec, + commitment.CommitPoint(), + ).Return(nil, errors.New("db down")) + + m2 := &Manager{cfg: ManagerCfg{SupplyCommitView: view2}} + err = m2.InsertSupplyCommit( + ctx, spec, commitment, supplycommit.SupplyLeaves{}, + ) + require.ErrorContains(t, err, "db down") +} + +// scriptedUniverse is a UniverseClient and dialer. It records inserts +// and can reject a commitment whose spent outpoint it has not seen. +type scriptedUniverse struct { + mu sync.Mutex + + dials int + dialFailLeft int + + inserts []wire.OutPoint + known map[wire.OutPoint]struct{} + + // failInsertsLeft returns insertErr that many times before the + // normal accept/reject path. + failInsertsLeft int + insertErr error + + fetches int + fetchFailLeft int + fetchErr error + fetchResult supplycommit.FetchSupplyCommitResult + + // onInsert, when set, replaces the insert body. + onInsert func(ctx context.Context) error +} + +func newScriptedUniverse() *scriptedUniverse { + return &scriptedUniverse{ + known: make(map[wire.OutPoint]struct{}), + } +} + +func (s *scriptedUniverse) factory( + _ universe.ServerAddr) (UniverseClient, error) { + + s.mu.Lock() + defer s.mu.Unlock() + + s.dials++ + if s.dialFailLeft > 0 { + s.dialFailLeft-- + + return nil, errors.New("dial failed") + } + + return s, nil +} + +func (s *scriptedUniverse) InsertSupplyCommit(ctx context.Context, + _ asset.Specifier, commitment supplycommit.RootCommitment, + _ supplycommit.SupplyLeaves, _ supplycommit.ChainProof) error { + + s.mu.Lock() + defer s.mu.Unlock() + + if s.onInsert != nil { + return s.onInsert(ctx) + } + + point := commitment.CommitPoint() + s.inserts = append(s.inserts, point) + + if s.failInsertsLeft > 0 { + s.failInsertsLeft-- + + return s.insertErr + } + + if commitment.SpentCommitment.IsSome() { + spent, err := commitment.SpentCommitment.UnwrapOrErr( + errors.New("missing spent outpoint"), + ) + if err != nil { + return err + } + if _, ok := s.known[spent]; !ok { + return ErrPrevCommitmentNotFound + } + } + + s.known[point] = struct{}{} + + return nil +} + +func (s *scriptedUniverse) FetchSupplyCommit(_ context.Context, + _ asset.Specifier, _ fn.Option[wire.OutPoint]) ( + supplycommit.FetchSupplyCommitResult, error) { + + s.mu.Lock() + defer s.mu.Unlock() + + s.fetches++ + if s.fetchFailLeft > 0 { + s.fetchFailLeft-- + + return supplycommit.FetchSupplyCommitResult{}, s.fetchErr + } + + return s.fetchResult, nil +} + +func (s *scriptedUniverse) Close() error { + return nil +} + +func (s *scriptedUniverse) snapshot() (dials int, inserts []wire.OutPoint, + fetches int) { + + s.mu.Lock() + defer s.mu.Unlock() + + return s.dials, append([]wire.OutPoint(nil), s.inserts...), s.fetches +} + +// memHistory serves push payloads keyed by the commitment outpoint. +type memHistory struct { + mu sync.Mutex + byOp map[wire.OutPoint]ancestorPush + fetches int +} + +func historyOf(commits []supplycommit.RootCommitment) *memHistory { + byOp := make(map[wire.OutPoint]ancestorPush, len(commits)) + for _, commit := range commits { + byOp[commit.CommitPoint()] = ancestorPush{ + commitment: commit, + } + } + + return &memHistory{byOp: byOp} +} + +func (h *memHistory) FetchSupplyCommitPush(_ context.Context, + _ asset.Specifier, outpoint wire.OutPoint) (supplycommit.RootCommitment, + supplycommit.SupplyLeaves, supplycommit.ChainProof, error) { + + h.mu.Lock() + defer h.mu.Unlock() + + h.fetches++ + push, ok := h.byOp[outpoint] + if !ok { + var ( + zeroCommit supplycommit.RootCommitment + zeroLeaves supplycommit.SupplyLeaves + zeroProof supplycommit.ChainProof + ) + + return zeroCommit, zeroLeaves, zeroProof, ErrCommitmentNotFound + } + + return push.commitment, push.leaves, push.chainProof, nil +} + +func (h *memHistory) fetchCount() int { + h.mu.Lock() + defer h.mu.Unlock() + + return h.fetches +} + +// rootCommit builds a distinct commitment. id selects the locktime so +// each commitment has its own outpoint. +func rootCommit(id uint32, spent fn.Option[wire.OutPoint], +) supplycommit.RootCommitment { + + tx := wire.NewMsgTx(2) + tx.LockTime = id + + return supplycommit.RootCommitment{ + Txn: tx, + TxOutIdx: 0, + SpentCommitment: spent, + } +} + +// commitChain returns n commitments, oldest first. Each spends the +// outpoint of the previous one. The first spends nothing. +func commitChain(n int) []supplycommit.RootCommitment { + commits := make([]supplycommit.RootCommitment, n) + var spent fn.Option[wire.OutPoint] + for i := range commits { + commits[i] = rootCommit(uint32(i+1), spent) + spent = fn.Some(commits[i].CommitPoint()) + } + + return commits +} + +func testSyncer(client *scriptedUniverse, hist SupplyCommitHistory, + retry *fn.RetryConfig) SupplySyncer { + + addr := universe.NewServerAddrFromStr("uni.example:10029") + + return NewSupplySyncer(SupplySyncerConfig{ + ClientFactory: client.factory, + Store: &recordingSyncerStore{}, + UniverseFederationView: &staticFederationView{ + servers: []universe.ServerAddr{addr}, + }, + History: hist, + Retry: retry, + }) +} + +func testSpec(t *testing.T) asset.Specifier { + t.Helper() + + return asset.NewSpecifierFromGroupKey(*test.RandPubKey(t)) +} + +func TestSupplySyncerRetryConfigDefault(t *testing.T) { + t.Parallel() + + syncer := NewSupplySyncer(SupplySyncerConfig{}) + require.Equal(t, fn.DefaultRetryConfig(), syncer.retryConfig()) + + custom := fn.RetryConfig{MaxRetries: 3, InitialBackoff: time.Second} + syncer = NewSupplySyncer(SupplySyncerConfig{Retry: &custom}) + require.Equal(t, custom, syncer.retryConfig()) +} + +// syncerWithRetry builds a syncer aimed at one scripted server and +// returns the store that records logged pushes. +func syncerWithRetry(client *scriptedUniverse, hist SupplyCommitHistory, + maxRetries int) (SupplySyncer, *recordingSyncerStore, string) { + + const host = "uni.example:10029" + + store := &recordingSyncerStore{} + syncer := NewSupplySyncer(SupplySyncerConfig{ + ClientFactory: client.factory, + Store: store, + UniverseFederationView: &staticFederationView{ + servers: []universe.ServerAddr{ + universe.NewServerAddrFromStr(host), + }, + }, + History: hist, + Retry: fastRetry(maxRetries), + }) + + return syncer, store, host +} + +// TestRetryConfigClampsNegativeMaxRetries pins that a negative retry +// budget is clamped to zero and that a valid budget is unchanged. Zero +// means the initial attempt and no further retries. +func TestRetryConfigClampsNegativeMaxRetries(t *testing.T) { + t.Parallel() + + custom := fn.RetryConfig{ + MaxRetries: -7, + InitialBackoff: time.Second, + BackoffMultiplier: 3, + MaxBackoff: 2 * time.Second, + } + syncer := NewSupplySyncer(SupplySyncerConfig{Retry: &custom}) + got := syncer.retryConfig() + + require.Equal(t, 0, got.MaxRetries) + require.Equal(t, time.Second, got.InitialBackoff) + require.Equal(t, 3.0, got.BackoffMultiplier) + require.Equal(t, 2*time.Second, got.MaxBackoff) + + // Clamping copies the config; the caller's value stays intact. + require.Equal(t, -7, custom.MaxRetries) + + zero := fn.RetryConfig{MaxRetries: 0} + syncer = NewSupplySyncer(SupplySyncerConfig{Retry: &zero}) + require.Equal(t, 0, syncer.retryConfig().MaxRetries) + + positive := fn.RetryConfig{MaxRetries: 4} + syncer = NewSupplySyncer(SupplySyncerConfig{Retry: &positive}) + require.Equal(t, 4, syncer.retryConfig().MaxRetries) + + lowest := fn.RetryConfig{MaxRetries: math.MinInt} + syncer = NewSupplySyncer(SupplySyncerConfig{Retry: &lowest}) + require.Equal(t, 0, syncer.retryConfig().MaxRetries) +} + +// TestNegativeMaxRetriesStillAttempts pins that a negative +// Retry.MaxRetries cannot skip the universe call and report success. +// That field counts retries after the first attempt. A negative value +// used to run the retry loop zero times and return nil, so a push +// logged the commitment as delivered and a pull reported success +// without contacting the server. +func TestNegativeMaxRetriesStillAttempts(t *testing.T) { + t.Parallel() + + for _, budget := range []int{-1, math.MinInt} { + t.Run(fmt.Sprintf("budget_%d", budget), func(t *testing.T) { + t.Parallel() + + testNegativeMaxRetriesStillAttempts(t, budget) + }) + } +} + +func testNegativeMaxRetriesStillAttempts(t *testing.T, budget int) { + ctx := context.Background() + spec := testSpec(t) + commitment := rootCommit(1, fn.None[wire.OutPoint]()) + + t.Run("failed push is not delivered", func(t *testing.T) { + client := newScriptedUniverse() + client.failInsertsLeft = 1 + client.insertErr = errors.New("unavailable") + syncer, store, _ := syncerWithRetry(client, nil, budget) + + errMap, err := syncer.PushSupplyCommitment( + ctx, spec, commitment, supplycommit.SupplyLeaves{}, + supplycommit.ChainProof{}, nil, + ) + require.NoError(t, err) + require.Len(t, errMap, 1) + for _, pushErr := range errMap { + require.ErrorContains(t, pushErr, "unavailable") + } + + dials, inserts, _ := client.snapshot() + require.Equal(t, 1, dials) + require.Len(t, inserts, 1) + require.Empty(t, store.logged) + }) + + t.Run("successful push contacts the server", func(t *testing.T) { + client := newScriptedUniverse() + syncer, store, host := syncerWithRetry(client, nil, budget) + + errMap, err := syncer.PushSupplyCommitment( + ctx, spec, commitment, supplycommit.SupplyLeaves{}, + supplycommit.ChainProof{}, nil, + ) + require.NoError(t, err) + require.Empty(t, errMap) + + dials, inserts, _ := client.snapshot() + require.Equal(t, 1, dials) + require.Equal(t, []wire.OutPoint{ + commitment.CommitPoint(), + }, inserts) + require.Equal(t, []string{host}, store.logged) + }) + + t.Run("failed pull is not a fetched commitment", func(t *testing.T) { + client := newScriptedUniverse() + client.fetchFailLeft = 3 + client.fetchErr = errors.New("unavailable") + syncer, _, host := syncerWithRetry(client, nil, budget) + + // pullUniServer is asserted directly. PullSupplyCommitment + // logs the root hash of a successful result, and the + // zero-attempt bug hands it an empty result. + result, err := syncer.pullUniServer( + ctx, spec, fn.None[wire.OutPoint](), + universe.NewServerAddrFromStr(host), + ) + _, _, fetches := client.snapshot() + require.Equal(t, 1, fetches) + require.ErrorContains(t, err, "unavailable") + require.Equal(t, supplycommit.FetchSupplyCommitResult{}, result) + + var res SupplyCommitPullResult + require.NotPanics(t, func() { + res, err = syncer.PullSupplyCommitment( + ctx, spec, fn.None[wire.OutPoint](), nil, + ) + }) + require.NoError(t, err) + require.Len(t, res.ErrorMap, 1) + require.True(t, res.FetchResult.IsNone()) + _, _, fetches = client.snapshot() + require.Equal(t, 2, fetches) + }) + + t.Run("successful pull returns the server commitment", + func(t *testing.T) { + client := newScriptedUniverse() + fetched := rootCommit(4, fn.None[wire.OutPoint]()) + fetched.SupplyRoot = mssmt.NewComputedBranch( + mssmt.EmptyTreeRootHash, 0, + ) + want := supplycommit.FetchSupplyCommitResult{ + RootCommitment: fetched, + } + client.fetchResult = want + syncer, _, host := syncerWithRetry(client, nil, budget) + + result, err := syncer.pullUniServer( + ctx, spec, fn.None[wire.OutPoint](), + universe.NewServerAddrFromStr(host), + ) + _, _, fetches := client.snapshot() + require.Equal(t, 1, fetches) + require.NoError(t, err) + require.Equal( + t, want.RootCommitment.SupplyRoot.NodeHash(), + result.RootCommitment.SupplyRoot.NodeHash(), + ) + }) + + t.Run("repair still inserts predecessors", func(t *testing.T) { + chain := commitChain(2) + client := newScriptedUniverse() + syncer, store, host := syncerWithRetry( + client, historyOf(chain), budget, + ) + + errMap, err := syncer.PushSupplyCommitment( + ctx, spec, chain[1], supplycommit.SupplyLeaves{}, + supplycommit.ChainProof{}, nil, + ) + require.NoError(t, err) + require.Empty(t, errMap) + + _, inserts, _ := client.snapshot() + require.Equal(t, []wire.OutPoint{ + chain[1].CommitPoint(), + chain[0].CommitPoint(), + chain[1].CommitPoint(), + }, inserts) + require.Equal(t, []string{host}, store.logged) + }) + + t.Run("cancelled context is not success", func(t *testing.T) { + syncer := NewSupplySyncer(SupplySyncerConfig{ + Retry: fastRetry(budget), + }) + cancelled, cancel := context.WithCancel(context.Background()) + cancel() + + calls := 0 + err := syncer.retrySupplyOp(cancelled, func() error { + calls++ + + return nil + }) + require.ErrorIs(t, err, context.Canceled) + require.Zero(t, calls) + }) +} + +// TestPushSupplyCommitmentRetriesTransientInsert pins backoff retry of +// a failed insert and of a failed dial. The sequence is bounded by the +// configured attempt count. +func TestPushSupplyCommitmentRetriesTransientInsert(t *testing.T) { + t.Parallel() + + ctx := context.Background() + spec := testSpec(t) + commitment := rootCommit(1, fn.None[wire.OutPoint]()) + + client := newScriptedUniverse() + client.failInsertsLeft = 2 + client.insertErr = errors.New("unavailable") + syncer := testSyncer(client, nil, fastRetry(4)) + + errMap, err := syncer.PushSupplyCommitment( + ctx, spec, commitment, supplycommit.SupplyLeaves{}, + supplycommit.ChainProof{}, nil, + ) + require.NoError(t, err) + require.Empty(t, errMap) + + _, inserts, _ := client.snapshot() + require.Len(t, inserts, 3) + + // A dial failure is retried the same way, and the insert runs + // only after a client is obtained. + client = newScriptedUniverse() + client.dialFailLeft = 2 + syncer = testSyncer(client, nil, fastRetry(4)) + + errMap, err = syncer.PushSupplyCommitment( + ctx, spec, commitment, supplycommit.SupplyLeaves{}, + supplycommit.ChainProof{}, nil, + ) + require.NoError(t, err) + require.Empty(t, errMap) + + dials, inserts, _ := client.snapshot() + require.Equal(t, 3, dials) + require.Len(t, inserts, 1) +} + +// TestPullSupplyCommitmentRetriesTransientFetch pins fetch retry, and +// that a definitive miss is returned on the first attempt. +func TestPullSupplyCommitmentRetriesTransientFetch(t *testing.T) { + t.Parallel() + + ctx := context.Background() + spec := testSpec(t) + client := newScriptedUniverse() + client.fetchFailLeft = 2 + client.fetchErr = errors.New("unavailable") + fetched := rootCommit(1, fn.None[wire.OutPoint]()) + fetched.SupplyRoot = mssmt.NewComputedBranch( + mssmt.EmptyTreeRootHash, 0, + ) + client.fetchResult = supplycommit.FetchSupplyCommitResult{ + RootCommitment: fetched, + } + syncer := testSyncer(client, nil, fastRetry(4)) + + res, err := syncer.PullSupplyCommitment( + ctx, spec, fn.None[wire.OutPoint](), nil, + ) + require.NoError(t, err) + require.Empty(t, res.ErrorMap) + require.True(t, res.FetchResult.IsSome()) + + _, _, fetches := client.snapshot() + require.Equal(t, 3, fetches) + + client = newScriptedUniverse() + client.fetchFailLeft = 5 + client.fetchErr = ErrCommitmentNotFound + syncer = testSyncer(client, nil, fastRetry(4)) + + res, err = syncer.PullSupplyCommitment( + ctx, spec, fn.None[wire.OutPoint](), nil, + ) + require.NoError(t, err) + require.Len(t, res.ErrorMap, 1) + for _, pullErr := range res.ErrorMap { + require.ErrorIs(t, pullErr, ErrCommitmentNotFound) + } + + _, _, fetches = client.snapshot() + require.Equal(t, 1, fetches) +} + +// TestSupplySyncRetryHonorsContext stops a retry when the caller +// cancels, both during the RPC and during the backoff wait. +func TestSupplySyncRetryHonorsContext(t *testing.T) { + t.Parallel() + + spec := testSpec(t) + commitment := rootCommit(1, fn.None[wire.OutPoint]()) + + t.Run("during rpc", func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + started := make(chan struct{}) + var once sync.Once + client := newScriptedUniverse() + client.onInsert = func(ctx context.Context) error { + once.Do(func() { close(started) }) + <-ctx.Done() + + return ctx.Err() + } + syncer := testSyncer(client, nil, fastRetry(4)) + + errCh := make(chan error, 1) + go func() { + _, err := syncer.PushSupplyCommitment( + ctx, spec, commitment, + supplycommit.SupplyLeaves{}, + supplycommit.ChainProof{}, nil, + ) + errCh <- err + }() + + select { + case <-started: + case <-time.After(2 * time.Second): + t.Fatal("insert did not start") + } + cancel() + + select { + case err := <-errCh: + require.ErrorIs(t, err, context.Canceled) + case <-time.After(2 * time.Second): + t.Fatal("retry ignored cancellation") + } + + _, inserts, _ := client.snapshot() + require.Empty(t, inserts) + }) + + t.Run("during backoff", func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + started := make(chan struct{}) + var once sync.Once + var calls atomicInt + client := newScriptedUniverse() + + // A long backoff would hang the test if cancellation + // were ignored. The hook counts calls directly because + // it replaces the scripted insert body. + client.onInsert = func(context.Context) error { + calls.add() + once.Do(func() { close(started) }) + + return errors.New("unavailable") + } + retry := &fn.RetryConfig{ + MaxRetries: 5, + InitialBackoff: time.Hour, + BackoffMultiplier: 2, + MaxBackoff: time.Hour, + } + syncer := testSyncer(client, nil, retry) + + errCh := make(chan error, 1) + go func() { + _, err := syncer.PushSupplyCommitment( + ctx, spec, commitment, + supplycommit.SupplyLeaves{}, + supplycommit.ChainProof{}, nil, + ) + errCh <- err + }() + + select { + case <-started: + case <-time.After(2 * time.Second): + t.Fatal("insert did not start") + } + cancel() + + select { + case err := <-errCh: + require.ErrorIs(t, err, context.Canceled) + case <-time.After(2 * time.Second): + t.Fatal("backoff ignored cancellation") + } + + require.Equal(t, 1, calls.get()) + }) +} + +// atomicInt is a tiny counter that is safe to bump from the insert hook. +type atomicInt struct { + mu sync.Mutex + n int +} + +func (a *atomicInt) add() { + a.mu.Lock() + a.n++ + a.mu.Unlock() +} + +func (a *atomicInt) get() int { + a.mu.Lock() + defer a.mu.Unlock() + + return a.n +} + +// TestPushDoesNotRetryOrStringMatchMissing pins two boundaries: a +// missing predecessor is not burned against the retry budget, and an +// error whose text merely looks like that sentinel does not trigger a +// history load. +func TestPushDoesNotRetryOrStringMatchMissing(t *testing.T) { + t.Parallel() + + ctx := context.Background() + spec := testSpec(t) + parent := rootCommit(1, fn.None[wire.OutPoint]()) + tip := rootCommit(2, fn.Some(parent.CommitPoint())) + hist := historyOf([]supplycommit.RootCommitment{parent}) + + client := newScriptedUniverse() + syncer := testSyncer(client, nil, fastRetry(5)) + + errMap, err := syncer.PushSupplyCommitment( + ctx, spec, tip, supplycommit.SupplyLeaves{}, + supplycommit.ChainProof{}, nil, + ) + require.NoError(t, err) + require.Len(t, errMap, 1) + for _, pushErr := range errMap { + require.ErrorIs(t, pushErr, ErrPrevCommitmentNotFound) + } + + _, inserts, _ := client.snapshot() + require.Len(t, inserts, 1) + + client = newScriptedUniverse() + client.insertErr = errors.New("previous supply commitment not found") + client.failInsertsLeft = 10 + syncer = testSyncer(client, hist, fastRetry(2)) + + errMap, err = syncer.PushSupplyCommitment( + ctx, spec, tip, supplycommit.SupplyLeaves{}, + supplycommit.ChainProof{}, nil, + ) + require.NoError(t, err) + require.Len(t, errMap, 1) + for _, pushErr := range errMap { + require.NotErrorIs(t, pushErr, ErrPrevCommitmentNotFound) + } + + _, inserts, _ = client.snapshot() + require.Len(t, inserts, 3) + require.Zero(t, hist.fetchCount()) +} + +// TestPushSupplyCommitmentInsertsMissingPredecessors inserts the gap +// oldest-first and then retries the commitment that was rejected. +func TestPushSupplyCommitmentInsertsMissingPredecessors(t *testing.T) { + t.Parallel() + + ctx := context.Background() + spec := testSpec(t) + chain := commitChain(3) + client := newScriptedUniverse() + syncer := testSyncer(client, historyOf(chain), fastRetry(2)) + + errMap, err := syncer.PushSupplyCommitment( + ctx, spec, chain[2], supplycommit.SupplyLeaves{}, + supplycommit.ChainProof{}, nil, + ) + require.NoError(t, err) + require.Empty(t, errMap) + + _, inserts, _ := client.snapshot() + require.Equal(t, []wire.OutPoint{ + chain[2].CommitPoint(), + chain[0].CommitPoint(), + chain[1].CommitPoint(), + chain[2].CommitPoint(), + }, inserts) + + // A transient failure is retried before the missing-predecessor + // repair runs. The first tip insert fails closed; the second is + // the rejection that starts the ordered backfill. + client = newScriptedUniverse() + client.failInsertsLeft = 1 + client.insertErr = errors.New("unavailable") + syncer = testSyncer(client, historyOf(chain), fastRetry(2)) + + errMap, err = syncer.PushSupplyCommitment( + ctx, spec, chain[2], supplycommit.SupplyLeaves{}, + supplycommit.ChainProof{}, nil, + ) + require.NoError(t, err) + require.Empty(t, errMap) + + _, inserts, _ = client.snapshot() + require.Equal(t, []wire.OutPoint{ + chain[2].CommitPoint(), + chain[2].CommitPoint(), + chain[0].CommitPoint(), + chain[1].CommitPoint(), + chain[2].CommitPoint(), + }, inserts) +} + +// TestPushSupplyCommitmentRejectsMismatchedHistory refuses a local +// payload whose outpoint is not the spent outpoint the server named. +func TestPushSupplyCommitmentRejectsMismatchedHistory(t *testing.T) { + t.Parallel() + + ctx := context.Background() + spec := testSpec(t) + parent := rootCommit(1, fn.None[wire.OutPoint]()) + tip := rootCommit(2, fn.Some(parent.CommitPoint())) + other := rootCommit(9, fn.None[wire.OutPoint]()) + + hist := &memHistory{ + byOp: map[wire.OutPoint]ancestorPush{ + parent.CommitPoint(): {commitment: other}, + }, + } + client := newScriptedUniverse() + syncer := testSyncer(client, hist, fastRetry(3)) + + errMap, err := syncer.PushSupplyCommitment( + ctx, spec, tip, supplycommit.SupplyLeaves{}, + supplycommit.ChainProof{}, nil, + ) + require.NoError(t, err) + require.Len(t, errMap, 1) + for _, pushErr := range errMap { + require.ErrorContains(t, pushErr, "outpoint") + } + + _, inserts, _ := client.snapshot() + require.Equal(t, []wire.OutPoint{tip.CommitPoint()}, inserts) +} + +// TestPushSupplyCommitmentRejectsPredecessorCycle fails closed when +// spent outpoints loop, instead of inserting forever. +func TestPushSupplyCommitmentRejectsPredecessorCycle(t *testing.T) { + t.Parallel() + + ctx := context.Background() + spec := testSpec(t) + + first := rootCommit(1, fn.None[wire.OutPoint]()) + second := rootCommit(2, fn.Some(first.CommitPoint())) + first.SpentCommitment = fn.Some(second.CommitPoint()) + + client := newScriptedUniverse() + syncer := testSyncer( + client, historyOf([]supplycommit.RootCommitment{first, second}), + fastRetry(5), + ) + + errMap, err := syncer.PushSupplyCommitment( + ctx, spec, second, supplycommit.SupplyLeaves{}, + supplycommit.ChainProof{}, nil, + ) + require.NoError(t, err) + require.Len(t, errMap, 1) + for _, pushErr := range errMap { + require.ErrorContains(t, pushErr, "cycle") + } + + _, inserts, _ := client.snapshot() + require.Len(t, inserts, 1) +} + +// TestPushSupplyCommitmentBoundsAncestorChain refuses a gap longer +// than the repair limit without walking it without end. +func TestPushSupplyCommitmentBoundsAncestorChain(t *testing.T) { + t.Parallel() + + ctx := context.Background() + spec := testSpec(t) + chain := commitChain(maxAncestorChain + 2) + client := newScriptedUniverse() + syncer := testSyncer(client, historyOf(chain), fastRetry(3)) + + errMap, err := syncer.PushSupplyCommitment( + ctx, spec, chain[len(chain)-1], supplycommit.SupplyLeaves{}, + supplycommit.ChainProof{}, nil, + ) + require.NoError(t, err) + require.Len(t, errMap, 1) + for _, pushErr := range errMap { + require.ErrorIs(t, pushErr, errSupplyChainRemainder) + } + + _, inserts, _ := client.snapshot() + require.Len(t, inserts, 1) +} diff --git a/universe/supplyverifier/verifier.go b/universe/supplyverifier/verifier.go index 1a5bebce3d..33874f352e 100644 --- a/universe/supplyverifier/verifier.go +++ b/universe/supplyverifier/verifier.go @@ -609,6 +609,42 @@ func (v *Verifier) verifyIgnoreLeaf(ctx context.Context, return nil } +// checkBurnLeafInputs fails closed on embedded burn-input files that +// are empty or that prove the same previous asset more than once. +func checkBurnLeafInputs(burnProof *proof.Proof) error { + if len(burnProof.AdditionalInputs) == 0 { + return nil + } + + seen := make(map[asset.PrevID]struct{}, len(burnProof.AdditionalInputs)) + for idx := range burnProof.AdditionalInputs { + inputFile := &burnProof.AdditionalInputs[idx] + if inputFile.IsEmpty() { + return fmt.Errorf("empty proof file") + } + + last, err := inputFile.LastProof() + if err != nil { + return fmt.Errorf("burn input %d: %w", idx, err) + } + + prevID := asset.PrevID{ + OutPoint: last.OutPoint(), + ID: last.Asset.ID(), + ScriptKey: asset.ToSerialized( + last.Asset.ScriptKey.PubKey, + ), + } + if _, ok := seen[prevID]; ok { + return fmt.Errorf("duplicate burn input %v", + prevID.OutPoint) + } + seen[prevID] = struct{}{} + } + + return nil +} + // verifyBurnLeaf verifies a single burn leaf entry. func (v *Verifier) verifyBurnLeaf(ctx context.Context, assetSpec asset.Specifier, burnEntry supplycommit.NewBurnEvent) error { @@ -629,6 +665,12 @@ func (v *Verifier) verifyBurnLeaf(ctx context.Context, err) } + err = checkBurnLeafInputs(burnProof) + if err != nil { + return fmt.Errorf("burn leaf proof failed verification: %w", + err) + } + _, err = burnProof.Verify(ctx, nil, lookup, vCtx) if err != nil { return fmt.Errorf("burn leaf proof failed verification: %w", diff --git a/universe/supplyverifier/verifier_methods_test.go b/universe/supplyverifier/verifier_methods_test.go index a9420d4726..cedea23bd8 100644 --- a/universe/supplyverifier/verifier_methods_test.go +++ b/universe/supplyverifier/verifier_methods_test.go @@ -13,6 +13,7 @@ import ( "github.com/lightninglabs/taproot-assets/asset" "github.com/lightninglabs/taproot-assets/fn" internaltest "github.com/lightninglabs/taproot-assets/internal/test" + "github.com/lightninglabs/taproot-assets/proof" "github.com/lightninglabs/taproot-assets/mssmt" "github.com/lightninglabs/taproot-assets/tapgarden" "github.com/lightninglabs/taproot-assets/universe" @@ -1074,5 +1075,44 @@ func TestVerifyBurnLeaf(t *testing.T) { err = v.verifyBurnLeaf(ctx, assetSpec, burnEntry) require.NoError(t, err) + + // A bare suffix has no provenance. Universe servers + // verify with a nil prior snapshot, so this is what a + // burn leaf looked like before the sender embedded the + // input proofs (lightninglabs/taproot-assets#2285). + bare := burnProof + bare.AdditionalInputs = nil + burnEntry.BurnProof = &bare + + err = v.verifyBurnLeaf(ctx, assetSpec, burnEntry) + require.Error(t, err) + require.ErrorContains(t, err, "missing asset input") + + // Two embedded files for one input must not collapse + // to whichever copy was verified last. + duplicated := burnProof + duplicated.AdditionalInputs = append( + append( + []proof.File{}, burnProof.AdditionalInputs..., + ), + burnProof.AdditionalInputs..., + ) + burnEntry.BurnProof = &duplicated + + err = v.verifyBurnLeaf(ctx, assetSpec, burnEntry) + require.Error(t, err) + require.ErrorContains(t, err, "duplicate burn input") + + // An embedded file that does not decode as a proof + // chain fails closed. + malformed := burnProof + malformed.AdditionalInputs = []proof.File{ + *proof.NewEmptyFile(proof.V0), + } + burnEntry.BurnProof = &malformed + + err = v.verifyBurnLeaf(ctx, assetSpec, burnEntry) + require.Error(t, err) + require.ErrorContains(t, err, "empty proof file") }) }