unverifiedblockstore_test.go 1.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
package unverifiedblockstore

import (
	"bytes"
	"io"
	"reflect"
	"testing"

	"github.com/ipfs/go-graphsync/ipldbridge"

	"github.com/ipld/go-ipld-prime"

	"github.com/ipfs/go-graphsync/testbridge"
	"github.com/ipfs/go-graphsync/testutil"

	"github.com/ipld/go-ipld-prime/linking/cid"
)

func TestVerifyBlockPresent(t *testing.T) {
	blocksWritten := make(map[ipld.Link][]byte)
	loader, storer := testbridge.NewMockStore(blocksWritten)
	unverifiedBlockStore := New(storer)
	block := testutil.GenerateBlocksOfSize(1, 100)[0]
	reader, err := loader(cidlink.Link{Cid: block.Cid()}, ipldbridge.LinkContext{})
	if reader != nil || err == nil {
		t.Fatal("block should not be loadable till it's verified and stored")
	}
	data, err := unverifiedBlockStore.VerifyBlock(cidlink.Link{Cid: block.Cid()})
	if data != nil || err == nil {
		t.Fatal("block should not be verifiable till it's added as an unverifiable block")
	}
	unverifiedBlockStore.AddUnverifiedBlock(cidlink.Link{Cid: block.Cid()}, block.RawData())
	reader, err = loader(cidlink.Link{Cid: block.Cid()}, ipldbridge.LinkContext{})
	if reader != nil || err == nil {
		t.Fatal("block should not be loadable till it's verified and stored")
	}
	data, err = unverifiedBlockStore.VerifyBlock(cidlink.Link{Cid: block.Cid()})
	if !reflect.DeepEqual(data, block.RawData()) || err != nil {
		t.Fatal("block should be returned on verification if added")
	}
	reader, err = loader(cidlink.Link{Cid: block.Cid()}, ipldbridge.LinkContext{})
	var buffer bytes.Buffer
	io.Copy(&buffer, reader)
	if !reflect.DeepEqual(buffer.Bytes(), block.RawData()) || err != nil {
		t.Fatal("block should be stored after verification and therefore loadable")
	}
	data, err = unverifiedBlockStore.VerifyBlock(cidlink.Link{Cid: block.Cid()})
	if data != nil || err == nil {
		t.Fatal("block cannot be verified twice")
	}
}