graphsync_test.go 20.3 KB
Newer Older
1 2 3
package graphsync

import (
4
	"bytes"
5
	"context"
6
	"errors"
7 8
	"io"
	"io/ioutil"
9 10
	"math"
	"math/rand"
11 12
	"os"
	"path/filepath"
13 14 15 16
	"reflect"
	"testing"
	"time"

17
	"github.com/ipld/go-ipld-prime/fluent"
18 19
	ipldfree "github.com/ipld/go-ipld-prime/impl/free"

20
	cidlink "github.com/ipld/go-ipld-prime/linking/cid"
21

22
	blocks "github.com/ipfs/go-block-format"
23
	"github.com/ipfs/go-blockservice"
24
	cid "github.com/ipfs/go-cid"
25 26 27 28 29 30 31 32 33 34 35 36
	"github.com/ipfs/go-datastore"
	dss "github.com/ipfs/go-datastore/sync"
	bstore "github.com/ipfs/go-ipfs-blockstore"
	chunker "github.com/ipfs/go-ipfs-chunker"
	offline "github.com/ipfs/go-ipfs-exchange-offline"
	files "github.com/ipfs/go-ipfs-files"
	ipldformat "github.com/ipfs/go-ipld-format"
	"github.com/ipfs/go-merkledag"
	unixfile "github.com/ipfs/go-unixfs/file"
	"github.com/ipfs/go-unixfs/importer/balanced"
	ihelper "github.com/ipfs/go-unixfs/importer/helpers"

37
	"github.com/ipfs/go-graphsync"
38

39
	"github.com/ipfs/go-graphsync/ipldbridge"
40 41 42 43 44
	gsmsg "github.com/ipfs/go-graphsync/message"
	gsnet "github.com/ipfs/go-graphsync/network"
	"github.com/ipfs/go-graphsync/testbridge"
	"github.com/ipfs/go-graphsync/testutil"
	ipld "github.com/ipld/go-ipld-prime"
Edgar Lee's avatar
Edgar Lee committed
45
	ipldselector "github.com/ipld/go-ipld-prime/traversal/selector"
46
	"github.com/ipld/go-ipld-prime/traversal/selector/builder"
47
	"github.com/libp2p/go-libp2p-core/host"
48
	"github.com/libp2p/go-libp2p-core/peer"
49
	mocknet "github.com/libp2p/go-libp2p/p2p/net/mock"
50
	mh "github.com/multiformats/go-multihash"
51 52 53 54 55 56 57
)

func TestMakeRequestToNetwork(t *testing.T) {
	// create network
	ctx := context.Background()
	ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
	defer cancel()
58
	td := newGsTestData(ctx, t)
59
	r := &receiver{
60
		messageReceived: make(chan receivedMessage),
61
	}
62 63
	td.gsnet2.SetDelegate(r)
	graphSync := td.GraphSyncHost1()
64

65
	blockChainLength := 100
66
	blockChain := setupBlockChain(ctx, t, td.storer1, td.bridge, 100, blockChainLength)
67

68
	spec := blockChainSelector(blockChainLength)
69

70 71
	requestCtx, requestCancel := context.WithCancel(ctx)
	defer requestCancel()
72
	graphSync.Request(requestCtx, td.host2.ID(), blockChain.tipLink, spec, td.extension)
73

74
	var message receivedMessage
75 76 77
	select {
	case <-ctx.Done():
		t.Fatal("did not receive message sent")
78
	case message = <-r.messageReceived:
79 80
	}

81
	sender := message.sender
82
	if sender != td.host1.ID() {
83 84 85
		t.Fatal("received message from wrong node")
	}

86
	received := message.message
87 88 89 90 91
	receivedRequests := received.Requests()
	if len(receivedRequests) != 1 {
		t.Fatal("Did not add request to received message")
	}
	receivedRequest := receivedRequests[0]
92
	receivedSpec, err := td.bridge.DecodeNode(receivedRequest.Selector())
93 94 95 96 97 98
	if err != nil {
		t.Fatal("unable to decode transmitted selector")
	}
	if !reflect.DeepEqual(spec, receivedSpec) {
		t.Fatal("did not transmit selector spec correctly")
	}
99
	_, err = td.bridge.ParseSelector(receivedSpec)
100 101 102
	if err != nil {
		t.Fatal("did not receive parsible selector on other side")
	}
103

104 105
	returnedData, found := receivedRequest.Extension(td.extensionName)
	if !found || !reflect.DeepEqual(td.extensionData, returnedData) {
106 107
		t.Fatal("Failed to encode extension")
	}
108
}
109 110 111 112 113 114

func TestSendResponseToIncomingRequest(t *testing.T) {
	// create network
	ctx := context.Background()
	ctx, cancel := context.WithTimeout(ctx, 1*time.Second)
	defer cancel()
115
	td := newGsTestData(ctx, t)
116 117 118
	r := &receiver{
		messageReceived: make(chan receivedMessage),
	}
119
	td.gsnet1.SetDelegate(r)
120 121

	var receivedRequestData []byte
122
	// initialize graphsync on second node to response to requests
123 124
	gsnet := td.GraphSyncHost2()
	err := gsnet.RegisterRequestReceivedHook(
125
		func(p peer.ID, requestData graphsync.RequestData, hookActions graphsync.RequestReceivedHookActions) {
126
			var has bool
127
			receivedRequestData, has = requestData.Extension(td.extensionName)
128 129 130
			if !has {
				t.Fatal("did not have expected extension")
			}
131
			hookActions.SendExtensionData(td.extensionResponse)
132 133 134 135 136
		},
	)
	if err != nil {
		t.Fatal("error registering extension")
	}
137

138
	blockChainLength := 100
139
	blockChain := setupBlockChain(ctx, t, td.storer2, td.bridge, 100, blockChainLength)
140

141 142 143
	spec := blockChainSelector(blockChainLength)

	selectorData, err := td.bridge.EncodeNode(spec)
144 145 146
	if err != nil {
		t.Fatal("could not encode selector spec")
	}
147
	requestID := graphsync.RequestID(rand.Int31())
148 149

	message := gsmsg.New()
150
	message.AddRequest(gsmsg.NewRequest(requestID, blockChain.tipLink.(cidlink.Link).Cid, selectorData, graphsync.Priority(math.MaxInt32), td.extension))
151
	// send request across network
152
	td.gsnet1.SendMessage(ctx, td.host2.ID(), message)
153 154 155
	// read the values sent back to requestor
	var received gsmsg.GraphSyncMessage
	var receivedBlocks []blocks.Block
156
	var receivedExtensions [][]byte
157 158 159 160 161 162 163
readAllMessages:
	for {
		select {
		case <-ctx.Done():
			t.Fatal("did not receive complete response")
		case message := <-r.messageReceived:
			sender := message.sender
164
			if sender != td.host2.ID() {
165 166 167 168 169 170
				t.Fatal("received message from wrong node")
			}

			received = message.message
			receivedBlocks = append(receivedBlocks, received.Blocks()...)
			receivedResponses := received.Responses()
171
			receivedExtension, found := receivedResponses[0].Extension(td.extensionName)
172 173 174
			if found {
				receivedExtensions = append(receivedExtensions, receivedExtension)
			}
175 176 177 178 179 180
			if len(receivedResponses) != 1 {
				t.Fatal("Did not receive response")
			}
			if receivedResponses[0].RequestID() != requestID {
				t.Fatal("Sent response for incorrect request id")
			}
181
			if receivedResponses[0].Status() != graphsync.PartialResponse {
182 183 184 185 186
				break readAllMessages
			}
		}
	}

187
	if len(receivedBlocks) != blockChainLength {
188 189
		t.Fatal("Send incorrect number of blocks or there were duplicate blocks")
	}
190

191
	if !reflect.DeepEqual(td.extensionData, receivedRequestData) {
192 193 194 195 196 197 198
		t.Fatal("did not receive correct request extension data")
	}

	if len(receivedExtensions) != 1 {
		t.Fatal("should have sent extension responses but didn't")
	}

199
	if !reflect.DeepEqual(receivedExtensions[0], td.extensionResponseData) {
200 201
		t.Fatal("did not return correct extension data")
	}
202
}
203 204 205 206 207 208

func TestGraphsyncRoundTrip(t *testing.T) {
	// create network
	ctx := context.Background()
	ctx, cancel := context.WithTimeout(ctx, 1*time.Second)
	defer cancel()
209
	td := newGsTestData(ctx, t)
210

211
	// initialize graphsync on first node to make requests
212
	requestor := td.GraphSyncHost1()
213 214

	// setup receiving peer to just record message coming in
215
	blockChainLength := 100
216
	blockChain := setupBlockChain(ctx, t, td.storer2, td.bridge, 100, blockChainLength)
217 218

	// initialize graphsync on second node to response to requests
219
	responder := td.GraphSyncHost2()
220 221 222 223

	var receivedResponseData []byte
	var receivedRequestData []byte

224
	err := requestor.RegisterResponseReceivedHook(
225
		func(p peer.ID, responseData graphsync.ResponseData) error {
226
			data, has := responseData.Extension(td.extensionName)
227 228 229 230 231 232 233 234 235 236 237
			if has {
				receivedResponseData = data
			}
			return nil
		})
	if err != nil {
		t.Fatal("Error setting up extension")
	}

	err = responder.RegisterRequestReceivedHook(func(p peer.ID, requestData graphsync.RequestData, hookActions graphsync.RequestReceivedHookActions) {
		var has bool
238
		receivedRequestData, has = requestData.Extension(td.extensionName)
239 240 241
		if !has {
			hookActions.TerminateWithError(errors.New("Missing extension"))
		} else {
242
			hookActions.SendExtensionData(td.extensionResponse)
243 244 245 246 247 248
		}
	})

	if err != nil {
		t.Fatal("Error setting up extension")
	}
249

250
	spec := blockChainSelector(blockChainLength)
251

252
	progressChan, errChan := requestor.Request(ctx, td.host2.ID(), blockChain.tipLink, spec, td.extension)
253 254 255 256

	responses := testutil.CollectResponses(ctx, t, progressChan)
	errs := testutil.CollectErrors(ctx, t, errChan)

257
	if len(responses) != blockChainLength*2 {
258 259
		t.Fatal("did not traverse all nodes")
	}
260 261
	if len(errs) != 0 {
		t.Fatal("errors during traverse")
262
	}
263
	if len(td.blockStore1) != blockChainLength {
264 265
		t.Fatal("did not store all blocks")
	}
266 267 268 269 270 271 272 273 274 275 276 277 278 279

	expectedPath := ""
	for i, response := range responses {
		if response.Path.String() != expectedPath {
			t.Fatal("incorrect path")
		}
		if i%2 == 0 {
			if expectedPath == "" {
				expectedPath = "Parents"
			} else {
				expectedPath = expectedPath + "/Parents"
			}
		} else {
			expectedPath = expectedPath + "/0"
280 281
		}
	}
282 283

	// verify extension roundtrip
284
	if !reflect.DeepEqual(receivedRequestData, td.extensionData) {
285 286 287
		t.Fatal("did not receive correct extension request data")
	}

288
	if !reflect.DeepEqual(receivedResponseData, td.extensionResponseData) {
289 290
		t.Fatal("did not receive correct extension response data")
	}
291
}
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308

// TestRoundTripLargeBlocksSlowNetwork test verifies graphsync continues to work
// under a specific of adverse conditions:
// -- large blocks being returned by a query
// -- slow network connection
// It verifies that Graphsync will properly break up network message packets
// so they can still be decoded on the client side, instead of building up a huge
// backlog of blocks and then sending them in one giant network packet that can't
// be decoded on the client side
func TestRoundTripLargeBlocksSlowNetwork(t *testing.T) {
	// create network
	if testing.Short() {
		t.Skip()
	}
	ctx := context.Background()
	ctx, cancel := context.WithTimeout(ctx, 20*time.Second)
	defer cancel()
309 310 311 312 313
	td := newGsTestData(ctx, t)
	td.mn.SetLinkDefaults(mocknet.LinkOptions{Latency: 100 * time.Millisecond, Bandwidth: 3000000})

	// initialize graphsync on first node to make requests
	requestor := td.GraphSyncHost1()
314

315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
	// setup receiving peer to just record message coming in
	blockChainLength := 40
	blockChain := setupBlockChain(ctx, t, td.storer2, td.bridge, 200000, blockChainLength)

	// initialize graphsync on second node to response to requests
	td.GraphSyncHost2()

	spec := blockChainSelector(blockChainLength)
	progressChan, errChan := requestor.Request(ctx, td.host2.ID(), blockChain.tipLink, spec)

	responses := testutil.CollectResponses(ctx, t, progressChan)
	errs := testutil.CollectErrors(ctx, t, errChan)

	if len(responses) != blockChainLength*2 {
		t.Fatal("did not traverse all nodes")
	}
	if len(errs) != 0 {
		t.Fatal("errors during traverse")
	}
}

336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
// What this test does:
// - Construct a blockstore + dag service
// - Import a file to UnixFS v1
// - setup a graphsync request from one node to the other
// for the file
// - Load the file from the new block store on the other node
// using the
// existing UnixFS v1 file reader
// - Verify the bytes match the original
func TestUnixFSFetch(t *testing.T) {
	if testing.Short() {
		t.Skip()
	}

	const unixfsChunkSize uint64 = 1 << 10
	const unixfsLinksPerLevel = 1024

	ctx := context.Background()
	ctx, cancel := context.WithTimeout(ctx, 20*time.Second)
	defer cancel()

	makeLoader := func(bs bstore.Blockstore) ipld.Loader {
		return func(lnk ipld.Link, lnkCtx ipld.LinkContext) (io.Reader, error) {
			c, ok := lnk.(cidlink.Link)
			if !ok {
				return nil, errors.New("Incorrect Link Type")
			}
			// read block from one store
			block, err := bs.Get(c.Cid)
			if err != nil {
				return nil, err
			}
			return bytes.NewReader(block.RawData()), nil
		}
	}

	makeStorer := func(bs bstore.Blockstore) ipld.Storer {
		return func(lnkCtx ipld.LinkContext) (io.Writer, ipld.StoreCommitter, error) {
			var buf bytes.Buffer
			var committer ipld.StoreCommitter = func(lnk ipld.Link) error {
				c, ok := lnk.(cidlink.Link)
				if !ok {
					return errors.New("Incorrect Link Type")
				}
				block, err := blocks.NewBlockWithCid(buf.Bytes(), c.Cid)
				if err != nil {
					return err
				}
				return bs.Put(block)
			}
			return &buf, committer, nil
		}
	}
	// make a blockstore and dag service
	bs1 := bstore.NewBlockstore(dss.MutexWrap(datastore.NewMapDatastore()))

	// make a second blockstore
	bs2 := bstore.NewBlockstore(dss.MutexWrap(datastore.NewMapDatastore()))
	dagService2 := merkledag.NewDAGService(blockservice.New(bs2, offline.Exchange(bs2)))

	// read in a fixture file
	path, err := filepath.Abs(filepath.Join("fixtures", "lorem.txt"))
	if err != nil {
		t.Fatal("unable to create path for fixture file")
	}

	f, err := os.Open(path)
	if err != nil {
		t.Fatal("unable to open fixture file")
	}
	var buf bytes.Buffer
	tr := io.TeeReader(f, &buf)
	file := files.NewReaderFile(tr)

	// import to UnixFS
	bufferedDS := ipldformat.NewBufferedDAG(ctx, dagService2)

	params := ihelper.DagBuilderParams{
		Maxlinks:   unixfsLinksPerLevel,
		RawLeaves:  true,
		CidBuilder: nil,
		Dagserv:    bufferedDS,
	}

	db, err := params.New(chunker.NewSizeSplitter(file, int64(unixfsChunkSize)))
	if err != nil {
		t.Fatal("unable to setup dag builder")
	}
	nd, err := balanced.Layout(db)
	if err != nil {
		t.Fatal("unable to create unix fs node")
	}
	err = bufferedDS.Commit()
	if err != nil {
		t.Fatal("unable to commit unix fs node")
	}

	// save the original files bytes
	origBytes := buf.Bytes()

	// setup an IPLD loader/storer for blockstore 1
	loader1 := makeLoader(bs1)
	storer1 := makeStorer(bs1)

	// setup an IPLD loader/storer for blockstore 2
	loader2 := makeLoader(bs2)
	storer2 := makeStorer(bs2)

	td := newGsTestData(ctx, t)
	requestor := New(ctx, td.gsnet1, td.bridge, loader1, storer1)
	responder := New(ctx, td.gsnet2, td.bridge, loader2, storer2)
	extensionName := graphsync.ExtensionName("Free for all")
	responder.RegisterRequestReceivedHook(func(p peer.ID, requestData graphsync.RequestData, hookActions graphsync.RequestReceivedHookActions) {
		hookActions.ValidateRequest()
		hookActions.SendExtensionData(graphsync.ExtensionData{
			Name: extensionName,
			Data: nil,
		})
	})
	// make a go-ipld-prime link for the root UnixFS node
	clink := cidlink.Link{Cid: nd.Cid()}

	// create a selector for the whole UnixFS dag
	ssb := builder.NewSelectorSpecBuilder(ipldfree.NodeBuilder())

	allSelector := ssb.ExploreRecursive(ipldselector.RecursionLimitNone(),
		ssb.ExploreAll(ssb.ExploreRecursiveEdge())).Node()

	// execute the traversal
	progressChan, errChan := requestor.Request(ctx, td.host2.ID(), clink, allSelector,
		graphsync.ExtensionData{
			Name: extensionName,
			Data: nil,
		})

	_ = testutil.CollectResponses(ctx, t, progressChan)
	responseErrors := testutil.CollectErrors(ctx, t, errChan)

	// verify traversal was successful
	if len(responseErrors) != 0 {
		t.Fatal("Response should be successful but wasn't")
	}

	// setup a DagService for the second block store
	dagService1 := merkledag.NewDAGService(blockservice.New(bs1, offline.Exchange(bs1)))

	// load the root of the UnixFS DAG from the new blockstore
	otherNode, err := dagService1.Get(ctx, nd.Cid())
	if err != nil {
		t.Fatal("should have been able to read received root node but didn't")
	}

	// Setup a UnixFS file reader
	n, err := unixfile.NewUnixfsFile(ctx, dagService1, otherNode)
	if err != nil {
		t.Fatal("should have been able to setup UnixFS file but wasn't")
	}

	fn, ok := n.(files.File)
	if !ok {
		t.Fatal("file should be a regular file, but wasn't")
	}

	// Read the bytes for the UnixFS File
	finalBytes, err := ioutil.ReadAll(fn)
	if err != nil {
		t.Fatal("should have been able to read all of unix FS file but wasn't")
	}

	// verify original bytes match final bytes!
	if !reflect.DeepEqual(origBytes, finalBytes) {
		t.Fatal("should have gotten same bytes written as read but didn't")
	}

}

512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
type gsTestData struct {
	mn                       mocknet.Mocknet
	ctx                      context.Context
	host1                    host.Host
	host2                    host.Host
	gsnet1                   gsnet.GraphSyncNetwork
	gsnet2                   gsnet.GraphSyncNetwork
	blockStore1, blockStore2 map[ipld.Link][]byte
	loader1, loader2         ipld.Loader
	storer1, storer2         ipld.Storer
	bridge                   ipldbridge.IPLDBridge
	extensionData            []byte
	extensionName            graphsync.ExtensionName
	extension                graphsync.ExtensionData
	extensionResponseData    []byte
	extensionResponse        graphsync.ExtensionData
}

func newGsTestData(ctx context.Context, t *testing.T) *gsTestData {
	td := &gsTestData{ctx: ctx}
	td.mn = mocknet.New(ctx)
	var err error
534
	// setup network
535
	td.host1, err = td.mn.GenPeer()
536 537 538
	if err != nil {
		t.Fatal("error generating host")
	}
539
	td.host2, err = td.mn.GenPeer()
540 541 542
	if err != nil {
		t.Fatal("error generating host")
	}
543
	err = td.mn.LinkAll()
544 545 546 547
	if err != nil {
		t.Fatal("error linking hosts")
	}

548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
	td.gsnet1 = gsnet.NewFromLibp2pHost(td.host1)
	td.gsnet2 = gsnet.NewFromLibp2pHost(td.host2)
	td.blockStore1 = make(map[ipld.Link][]byte)
	td.loader1, td.storer1 = testbridge.NewMockStore(td.blockStore1)
	td.blockStore2 = make(map[ipld.Link][]byte)
	td.loader2, td.storer2 = testbridge.NewMockStore(td.blockStore2)
	td.bridge = ipldbridge.NewIPLDBridge()
	// setup extension handlers
	td.extensionData = testutil.RandomBytes(100)
	td.extensionName = graphsync.ExtensionName("AppleSauce/McGee")
	td.extension = graphsync.ExtensionData{
		Name: td.extensionName,
		Data: td.extensionData,
	}
	td.extensionResponseData = testutil.RandomBytes(100)
	td.extensionResponse = graphsync.ExtensionData{
		Name: td.extensionName,
		Data: td.extensionResponseData,
	}
567

568 569
	return td
}
570

571 572 573
func (td *gsTestData) GraphSyncHost1() graphsync.GraphExchange {
	return New(td.ctx, td.gsnet1, td.bridge, td.loader1, td.storer1)
}
574

575
func (td *gsTestData) GraphSyncHost2() graphsync.GraphExchange {
576

577 578
	return New(td.ctx, td.gsnet2, td.bridge, td.loader2, td.storer2)
}
579

580 581 582 583
type receivedMessage struct {
	message gsmsg.GraphSyncMessage
	sender  peer.ID
}
584

585 586 587 588
// Receiver is an interface for receiving messages from the GraphSyncNetwork.
type receiver struct {
	messageReceived chan receivedMessage
}
589

590 591 592 593
func (r *receiver) ReceiveMessage(
	ctx context.Context,
	sender peer.ID,
	incoming gsmsg.GraphSyncMessage) {
594

595 596 597 598 599
	select {
	case <-ctx.Done():
	case r.messageReceived <- receivedMessage{incoming, sender}:
	}
}
600

601 602
func (r *receiver) ReceiveError(err error) {
}
603

604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
func (r *receiver) Connected(p peer.ID) {
}

func (r *receiver) Disconnected(p peer.ID) {
}

type blockChain struct {
	genisisNode ipld.Node
	genisisLink ipld.Link
	middleNodes []ipld.Node
	middleLinks []ipld.Link
	tipNode     ipld.Node
	tipLink     ipld.Link
}

func createBlock(nb ipldbridge.NodeBuilder, parents []ipld.Link, size int64) ipld.Node {
	return nb.CreateMap(func(mb ipldbridge.MapBuilder, knb ipldbridge.NodeBuilder, vnb ipldbridge.NodeBuilder) {
		mb.Insert(knb.CreateString("Parents"), vnb.CreateList(func(lb ipldbridge.ListBuilder, vnb ipldbridge.NodeBuilder) {
			for _, parent := range parents {
				lb.Append(vnb.CreateLink(parent))
			}
		}))
		mb.Insert(knb.CreateString("Messages"), vnb.CreateList(func(lb ipldbridge.ListBuilder, vnb ipldbridge.NodeBuilder) {
			lb.Append(vnb.CreateBytes(testutil.RandomBytes(size)))
		}))
	})
}

func setupBlockChain(
	ctx context.Context,
	t *testing.T,
	storer ipldbridge.Storer,
	bridge ipldbridge.IPLDBridge,
	size int64,
	blockChainLength int) *blockChain {
	linkBuilder := cidlink.LinkBuilder{Prefix: cid.NewPrefixV1(cid.DagCBOR, mh.SHA2_256)}
	var genisisNode ipld.Node
	err := fluent.Recover(func() {
		nb := fluent.WrapNodeBuilder(ipldfree.NodeBuilder())
		genisisNode = createBlock(nb, []ipld.Link{}, size)
	})
	if err != nil {
		t.Fatal("Error creating genesis block")
647
	}
648 649 650
	genesisLink, err := linkBuilder.Build(ctx, ipldbridge.LinkContext{}, genisisNode, storer)
	if err != nil {
		t.Fatal("Error creating link to genesis block")
651
	}
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
	parent := genesisLink
	middleNodes := make([]ipld.Node, 0, blockChainLength-2)
	middleLinks := make([]ipld.Link, 0, blockChainLength-2)
	for i := 0; i < blockChainLength-2; i++ {
		var node ipld.Node
		err := fluent.Recover(func() {
			nb := fluent.WrapNodeBuilder(ipldfree.NodeBuilder())
			node = createBlock(nb, []ipld.Link{parent}, size)
		})
		if err != nil {
			t.Fatal("Error creating middle block")
		}
		middleNodes = append(middleNodes, node)
		link, err := linkBuilder.Build(ctx, ipldbridge.LinkContext{}, node, storer)
		if err != nil {
			t.Fatal("Error creating link to middle block")
		}
		middleLinks = append(middleLinks, link)
		parent = link
	}
	var tipNode ipld.Node
	err = fluent.Recover(func() {
		nb := fluent.WrapNodeBuilder(ipldfree.NodeBuilder())
		tipNode = createBlock(nb, []ipld.Link{parent}, size)
	})
	if err != nil {
		t.Fatal("Error creating tip block")
	}
	tipLink, err := linkBuilder.Build(ctx, ipldbridge.LinkContext{}, tipNode, storer)
	if err != nil {
		t.Fatal("Error creating link to tip block")
	}
	return &blockChain{genisisNode, genesisLink, middleNodes, middleLinks, tipNode, tipLink}
}

func blockChainSelector(blockChainLength int) ipld.Node {
	ssb := builder.NewSelectorSpecBuilder(ipldfree.NodeBuilder())
	return ssb.ExploreRecursive(ipldselector.RecursionLimitDepth(blockChainLength),
		ssb.ExploreFields(func(efsb ipldbridge.ExploreFieldsSpecBuilder) {
			efsb.Insert("Parents", ssb.ExploreAll(
				ssb.ExploreRecursiveEdge()))
		})).Node()
694
}