diff --git a/docs/release-notes/release-notes-0.8.5.md b/docs/release-notes/release-notes-0.8.5.md index 475f4ca76f..9c0e28b7e4 100644 --- a/docs/release-notes/release-notes-0.8.5.md +++ b/docs/release-notes/release-notes-0.8.5.md @@ -15,3 +15,15 @@ bytes. A supply commitment verifier re-encodes burn proofs to compute their universe leaves, and could reject a supply commitment for a burned asset that spent several inputs. Both are now encoded sorted by key. + +* [Universe servers no longer reject supply commitments that carry + burns](https://github.com/lightninglabs/taproot-assets/pull/2331). + A burn leaf's proof is a bare state transition, with no provenance + for the input it consumes, and was verified as if it were + self-contained, so every such commitment failed with `missing asset + input(s)` and the group stopped publishing supply commitments. The + verifier now checks the burn against its input's provenance: a + universe server takes it from its own universe, and a node syncing + supply commitments from the servers it pulls from. The issuer + publishes that provenance to each server before pushing the + commitment. diff --git a/itest/supply_commit_test.go b/itest/supply_commit_test.go index c1f6596be8..caf4dbddac 100644 --- a/itest/supply_commit_test.go +++ b/itest/supply_commit_test.go @@ -789,6 +789,7 @@ func MintAssetWithSupplyCommit(t *harnessTest, // 3. Burning assets creates burn leaves in the supply tree with negative // amounts. // 4. All operations produce valid inclusion proofs that can be verified. +// 5. The universe server accepts the commitment carrying the burn. func testSupplyCommitMintBurn(t *harnessTest) { ctxb := context.Background() @@ -955,6 +956,11 @@ func testSupplyCommitMintBurn(t *harnessTest) { fetchResp.BurnSubtreeRoot, ) + t.Log("Verifying universe server holds the burn commitment") + assertBurnCommit( + t, t.universeServer.service, groupKeyBytes, fetchResp, burnAmt, + ) + t.Log("Fetching supply leaves for detailed verification") // Fetch supply leaves to verify individual entries have all been @@ -1552,6 +1558,10 @@ func unmarshalRPCSupplyLeafKey(t *testing.T, // 8. Primary node mints another asset into the group and publishes the // third supply commitment. // 9. Verifies the secondary node can fetch the third supply commitment. +// 10. Primary node burns part of its change from the transfer and +// publishes the fourth supply commitment. +// 11. Verifies the universe server and the secondary node both hold the +// fourth supply commitment. func testSupplyVerifyPeerNode(t *harnessTest) { ctxb := context.Background() @@ -1813,7 +1823,7 @@ func testSupplyVerifyPeerNode(t *harnessTest) { firstMintReq.Asset.Amount + secondMintReq.Asset.Amount, ) var thirdSupplyCommitResp *unirpc.FetchSupplyCommitResponse - thirdSupplyCommitResp, _ = WaitForSupplyCommit( + thirdSupplyCommitResp, supplyOutpoint = WaitForSupplyCommit( t.t, ctxb, t.tapd, groupKeyBytes, fn.Some(supplyOutpoint), func(resp *unirpc.FetchSupplyCommitResponse) bool { actualRootSum := @@ -1863,6 +1873,112 @@ func testSupplyVerifyPeerNode(t *harnessTest) { // Verify that the secondary node's third supply commitment matches the // primary's. assertFetchCommitResponse(t, thirdSupplyCommitResp, peerFetchResp3) + + // Step 10: Primary node burns part of its change from the transfer to + // the secondary node. The change output never passed through the + // universe server, so the burn's input provenance reaches it only + // through the commitment push. + t.Log("Burning part of the change from the transfer") + + const burnAmt = 500 + burnResp, err := t.tapd.BurnAsset(ctxb, &taprpc.BurnAssetRequest{ + AssetSpecifier: &taprpc.AssetSpecifier{ + Id: &taprpc.AssetSpecifier_AssetId{ + AssetId: rpcFirstAsset.AssetGenesis.AssetId, + }, + }, + AmountToBurn: burnAmt, + ConfirmationText: rpcserver.AssetBurnConfirmationText, + }) + require.NoError(t.t, err) + + AssertAssetOutboundTransferWithOutputs( + t.t, t.lndHarness.Miner(), t.tapd, burnResp.BurnTransfer, + [][]byte{rpcFirstAsset.AssetGenesis.AssetId}, + []uint64{sendChangeAmount - burnAmt, burnAmt}, 1, 2, 2, true, + ) + + // The burn's supply-commit event is recorded asynchronously, and a + // tick with nothing pending is a no-op, so tick until the commitment + // transaction is broadcast. + t.Log("Updating supply commitment after burn (creating fourth " + + "supply commitment)") + lndMiner := t.lndHarness.Miner() + updateReq := &unirpc.UpdateSupplyCommitRequest{ + GroupKey: &unirpc.UpdateSupplyCommitRequest_GroupKeyBytes{ + GroupKeyBytes: groupKeyBytes, + }, + } + deadline := time.Now().Add(defaultWaitTimeout) + for len(lndMiner.GetRawMempool()) == 0 { + require.True( + t.t, time.Now().Before(deadline), + "no commitment broadcast after the burn", + ) + + _, err = t.tapd.UpdateSupplyCommit(ctxb, updateReq) + require.NoError(t.t, err) + + time.Sleep(2 * time.Second) + } + MineBlocks(t.t, lndMiner, 1, 1) + + burnCommitResp, _ := WaitForSupplyCommit( + t.t, ctxb, t.tapd, groupKeyBytes, fn.Some(supplyOutpoint), + func(resp *unirpc.FetchSupplyCommitResponse) bool { + return resp.BurnSubtreeRoot != nil && + resp.BurnSubtreeRoot.RootNode.RootSum == burnAmt + }, + ) + + // Step 11: The universe server verifies the burn against the + // provenance the push published to it, and the secondary node + // against the provenance it fetches from the universe server. + t.Log("Verifying universe server holds the fourth supply commitment") + assertBurnCommit( + t, t.universeServer.service, groupKeyBytes, burnCommitResp, + burnAmt, + ) + + t.Log("Verifying secondary node holds the fourth supply commitment") + assertBurnCommit(t, secondTapd, groupKeyBytes, burnCommitResp, burnAmt) +} + +// assertBurnCommit asserts that the given node holds the issuer's supply +// commitment carrying burns, as identified by the commitment it spends, and +// that its burn subtree sums to the expected amount. +func assertBurnCommit(t *harnessTest, node unirpc.UniverseClient, + groupKeyBytes []byte, issuerResp *unirpc.FetchSupplyCommitResponse, + burnSum int64) { + + t.t.Helper() + + burnPred := func(resp *unirpc.FetchSupplyCommitResponse) error { + if resp.BurnSubtreeRoot == nil { + return fmt.Errorf("burn subtree root is nil") + } + + actualSum := resp.BurnSubtreeRoot.RootNode.RootSum + if actualSum != burnSum { + return fmt.Errorf("expected burn RootSum %d, got %d", + burnSum, actualSum) + } + + return nil + } + req := unirpc.FetchSupplyCommitRequest{ + GroupKey: &unirpc.FetchSupplyCommitRequest_GroupKeyBytes{ + GroupKeyBytes: groupKeyBytes, + }, + Locator: &unirpc.FetchSupplyCommitRequest_SpentCommitOutpoint{ + SpentCommitOutpoint: issuerResp.SpentCommitmentOutpoint, + }, + } + resp := rpcassert.FetchSupplyCommitRPC( + t.t, context.Background(), node, burnPred, &req, + ) + + assertFetchCommitResponse(t, issuerResp, resp) } // testSupplyCommitSendBeforeCommit mints a grouped asset, sends some of diff --git a/proof/courier.go b/proof/courier.go index 32e19a0aaf..6d6731ef42 100644 --- a/proof/courier.go +++ b/proof/courier.go @@ -1780,6 +1780,18 @@ func FetchProofProvenance(ctx context.Context, localArchive Archiver, // is a reversal of that found in the proof file. var reversedProofs []Blob for { + // The walk follows inputs named by the proofs it fetches, so + // nothing but the source guarantees it reaches a genesis proof. + // Stop once the context ends, or once the chain is longer than + // any proof file may be. + if err := ctx.Err(); err != nil { + return nil, err + } + if len(reversedProofs) >= FileMaxNumProofs { + return nil, fmt.Errorf("%w: provenance exceeds %d "+ + "proofs", ErrProofFileInvalid, FileMaxNumProofs) + } + // Before we attempt to fetch the proof from the potentially // remote universe, we'll check our local archive to see if we // already have it. This doesn't make sense in all cases, so we diff --git a/proof/courier_test.go b/proof/courier_test.go index 3a145fdb42..856b38892b 100644 --- a/proof/courier_test.go +++ b/proof/courier_test.go @@ -151,3 +151,49 @@ func TestCheckUniverseRpcCourierConnection(t *testing.T) { }) } } + +// TestFetchProofProvenanceStopsOnContext tests that a provenance walk that +// never reaches a genesis proof ends once its context does. +func TestFetchProofProvenanceStopsOnContext(t *testing.T) { + t.Parallel() + + testBlocks := readTestData(t) + genesis := asset.RandGenesis(t, asset.Collectible) + scriptKey := test.RandPubKey(t) + transfer := RandProof(t, genesis, scriptKey, testBlocks[0], 0, 1) + + // A transfer that names its own output as its input: following its + // inputs back never arrives at a genesis proof. + outPoint := transfer.OutPoint() + transfer.Asset.PrevWitnesses = []asset.Witness{{ + PrevID: &asset.PrevID{ + OutPoint: outPoint, + ID: genesis.ID(), + ScriptKey: asset.ToSerialized(scriptKey), + }, + }} + transferBlob, err := transfer.Bytes() + require.NoError(t, err) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + const cancelAfter = 3 + var fetches int + fetchSingleProof := func(context.Context, Locator) (Blob, error) { + fetches++ + if fetches == cancelAfter { + cancel() + } + + return transferBlob, nil + } + + _, err = FetchProofProvenance(ctx, nil, Locator{ + AssetID: fn.Ptr(genesis.ID()), + ScriptKey: *scriptKey, + OutPoint: &outPoint, + }, fetchSingleProof) + require.ErrorIs(t, err, context.Canceled) + require.Equal(t, cancelAfter, fetches) +} diff --git a/rpcserver/supplysync_rpc.go b/rpcserver/supplysync_rpc.go index 9d721732ab..d943d0be9e 100644 --- a/rpcserver/supplysync_rpc.go +++ b/rpcserver/supplysync_rpc.go @@ -10,6 +10,7 @@ import ( "github.com/lightninglabs/taproot-assets/fn" "github.com/lightninglabs/taproot-assets/mssmt" "github.com/lightninglabs/taproot-assets/proof" + "github.com/lightninglabs/taproot-assets/rpcutils" "github.com/lightninglabs/taproot-assets/taprpc" unirpc "github.com/lightninglabs/taproot-assets/taprpc/universerpc" "github.com/lightninglabs/taproot-assets/universe" @@ -252,6 +253,74 @@ func (r *RpcSupplySync) FetchSupplyCommit(ctx context.Context, return result, nil } +// InsertProof inserts a single issuance or transfer proof into the remote +// universe server. +func (r *RpcSupplySync) InsertProof(ctx context.Context, + p *proof.Proof) error { + + rawProof, err := p.Bytes() + if err != nil { + return fmt.Errorf("unable to encode proof: %w", err) + } + + var groupKeyBytes []byte + if p.Asset.GroupKey != nil { + groupKey := p.Asset.GroupKey.GroupPubKey + groupKeyBytes = groupKey.SerializeCompressed() + } + + assetID := p.Asset.ID() + _, err = r.conn.InsertProof(ctx, &unirpc.AssetProof{ + Key: &unirpc.UniverseKey{ + Id: rpcutils.MarshalUniverseID( + assetID[:], groupKeyBytes, + ), + LeafKey: rpcutils.MarshalAssetKey( + p.OutPoint(), p.Asset.ScriptKey.PubKey, + ), + }, + AssetLeaf: &unirpc.AssetLeaf{ + Proof: rawProof, + }, + }) + if err != nil { + return fmt.Errorf("unable to insert proof: %w", err) + } + + return nil +} + +// FetchProof fetches the single issuance or transfer proof at the given +// locator from the remote universe server. +func (r *RpcSupplySync) FetchProof(ctx context.Context, + loc proof.Locator) (proof.Blob, error) { + + if loc.AssetID == nil || loc.OutPoint == nil { + return nil, fmt.Errorf("proof locator must specify asset ID " + + "and outpoint") + } + + var groupKeyBytes []byte + if loc.GroupKey != nil { + groupKeyBytes = loc.GroupKey.SerializeCompressed() + } + + resp, err := r.conn.QueryProof(ctx, &unirpc.UniverseKey{ + Id: rpcutils.MarshalUniverseID(loc.AssetID[:], groupKeyBytes), + LeafKey: rpcutils.MarshalAssetKey( + *loc.OutPoint, &loc.ScriptKey, + ), + }) + if err != nil { + return nil, fmt.Errorf("unable to query proof: %w", err) + } + if resp.AssetLeaf == nil { + return nil, fmt.Errorf("universe returned no asset leaf") + } + + return resp.AssetLeaf.Proof, nil +} + // Close closes the RPC connection to the universe server. func (r *RpcSupplySync) Close() error { if r.conn != nil && r.conn.ClientConn != nil { diff --git a/tapcfg/server.go b/tapcfg/server.go index ae9efd126d..f4b2cb8504 100644 --- a/tapcfg/server.go +++ b/tapcfg/server.go @@ -646,6 +646,7 @@ func genServerConfig(cfg *Config, cfgLogger btclog.Logger, ClientFactory: rpcserver.NewRpcSupplySync, Store: supplySyncerStore, UniverseFederationView: federationDB, + LocalProofs: proofArchive, }, ) @@ -681,6 +682,7 @@ func genServerConfig(cfg *Config, cfgLogger btclog.Logger, SupplyTreeView: supplyTreeStore, SupplySyncer: supplySyncer, GroupFetcher: assetMintingStore, + UniverseProofs: multiverse, IssuanceSubscriptions: universeSyncer, DaemonAdapters: lndFsmDaemonAdapters, DisableChainWatch: cfg.Universe.DisableSupplyVerifierChainWatch, diff --git a/tapfreighter/chain_porter.go b/tapfreighter/chain_porter.go index 06ee62532c..a5d7211ce6 100644 --- a/tapfreighter/chain_porter.go +++ b/tapfreighter/chain_porter.go @@ -918,7 +918,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. // @@ -952,9 +951,26 @@ func (p *ChainPorter) storePackageAnchorTxConf(pkg *sendPackage) error { OutPoint: op, } - // Set the block height and header in the burn proof. - b.Proof.BlockHeight = uint32(anchorTxBlockHeight) - b.Proof.BlockHeader = anchorTxBlockHeader + // storeProofs updates a decoded copy of the proof + // suffix, not this virtual-packet suffix. Copy the + // confirmation onto the burn proof, including the + // transaction merkle proof. Burn-leaf verification + // checks that proof. + err := b.Proof.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("unable to update burn "+ + "proof: %w", err) + } if o.Asset.GroupKey != nil { groupKey := o.Asset.GroupKey.GroupPubKey diff --git a/universe/supplyverifier/manager.go b/universe/supplyverifier/manager.go index 3cafb543c7..e99939e4ff 100644 --- a/universe/supplyverifier/manager.go +++ b/universe/supplyverifier/manager.go @@ -12,6 +12,7 @@ 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/tapgarden" "github.com/lightninglabs/taproot-assets/universe" "github.com/lightninglabs/taproot-assets/universe/supplycommit" @@ -84,6 +85,11 @@ type ManagerCfg struct { // GroupFetcher is used to fetch asset group information. GroupFetcher tapgarden.GroupFetcher + // UniverseProofs assembles the full proof file of an asset from the + // local universe. Supply commitments pushed to this node are verified + // against the provenance its own universe holds. + UniverseProofs proof.Exporter + // IssuanceSubscriptions registers verifier state machines to receive // new asset group issuance event notifications. IssuanceSubscriptions IssuanceSubscriptions @@ -129,6 +135,10 @@ func (m *ManagerCfg) Validate() error { return fmt.Errorf("group fetcher is required") } + if m.UniverseProofs == nil { + return fmt.Errorf("universe proofs is required") + } + if m.IssuanceSubscriptions == nil { return fmt.Errorf("issuance subscriptions is required") } @@ -570,6 +580,7 @@ func (m *Manager) InsertSupplyCommit(ctx context.Context, GroupFetcher: m.cfg.GroupFetcher, SupplyCommitView: m.cfg.SupplyCommitView, SupplyTreeView: m.cfg.SupplyTreeView, + Provenance: m.cfg.UniverseProofs, }, ) if err != nil { diff --git a/universe/supplyverifier/syncer.go b/universe/supplyverifier/syncer.go index df02df63a7..dcc87bdf90 100644 --- a/universe/supplyverifier/syncer.go +++ b/universe/supplyverifier/syncer.go @@ -1,7 +1,9 @@ package supplyverifier import ( + "bytes" "context" + "errors" "fmt" "net/url" "sync" @@ -10,6 +12,7 @@ import ( "github.com/btcsuite/btcd/wire" "github.com/lightninglabs/taproot-assets/asset" "github.com/lightninglabs/taproot-assets/fn" + "github.com/lightninglabs/taproot-assets/proof" "github.com/lightninglabs/taproot-assets/universe" "github.com/lightninglabs/taproot-assets/universe/supplycommit" ) @@ -35,6 +38,14 @@ type UniverseClient interface { spentCommitOutpoint fn.Option[wire.OutPoint]) ( supplycommit.FetchSupplyCommitResult, error) + // InsertProof inserts a single issuance or transfer proof into the + // remote universe server. + InsertProof(ctx context.Context, p *proof.Proof) error + + // FetchProof fetches the single issuance or transfer proof at the + // given locator from the remote universe server. + FetchProof(ctx context.Context, loc proof.Locator) (proof.Blob, error) + // Close closes the fetcher and cleans up any resources. Close() error } @@ -75,6 +86,11 @@ type SupplySyncerConfig struct { // UniverseFederationView is used to fetch the list of known // universe servers in the federation. UniverseFederationView UniverseFederationView + + // LocalProofs fetches the full proof files of this node's own + // assets. The provenance of each burn a pushed commitment carries + // is published from them. + LocalProofs proof.Exporter } // SupplySyncer is a struct that is responsible for retrieving supply leaves @@ -116,6 +132,11 @@ func (s *SupplySyncer) pushUniServer(ctx context.Context, } }() + err = s.publishBurnProvenance(ctx, client, updateLeaves) + if err != nil { + return fmt.Errorf("unable to publish burn provenance: %w", err) + } + err = client.InsertSupplyCommit( ctx, assetSpec, commitment, updateLeaves, chainProof, ) @@ -139,6 +160,57 @@ func (s *SupplySyncer) pushUniServer(ctx context.Context, return nil } +// publishBurnProvenance inserts the provenance of each burn's primary input +// into the remote universe, ahead of the commitment that carries the burns. +// A burn leaf's proof is a bare state transition, which the server verifies +// against the provenance its own universe holds. +func (s *SupplySyncer) publishBurnProvenance(ctx context.Context, + client UniverseClient, leaves supplycommit.SupplyLeaves) error { + + for _, burn := range leaves.BurnLeafEntries { + burnProof := burn.BurnProof + if burnProof == nil { + return fmt.Errorf("missing burn proof for burn leaf") + } + + burnOutPoint := burnProof.OutPoint() + blob, err := s.cfg.LocalProofs.FetchProof(ctx, proof.Locator{ + AssetID: fn.Ptr(burnProof.Asset.ID()), + ScriptKey: *burnProof.Asset.ScriptKey.PubKey, + OutPoint: &burnOutPoint, + }) + if err != nil { + return fmt.Errorf("unable to fetch burn proof file: %w", + err) + } + + burnFile, err := blob.AsFile() + if err != nil { + return fmt.Errorf("unable to decode burn proof file: "+ + "%w", err) + } + + // The burn's proof file is its primary input's file with the + // burn appended, so every proof but the last makes up the + // input's provenance. The server absorbs proofs it already + // holds. + for idx := 0; idx < burnFile.NumProofs()-1; idx++ { + p, err := burnFile.ProofAt(uint32(idx)) + if err != nil { + return err + } + + if err := client.InsertProof(ctx, p); err != nil { + return fmt.Errorf("unable to insert proof "+ + "%d of burn input provenance: %w", idx, + err) + } + } + } + + return nil +} + // fetchServerAddrs retrieves the list of universe server addresses that // the syncer uses to interact with remote servers. func (s *SupplySyncer) fetchServerAddrs(ctx context.Context, @@ -408,3 +480,91 @@ func (s *SupplySyncer) PullSupplyCommitment(ctx context.Context, ErrorMap: errorMap, }, nil } + +// Provenance returns a proof exporter that assembles the full proof file of +// an asset from the universe servers the syncer pulls supply commitments +// from. +func (s *SupplySyncer) Provenance( + canonicalUniverses []url.URL) proof.Exporter { + + return &remoteProvenance{ + syncer: s, + canonicalUniverses: canonicalUniverses, + } +} + +// remoteProvenance is a proof exporter backed by remote universe servers. +type remoteProvenance struct { + syncer *SupplySyncer + canonicalUniverses []url.URL +} + +// FetchProof assembles the full proof file of the asset at the given +// locator, trying each target universe server in turn. +// +// NOTE: This is part of the proof.Exporter interface. +func (r *remoteProvenance) FetchProof(ctx context.Context, + loc proof.Locator) (proof.Blob, error) { + + targetAddrs, err := r.syncer.fetchServerAddrs( + ctx, r.canonicalUniverses, + ) + if err != nil { + return nil, fmt.Errorf("unable to fetch target universe "+ + "server addresses: %w", err) + } + if len(targetAddrs) == 0 { + return nil, fmt.Errorf("no universe servers to fetch proof " + + "provenance from") + } + + var fetchErrs []error + for _, serverAddr := range targetAddrs { + // Bound each server's round, as the commitment pull is. + ctxFetch, cancel := context.WithTimeout(ctx, defaultPullTimeout) + blob, err := r.fetchFromServer(ctxFetch, loc, serverAddr) + cancel() + if err == nil { + return blob, nil + } + + fetchErrs = append(fetchErrs, fmt.Errorf("%s: %w", + serverAddr.HostStr(), err)) + } + + return nil, fmt.Errorf("unable to fetch proof provenance: %w", + errors.Join(fetchErrs...)) +} + +// fetchFromServer assembles the full proof file of the asset at the given +// locator from the single proofs held by one universe server. +func (r *remoteProvenance) fetchFromServer(ctx context.Context, + loc proof.Locator, serverAddr universe.ServerAddr) (proof.Blob, + error) { + + client, err := r.syncer.cfg.ClientFactory(serverAddr) + if err != nil { + return nil, fmt.Errorf("unable to create universe client: %w", + err) + } + defer func() { + if closeErr := client.Close(); closeErr != nil { + log.Errorf("Unable to close provenance universe "+ + "client: %v", closeErr) + } + }() + + file, err := proof.FetchProofProvenance( + ctx, nil, loc, client.FetchProof, + ) + if err != nil { + return nil, err + } + + var buf bytes.Buffer + if err := file.Encode(&buf); err != nil { + return nil, fmt.Errorf("unable to encode proof file: %w", err) + } + + return buf.Bytes(), nil +} diff --git a/universe/supplyverifier/transitions.go b/universe/supplyverifier/transitions.go index 4b6502e397..d93a1ea70e 100644 --- a/universe/supplyverifier/transitions.go +++ b/universe/supplyverifier/transitions.go @@ -223,6 +223,9 @@ func (s *SyncVerifyState) ProcessEvent(event Event, GroupFetcher: env.GroupFetcher, SupplyCommitView: env.SupplyCommitView, SupplyTreeView: env.SupplyTreeView, + Provenance: env.SupplySyncer.Provenance( + canonicalUniverses, + ), }, ) if err != nil { diff --git a/universe/supplyverifier/util_test.go b/universe/supplyverifier/util_test.go index ccde539be7..75142720ff 100644 --- a/universe/supplyverifier/util_test.go +++ b/universe/supplyverifier/util_test.go @@ -956,13 +956,14 @@ func taprootKeySpendWitness(t *testing.T, privKey btcec.PrivateKey, } // randBurnProofWithGroupKey constructs a valid burn proof that passes -// burnProof.Verify with real verifiers. It builds on randProofWithGroupKey -// for the genesis proof, then constructs a transfer to a burn key with a -// valid Schnorr witness. The genesis proof is embedded as AdditionalInputs -// so proof.Verify can resolve the previous asset state. +// verification with real verifiers. It builds on randProofWithGroupKey for +// the genesis proof, then constructs a transfer to a burn key with a valid +// Schnorr witness. Like the burn proofs the chain porter records, the burn +// proof is a bare transition: the genesis proof file it spends is returned +// separately as the input's provenance. func randBurnProofWithGroupKey(t *testing.T, groupPrivKey *btcec.PrivateKey, - delegationKey *btcec.PublicKey) proof.Proof { + delegationKey *btcec.PublicKey) (proof.Proof, *proof.File) { t.Helper() @@ -1069,7 +1070,7 @@ func randBurnProofWithGroupKey(t *testing.T, genesisFile, err := proof.NewFile(proof.V0, genesisProof) require.NoError(t, err) - return proof.Proof{ + burnProof := proof.Proof{ PrevOut: prevOutpoint, BlockHeader: burnBlockHeader, BlockHeight: genesisProof.BlockHeight + 1, @@ -1084,8 +1085,9 @@ func randBurnProofWithGroupKey(t *testing.T, TapSiblingPreimage: siblingPreimage, }, }, - AdditionalInputs: []proof.File{*genesisFile}, } + + return burnProof, genesisFile } // createVerifiableCommitment builds a RootCommitment whose chain anchor diff --git a/universe/supplyverifier/verifier.go b/universe/supplyverifier/verifier.go index 1a5bebce3d..95cecbc82b 100644 --- a/universe/supplyverifier/verifier.go +++ b/universe/supplyverifier/verifier.go @@ -42,6 +42,11 @@ type VerifierCfg struct { // SupplyTreeView is used to fetch supply leaves by height. SupplyTreeView SupplyTreeView + + // Provenance assembles the full proof file of an asset from a + // universe. A burn is a state transition, so its leaf verifies only + // against the provenance of the input it consumes. + Provenance proof.Exporter } // Validate performs basic validation on the verifier configuration. @@ -70,6 +75,10 @@ func (v *VerifierCfg) Validate() error { return fmt.Errorf("supply tree view is required") } + if v.Provenance == nil { + return fmt.Errorf("provenance is required") + } + return nil } @@ -609,32 +618,66 @@ func (v *Verifier) verifyIgnoreLeaf(ctx context.Context, return nil } -// verifyBurnLeaf verifies a single burn leaf entry. -func (v *Verifier) verifyBurnLeaf(ctx context.Context, - assetSpec asset.Specifier, burnEntry supplycommit.NewBurnEvent) error { +// burnProofFile assembles the full proof file of a burn: the provenance of +// the burn's primary input, with the burn proof appended. +func (v *Verifier) burnProofFile(ctx context.Context, + burnProof *proof.Proof) (*proof.File, error) { - v.assetLog.Tracef("Verifying burn leaf") + prevID, err := burnProof.Asset.PrimaryPrevID() + if err != nil { + return nil, err + } + if prevID == nil { + return nil, fmt.Errorf("burn asset has no primary input") + } - burnProof := burnEntry.BurnProof - if burnProof == nil { - return fmt.Errorf("missing burn proof for burn leaf") + scriptKey, err := btcec.ParsePubKey(prevID.ScriptKey[:]) + if err != nil { + return nil, fmt.Errorf("unable to parse input script key: %w", + err) } - vCtx := v.proofVerifierCtx(ctx) - lookup, err := vCtx.ChainLookupGen.GenProofChainLookup( - burnProof, - ) + var groupKey *btcec.PublicKey + if burnProof.Asset.GroupKey != nil { + groupKey = &burnProof.Asset.GroupKey.GroupPubKey + } + + inputBlob, err := v.cfg.Provenance.FetchProof(ctx, proof.Locator{ + AssetID: &prevID.ID, + GroupKey: groupKey, + ScriptKey: *scriptKey, + OutPoint: &prevID.OutPoint, + }) if err != nil { - return fmt.Errorf("unable to generate proof chain lookup: %w", + return nil, fmt.Errorf("unable to fetch input provenance: %w", err) } - _, err = burnProof.Verify(ctx, nil, lookup, vCtx) + burnFile, err := inputBlob.AsFile() if err != nil { - return fmt.Errorf("burn leaf proof failed verification: %w", + return nil, fmt.Errorf("unable to decode input provenance: %w", err) } + err = burnFile.AppendProof(*burnProof) + if err != nil { + return nil, fmt.Errorf("unable to append burn proof: %w", err) + } + + return burnFile, nil +} + +// verifyBurnLeaf verifies a single burn leaf entry. +func (v *Verifier) verifyBurnLeaf(ctx context.Context, + assetSpec asset.Specifier, burnEntry supplycommit.NewBurnEvent) error { + + v.assetLog.Tracef("Verifying burn leaf") + + burnProof := burnEntry.BurnProof + if burnProof == nil { + return fmt.Errorf("missing burn proof for burn leaf") + } + // Ensure that the leaf key asset ID matches the asset ID in the burn // proof. leafKeyAssetID := burnEntry.BurnLeaf.UniverseKey.LeafAssetID() @@ -667,6 +710,22 @@ func (v *Verifier) verifyBurnLeaf(ctx context.Context, "does not match expected asset group key") } + // The burn proof is a bare state transition: it carries no + // provenance for the input it consumes. Verify it as the last proof + // of its full proof file, built from that input's provenance. This + // is the costly part, so it runs only once the checks above pass. + burnFile, err := v.burnProofFile(ctx, burnProof) + if err != nil { + return fmt.Errorf("unable to assemble burn proof file: %w", + err) + } + + _, err = burnFile.Verify(ctx, v.proofVerifierCtx(ctx)) + if err != nil { + return fmt.Errorf("burn leaf proof failed verification: %w", + err) + } + return nil } @@ -801,25 +860,36 @@ func (v *Verifier) VerifyCommit(ctx context.Context, len(unspentPreCommits), len(leaves.IssuanceLeafEntries)) } - // Perform validation of the provided supply leaves. - err = v.verifySupplyLeaves(ctx, assetSpec, delegationKey, leaves) - if err != nil { - return fmt.Errorf("unable to verify supply leaves: %w", err) - } - + // Verify the commitment against its predecessor before verifying its + // leaves. Spending the pre-commitment outputs or the previous + // commitment ties the commitment to the issuer, and its root ties the + // leaves to it. Leaf verification can fetch and verify the full + // provenance of every burn, so it only runs for leaves the issuer + // committed to. + // // If the commitment does not specify a spent outpoint, then we dispatch - // to the initial commitment verification routine. + // to the initial commitment verification routine. Otherwise, we + // dispatch to the incremental commitment verification routine. if commitment.SpentCommitment.IsNone() { - return v.verifyInitialCommit( + err = v.verifyInitialCommit( ctx, assetSpec, commitment, leaves, unspentPreCommits, ) + } else { + err = v.verifyIncrementalCommit( + ctx, assetSpec, commitment, leaves, + unspentPreCommits, + ) + } + if err != nil { + return err } - // Otherwise, we dispatch to the incremental commitment verification - // routine. - return v.verifyIncrementalCommit( - ctx, assetSpec, commitment, leaves, - unspentPreCommits, - ) + // Perform validation of the provided supply leaves. + err = v.verifySupplyLeaves(ctx, assetSpec, delegationKey, leaves) + if err != nil { + return fmt.Errorf("unable to verify supply leaves: %w", err) + } + + return nil } diff --git a/universe/supplyverifier/verifier_methods_test.go b/universe/supplyverifier/verifier_methods_test.go index a9420d4726..f2ab7aa1c2 100644 --- a/universe/supplyverifier/verifier_methods_test.go +++ b/universe/supplyverifier/verifier_methods_test.go @@ -1,6 +1,7 @@ package supplyverifier import ( + "bytes" "context" "fmt" "testing" @@ -14,6 +15,7 @@ import ( "github.com/lightninglabs/taproot-assets/fn" internaltest "github.com/lightninglabs/taproot-assets/internal/test" "github.com/lightninglabs/taproot-assets/mssmt" + "github.com/lightninglabs/taproot-assets/proof" "github.com/lightninglabs/taproot-assets/tapgarden" "github.com/lightninglabs/taproot-assets/universe" "github.com/lightninglabs/taproot-assets/universe/supplycommit" @@ -998,6 +1000,120 @@ func TestVerifyCommit(t *testing.T) { mockLookup.AssertExpectations(t) mockTreeView.AssertExpectations(t) }) + + // A commitment that doesn't spend the issuer's pre-commitment output + // is rejected before any provenance is fetched for its burn leaves. + t.Run("unanchored commitment skips provenance", func(t *testing.T) { + ctx := context.Background() + + groupPrivKey, err := btcec.NewPrivateKey() + require.NoError(t, err) + delegKey := createTestDelegationKey(t) + + burnProof, _ := randBurnProofWithGroupKey( + t, groupPrivKey, &delegKey, + ) + groupKey := burnProof.Asset.GroupKey.GroupPubKey + assetSpec := asset.NewSpecifierFromGroupKey(groupKey) + + scriptKey := burnProof.Asset.ScriptKey + burnEntry := supplycommit.NewBurnEvent{ + BurnLeaf: universe.BurnLeaf{ + UniverseKey: universe.AssetLeafKey{ + BaseLeafKey: universe.BaseLeafKey{ + OutPoint: burnProof.OutPoint(), + ScriptKey: &scriptKey, + }, + AssetID: burnProof.Asset.ID(), + }, + BurnProof: &burnProof, + }, + } + leaves := supplycommit.SupplyLeaves{ + BurnLeafEntries: []supplycommit.NewBurnEvent{burnEntry}, + } + + // The commitment spends none of the pre-commitment outputs. + pc := createTestPreCommitment(t, 100, 0, 0) + commitment := createVerifiableCommitment( + t, 200, fn.None[wire.OutPoint](), nil, + ) + + mockView := &MockSupplyCommitView{} + mockLookup := &supplycommit.MockAssetLookup{} + + mockView.On( + "FetchCommitmentByOutpoint", + mock.Anything, + mock.Anything, + commitment.CommitPoint(), + ).Return(nil, ErrCommitmentNotFound).Once() + + setupDelegationKeyMocks(t, mockLookup, &groupKey, &delegKey) + + mockView.On( + "FetchStartingCommitment", + mock.Anything, + mock.Anything, + ).Return(nil, ErrCommitmentNotFound).Once() + + exporter := &countingExporter{} + v := Verifier{ + assetLog: log, + cfg: VerifierCfg{ + ChainBridge: tapgarden.NewMockChainBridge(), + SupplyCommitView: mockView, + AssetLookup: mockLookup, + GroupFetcher: &MockGroupFetcher{}, + Provenance: exporter, + }, + } + + err = v.VerifyCommit( + ctx, assetSpec, commitment, leaves, + supplycommit.PreCommits{pc}, + ) + require.ErrorContains(t, err, "does not spend all known "+ + "pre-commitments") + require.Zero(t, exporter.fetches) + mockView.AssertExpectations(t) + mockLookup.AssertExpectations(t) + }) +} + +// inputProvenance returns a proof archive that holds the given file as the +// provenance of the burn's primary input, keyed the way a universe serves it. +func inputProvenance(t *testing.T, burnProof *proof.Proof, + inputFile *proof.File) *proof.MockProofArchive { + + t.Helper() + + prevID, err := burnProof.Asset.PrimaryPrevID() + require.NoError(t, err) + + scriptKey, err := btcec.ParsePubKey(prevID.ScriptKey[:]) + require.NoError(t, err) + + var buf bytes.Buffer + require.NoError(t, inputFile.Encode(&buf)) + + groupKey := burnProof.Asset.GroupKey.GroupPubKey + archive := proof.NewMockProofArchive() + err = archive.ImportProofs( + context.Background(), proof.VerifierCtx{}, false, + &proof.AnnotatedProof{ + Locator: proof.Locator{ + AssetID: &prevID.ID, + GroupKey: &groupKey, + ScriptKey: *scriptKey, + OutPoint: &prevID.OutPoint, + }, + Blob: buf.Bytes(), + }, + ) + require.NoError(t, err) + + return archive } // TestVerifyBurnLeaf tests verifyBurnLeaf. @@ -1023,14 +1139,20 @@ func TestVerifyBurnLeaf(t *testing.T) { require.ErrorContains(t, err, "missing burn proof") }) - t.Run("valid burn proof", func(t *testing.T) { + // burnLeafCase builds a burn leaf around a bare burn transition, and + // a verifier whose provenance source is chosen by the caller from the + // burn proof and its input's proof file. + burnLeafCase := func(t *testing.T, + provenance func(*proof.Proof, *proof.File) proof.Exporter) ( + Verifier, asset.Specifier, supplycommit.NewBurnEvent) { + groupPrivKey, err := btcec.NewPrivateKey() require.NoError(t, err) delegPrivKey, err := btcec.NewPrivateKey() require.NoError(t, err) - burnProof := randBurnProofWithGroupKey( + burnProof, inputFile := randBurnProofWithGroupKey( t, groupPrivKey, delegPrivKey.PubKey(), ) @@ -1069,10 +1191,89 @@ func TestVerifyBurnLeaf(t *testing.T) { cfg: VerifierCfg{ ChainBridge: tapgarden.NewMockChainBridge(), GroupFetcher: mockGroupFetcher, + Provenance: provenance(&burnProof, inputFile), }, } - err = v.verifyBurnLeaf(ctx, assetSpec, burnEntry) + return v, assetSpec, burnEntry + } + + t.Run("valid burn proof", func(t *testing.T) { + v, assetSpec, burnEntry := burnLeafCase( + t, func(burnProof *proof.Proof, + inputFile *proof.File) proof.Exporter { + + return inputProvenance(t, burnProof, inputFile) + }, + ) + + err := v.verifyBurnLeaf(ctx, assetSpec, burnEntry) require.NoError(t, err) }) + + // A burn proof is a bare transition, so without its input's + // provenance it cannot verify. + t.Run("unknown input provenance", func(t *testing.T) { + v, assetSpec, burnEntry := burnLeafCase( + t, func(*proof.Proof, *proof.File) proof.Exporter { + return proof.NewMockProofArchive() + }, + ) + + err := v.verifyBurnLeaf(ctx, assetSpec, burnEntry) + require.ErrorIs(t, err, proof.ErrProofNotFound) + }) + + // Provenance that doesn't reach back to a genesis proof leaves the + // burn unverified, however valid the transition itself. + t.Run("provenance not rooted at genesis", func(t *testing.T) { + v, assetSpec, burnEntry := burnLeafCase( + t, func(burnProof *proof.Proof, + _ *proof.File) proof.Exporter { + + unrooted, err := proof.NewFile( + proof.V0, *burnProof, + ) + require.NoError(t, err) + + return inputProvenance(t, burnProof, unrooted) + }, + ) + + err := v.verifyBurnLeaf(ctx, assetSpec, burnEntry) + require.ErrorIs(t, err, proof.ErrProofFileInvalid) + }) + + // A burn leaf whose own claims don't hold is rejected before any + // provenance is fetched for it. + t.Run("foreign group rejected before provenance", func(t *testing.T) { + exporter := &countingExporter{} + v, _, burnEntry := burnLeafCase( + t, func(*proof.Proof, *proof.File) proof.Exporter { + return exporter + }, + ) + + err := v.verifyBurnLeaf( + ctx, createTestAssetSpec(t), burnEntry, + ) + require.ErrorContains(t, err, "does not match expected asset "+ + "group key") + require.Zero(t, exporter.fetches) + }) +} + +// countingExporter is a provenance source that holds nothing and counts the +// fetches made of it. +type countingExporter struct { + fetches int +} + +// FetchProof counts the fetch and reports the proof as not found. +func (c *countingExporter) FetchProof(context.Context, + proof.Locator) (proof.Blob, error) { + + c.fetches++ + + return nil, proof.ErrProofNotFound } diff --git a/universe/supplyverifier/verifier_test.go b/universe/supplyverifier/verifier_test.go index 1ddc0e0550..27e628b559 100644 --- a/universe/supplyverifier/verifier_test.go +++ b/universe/supplyverifier/verifier_test.go @@ -7,6 +7,7 @@ import ( "github.com/btcsuite/btcd/wire" "github.com/lightninglabs/lndclient" "github.com/lightninglabs/taproot-assets/fn" + "github.com/lightninglabs/taproot-assets/proof" "github.com/lightninglabs/taproot-assets/tapgarden" "github.com/lightninglabs/taproot-assets/universe/supplycommit" "github.com/stretchr/testify/require" @@ -25,6 +26,7 @@ func newTestVerifierCfg(t *testing.T) VerifierCfg { GroupFetcher: &MockGroupFetcher{}, SupplyCommitView: &MockSupplyCommitView{}, SupplyTreeView: &MockSupplyTreeView{}, + Provenance: proof.NewMockProofArchive(), } } @@ -83,6 +85,13 @@ func TestVerifierCfgValidate(t *testing.T) { }, expectError: true, }, + { + name: "nil provenance", + mutate: func(cfg *VerifierCfg) { + cfg.Provenance = nil + }, + expectError: true, + }, } for _, tt := range tests {