From 516ad171d2c05b9d52d50c173e41a646941f8c6d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Magiera?= Date: Wed, 12 Oct 2022 10:03:22 +0200 Subject: [PATCH] fix: bstore: Handle codecs correctly in membstore Get --- blockstore/mem.go | 3 +++ blockstore/mem_test.go | 45 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 blockstore/mem_test.go diff --git a/blockstore/mem.go b/blockstore/mem.go index 15708dcd4..7cfefafd7 100644 --- a/blockstore/mem.go +++ b/blockstore/mem.go @@ -47,6 +47,9 @@ func (m MemBlockstore) Get(ctx context.Context, k cid.Cid) (blocks.Block, error) if !ok { return nil, ipld.ErrNotFound{Cid: k} } + if b.Cid().Prefix().Codec != k.Prefix().Codec { + return blocks.NewBlockWithCid(b.RawData(), k) + } return b, nil } diff --git a/blockstore/mem_test.go b/blockstore/mem_test.go new file mode 100644 index 000000000..4d4a77624 --- /dev/null +++ b/blockstore/mem_test.go @@ -0,0 +1,45 @@ +package blockstore + +import ( + "context" + "testing" + + blocks "github.com/ipfs/go-block-format" + "github.com/ipfs/go-cid" + mh "github.com/multiformats/go-multihash" + "github.com/stretchr/testify/require" +) + +func TestMemGetCodec(t *testing.T) { + ctx := context.Background() + bs := NewMemory() + + cborArr := []byte{0x82, 1, 2} + + h, err := mh.Sum(cborArr, mh.SHA2_256, -1) + require.NoError(t, err) + + rawCid := cid.NewCidV1(cid.Raw, h) + rawBlk, err := blocks.NewBlockWithCid(cborArr, rawCid) + require.NoError(t, err) + + err = bs.Put(ctx, rawBlk) + require.NoError(t, err) + + cborCid := cid.NewCidV1(cid.DagCBOR, h) + + cborBlk, err := bs.Get(ctx, cborCid) + require.NoError(t, err) + + require.Equal(t, cborCid.Prefix(), cborBlk.Cid().Prefix()) + require.EqualValues(t, cborArr, cborBlk.RawData()) + + // was allocated + require.NotEqual(t, cborBlk, rawBlk) + + gotRawBlk, err := bs.Get(ctx, rawCid) + require.NoError(t, err) + + // not allocated + require.Equal(t, rawBlk, gotRawBlk) +}