graphsync_test.go 16.5 KB
Newer Older
1 2 3 4
package graphsync

import (
	"context"
5
	"errors"
6 7
	"math"
	"math/rand"
8 9 10 11
	"reflect"
	"testing"
	"time"

12
	"github.com/ipld/go-ipld-prime/fluent"
13 14
	ipldfree "github.com/ipld/go-ipld-prime/impl/free"

15
	cidlink "github.com/ipld/go-ipld-prime/linking/cid"
16

17
	blocks "github.com/ipfs/go-block-format"
18
	cid "github.com/ipfs/go-cid"
19
	"github.com/ipfs/go-graphsync"
20

21
	"github.com/ipfs/go-graphsync/ipldbridge"
22 23 24 25 26
	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
27
	ipldselector "github.com/ipld/go-ipld-prime/traversal/selector"
28
	"github.com/ipld/go-ipld-prime/traversal/selector/builder"
29
	"github.com/libp2p/go-libp2p-core/peer"
30
	mocknet "github.com/libp2p/go-libp2p/p2p/net/mock"
31
	mh "github.com/multiformats/go-multihash"
32 33
)

34 35 36 37 38
type receivedMessage struct {
	message gsmsg.GraphSyncMessage
	sender  peer.ID
}

39 40
// Receiver is an interface for receiving messages from the GraphSyncNetwork.
type receiver struct {
41
	messageReceived chan receivedMessage
42 43 44 45 46 47
}

func (r *receiver) ReceiveMessage(
	ctx context.Context,
	sender peer.ID,
	incoming gsmsg.GraphSyncMessage) {
48

49 50
	select {
	case <-ctx.Done():
51
	case r.messageReceived <- receivedMessage{incoming, sender}:
52 53 54 55 56 57
	}
}

func (r *receiver) ReceiveError(err error) {
}

58 59 60 61 62 63
func (r *receiver) Connected(p peer.ID) {
}

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

64 65 66 67 68 69 70 71 72
type blockChain struct {
	genisisNode ipld.Node
	genisisLink ipld.Link
	middleNodes []ipld.Node
	middleLinks []ipld.Link
	tipNode     ipld.Node
	tipLink     ipld.Link
}

73
func createBlock(nb ipldbridge.NodeBuilder, parents []ipld.Link, size int64) ipld.Node {
74 75 76 77 78 79 80
	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) {
81
			lb.Append(vnb.CreateBytes(testutil.RandomBytes(size)))
82 83 84 85 86 87 88 89
		}))
	})
}

func setupBlockChain(
	ctx context.Context,
	t *testing.T,
	storer ipldbridge.Storer,
90 91 92
	bridge ipldbridge.IPLDBridge,
	size int64,
	blockChainLength int) *blockChain {
93
	linkBuilder := cidlink.LinkBuilder{Prefix: cid.NewPrefixV1(cid.DagCBOR, mh.SHA2_256)}
94 95 96 97
	var genisisNode ipld.Node
	err := fluent.Recover(func() {
		nb := fluent.WrapNodeBuilder(ipldfree.NodeBuilder())
		genisisNode = createBlock(nb, []ipld.Link{}, size)
98 99 100 101 102 103 104 105 106 107 108 109
	})
	if err != nil {
		t.Fatal("Error creating genesis block")
	}
	genesisLink, err := linkBuilder.Build(ctx, ipldbridge.LinkContext{}, genisisNode, storer)
	if err != nil {
		t.Fatal("Error creating link to genesis block")
	}
	parent := genesisLink
	middleNodes := make([]ipld.Node, 0, blockChainLength-2)
	middleLinks := make([]ipld.Link, 0, blockChainLength-2)
	for i := 0; i < blockChainLength-2; i++ {
110 111 112 113
		var node ipld.Node
		err := fluent.Recover(func() {
			nb := fluent.WrapNodeBuilder(ipldfree.NodeBuilder())
			node = createBlock(nb, []ipld.Link{parent}, size)
114 115 116 117 118 119 120 121 122 123 124 125
		})
		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
	}
126 127 128 129
	var tipNode ipld.Node
	err = fluent.Recover(func() {
		nb := fluent.WrapNodeBuilder(ipldfree.NodeBuilder())
		tipNode = createBlock(nb, []ipld.Link{parent}, size)
130 131 132 133 134 135 136 137 138 139 140
	})
	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}
}

141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
func TestMakeRequestToNetwork(t *testing.T) {
	// create network
	ctx := context.Background()
	ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
	defer cancel()
	mn := mocknet.New(ctx)

	// setup network
	host1, err := mn.GenPeer()
	if err != nil {
		t.Fatal("error generating host")
	}
	host2, err := mn.GenPeer()
	if err != nil {
		t.Fatal("error generating host")
	}
	err = mn.LinkAll()
	if err != nil {
		t.Fatal("error linking hosts")
	}

	gsnet1 := gsnet.NewFromLibp2pHost(host1)

	// setup receiving peer to just record message coming in
	gsnet2 := gsnet.NewFromLibp2pHost(host2)
	r := &receiver{
167
		messageReceived: make(chan receivedMessage),
168 169 170
	}
	gsnet2.SetDelegate(r)

171 172
	blockStore := make(map[ipld.Link][]byte)
	loader, storer := testbridge.NewMockStore(blockStore)
173
	bridge := ipldbridge.NewIPLDBridge()
174
	graphSync := New(ctx, gsnet1, bridge, loader, storer)
175

176 177 178
	blockChainLength := 100
	blockChain := setupBlockChain(ctx, t, storer, bridge, 100, blockChainLength)

179 180 181 182 183 184
	ssb := builder.NewSelectorSpecBuilder(ipldfree.NodeBuilder())
	spec := ssb.ExploreRecursive(ipldselector.RecursionLimitDepth(blockChainLength),
		ssb.ExploreFields(func(efsb ipldbridge.ExploreFieldsSpecBuilder) {
			efsb.Insert("Parents", ssb.ExploreAll(
				ssb.ExploreRecursiveEdge()))
		})).Node()
185 186 187 188 189 190 191 192

	extensionData := testutil.RandomBytes(100)
	extensionName := graphsync.ExtensionName("AppleSauce/McGee")
	extension := graphsync.ExtensionData{
		Name: extensionName,
		Data: extensionData,
	}

193 194
	requestCtx, requestCancel := context.WithCancel(ctx)
	defer requestCancel()
195
	graphSync.Request(requestCtx, host2.ID(), blockChain.tipLink, spec, extension)
196

197
	var message receivedMessage
198 199 200
	select {
	case <-ctx.Done():
		t.Fatal("did not receive message sent")
201
	case message = <-r.messageReceived:
202 203
	}

204
	sender := message.sender
205 206 207 208
	if sender != host1.ID() {
		t.Fatal("received message from wrong node")
	}

209
	received := message.message
210 211 212 213 214 215 216 217 218 219 220 221
	receivedRequests := received.Requests()
	if len(receivedRequests) != 1 {
		t.Fatal("Did not add request to received message")
	}
	receivedRequest := receivedRequests[0]
	receivedSpec, err := bridge.DecodeNode(receivedRequest.Selector())
	if err != nil {
		t.Fatal("unable to decode transmitted selector")
	}
	if !reflect.DeepEqual(spec, receivedSpec) {
		t.Fatal("did not transmit selector spec correctly")
	}
222 223 224 225
	_, err = bridge.ParseSelector(receivedSpec)
	if err != nil {
		t.Fatal("did not receive parsible selector on other side")
	}
226 227 228 229 230

	returnedData, found := receivedRequest.Extension(extensionName)
	if !found || !reflect.DeepEqual(extensionData, returnedData) {
		t.Fatal("Failed to encode extension")
	}
231
}
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262

func TestSendResponseToIncomingRequest(t *testing.T) {
	// create network
	ctx := context.Background()
	ctx, cancel := context.WithTimeout(ctx, 1*time.Second)
	defer cancel()
	mn := mocknet.New(ctx)

	// setup network
	host1, err := mn.GenPeer()
	if err != nil {
		t.Fatal("error generating host")
	}
	host2, err := mn.GenPeer()
	if err != nil {
		t.Fatal("error generating host")
	}
	err = mn.LinkAll()
	if err != nil {
		t.Fatal("error linking hosts")
	}

	gsnet1 := gsnet.NewFromLibp2pHost(host1)
	r := &receiver{
		messageReceived: make(chan receivedMessage),
	}
	gsnet1.SetDelegate(r)

	// setup receiving peer to just record message coming in
	gsnet2 := gsnet.NewFromLibp2pHost(host2)

263 264
	blockStore := make(map[ipld.Link][]byte)
	loader, storer := testbridge.NewMockStore(blockStore)
265
	bridge := ipldbridge.NewIPLDBridge()
266

267 268 269 270 271 272 273 274 275 276 277 278 279
	extensionData := testutil.RandomBytes(100)
	extensionName := graphsync.ExtensionName("AppleSauce/McGee")
	extension := graphsync.ExtensionData{
		Name: extensionName,
		Data: extensionData,
	}
	extensionResponseData := testutil.RandomBytes(100)
	extensionResponse := graphsync.ExtensionData{
		Name: extensionName,
		Data: extensionResponseData,
	}

	var receivedRequestData []byte
280
	// initialize graphsync on second node to response to requests
281
	gsnet := New(ctx, gsnet2, bridge, loader, storer)
282 283
	err = gsnet.RegisterRequestReceivedHook(
		func(p peer.ID, requestData graphsync.RequestData, hookActions graphsync.RequestReceivedHookActions) {
284 285 286 287 288
			var has bool
			receivedRequestData, has = requestData.Extension(extensionName)
			if !has {
				t.Fatal("did not have expected extension")
			}
289
			hookActions.SendExtensionData(extensionResponse)
290 291 292 293 294
		},
	)
	if err != nil {
		t.Fatal("error registering extension")
	}
295

296 297
	blockChainLength := 100
	blockChain := setupBlockChain(ctx, t, storer, bridge, 100, blockChainLength)
298 299 300 301 302 303
	ssb := builder.NewSelectorSpecBuilder(ipldfree.NodeBuilder())
	spec := ssb.ExploreRecursive(ipldselector.RecursionLimitDepth(blockChainLength),
		ssb.ExploreFields(func(efsb ipldbridge.ExploreFieldsSpecBuilder) {
			efsb.Insert("Parents", ssb.ExploreAll(
				ssb.ExploreRecursiveEdge()))
		})).Node()
304 305 306 307 308

	selectorData, err := bridge.EncodeNode(spec)
	if err != nil {
		t.Fatal("could not encode selector spec")
	}
309
	requestID := graphsync.RequestID(rand.Int31())
310 311

	message := gsmsg.New()
312
	message.AddRequest(gsmsg.NewRequest(requestID, blockChain.tipLink.(cidlink.Link).Cid, selectorData, graphsync.Priority(math.MaxInt32), extension))
313 314 315 316 317
	// send request across network
	gsnet1.SendMessage(ctx, host2.ID(), message)
	// read the values sent back to requestor
	var received gsmsg.GraphSyncMessage
	var receivedBlocks []blocks.Block
318
	var receivedExtensions [][]byte
319 320 321 322 323 324 325 326 327 328 329 330 331 332
readAllMessages:
	for {
		select {
		case <-ctx.Done():
			t.Fatal("did not receive complete response")
		case message := <-r.messageReceived:
			sender := message.sender
			if sender != host2.ID() {
				t.Fatal("received message from wrong node")
			}

			received = message.message
			receivedBlocks = append(receivedBlocks, received.Blocks()...)
			receivedResponses := received.Responses()
333 334 335 336
			receivedExtension, found := receivedResponses[0].Extension(extensionName)
			if found {
				receivedExtensions = append(receivedExtensions, receivedExtension)
			}
337 338 339 340 341 342
			if len(receivedResponses) != 1 {
				t.Fatal("Did not receive response")
			}
			if receivedResponses[0].RequestID() != requestID {
				t.Fatal("Sent response for incorrect request id")
			}
343
			if receivedResponses[0].Status() != graphsync.PartialResponse {
344 345 346 347 348
				break readAllMessages
			}
		}
	}

349
	if len(receivedBlocks) != blockChainLength {
350 351
		t.Fatal("Send incorrect number of blocks or there were duplicate blocks")
	}
352 353 354 355 356 357 358 359 360 361 362 363

	if !reflect.DeepEqual(extensionData, receivedRequestData) {
		t.Fatal("did not receive correct request extension data")
	}

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

	if !reflect.DeepEqual(receivedExtensions[0], extensionResponseData) {
		t.Fatal("did not return correct extension data")
	}
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

func TestGraphsyncRoundTrip(t *testing.T) {
	// create network
	ctx := context.Background()
	ctx, cancel := context.WithTimeout(ctx, 1*time.Second)
	defer cancel()
	mn := mocknet.New(ctx)

	// setup network
	host1, err := mn.GenPeer()
	if err != nil {
		t.Fatal("error generating host")
	}
	host2, err := mn.GenPeer()
	if err != nil {
		t.Fatal("error generating host")
	}
	err = mn.LinkAll()
	if err != nil {
		t.Fatal("error linking hosts")
	}

	gsnet1 := gsnet.NewFromLibp2pHost(host1)

	blockStore1 := make(map[ipld.Link][]byte)
	loader1, storer1 := testbridge.NewMockStore(blockStore1)
391
	bridge1 := ipldbridge.NewIPLDBridge()
392

393
	// initialize graphsync on first node to make requests
394 395 396 397 398 399 400
	requestor := New(ctx, gsnet1, bridge1, loader1, storer1)

	// setup receiving peer to just record message coming in
	gsnet2 := gsnet.NewFromLibp2pHost(host2)

	blockStore2 := make(map[ipld.Link][]byte)
	loader2, storer2 := testbridge.NewMockStore(blockStore2)
401 402
	bridge2 := ipldbridge.NewIPLDBridge()

403 404
	blockChainLength := 100
	blockChain := setupBlockChain(ctx, t, storer2, bridge2, 100, blockChainLength)
405 406

	// initialize graphsync on second node to response to requests
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
	responder := New(ctx, gsnet2, bridge2, loader2, storer2)

	// setup extension handlers
	extensionData := testutil.RandomBytes(100)
	extensionName := graphsync.ExtensionName("AppleSauce/McGee")
	extension := graphsync.ExtensionData{
		Name: extensionName,
		Data: extensionData,
	}
	extensionResponseData := testutil.RandomBytes(100)
	extensionResponse := graphsync.ExtensionData{
		Name: extensionName,
		Data: extensionResponseData,
	}

	var receivedResponseData []byte
	var receivedRequestData []byte

	err = requestor.RegisterResponseReceivedHook(
		func(p peer.ID, responseData graphsync.ResponseData) error {
			data, has := responseData.Extension(extensionName)
			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
		receivedRequestData, has = requestData.Extension(extensionName)
		if !has {
			hookActions.TerminateWithError(errors.New("Missing extension"))
		} else {
			hookActions.SendExtensionData(extensionResponse)
		}
	})

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

451 452 453 454 455 456
	ssb := builder.NewSelectorSpecBuilder(ipldfree.NodeBuilder())
	spec := ssb.ExploreRecursive(ipldselector.RecursionLimitDepth(blockChainLength),
		ssb.ExploreFields(func(efsb ipldbridge.ExploreFieldsSpecBuilder) {
			efsb.Insert("Parents", ssb.ExploreAll(
				ssb.ExploreRecursiveEdge()))
		})).Node()
457

458
	progressChan, errChan := requestor.Request(ctx, host2.ID(), blockChain.tipLink, spec, extension)
459 460 461 462

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

463
	if len(responses) != blockChainLength*2 {
464 465
		t.Fatal("did not traverse all nodes")
	}
466 467
	if len(errs) != 0 {
		t.Fatal("errors during traverse")
468
	}
469
	if len(blockStore1) != blockChainLength {
470 471
		t.Fatal("did not store all blocks")
	}
472 473 474 475 476 477 478 479 480 481 482 483 484 485

	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"
486 487
		}
	}
488 489 490 491 492 493 494 495 496

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

	if !reflect.DeepEqual(receivedResponseData, extensionResponseData) {
		t.Fatal("did not receive correct extension response data")
	}
497
}
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553

// 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()
	mn := mocknet.New(ctx)

	// setup network
	host1, err := mn.GenPeer()
	if err != nil {
		t.Fatal("error generating host")
	}
	host2, err := mn.GenPeer()
	if err != nil {
		t.Fatal("error generating host")
	}
	mn.SetLinkDefaults(mocknet.LinkOptions{Latency: 100 * time.Millisecond, Bandwidth: 3000000})
	err = mn.LinkAll()
	if err != nil {
		t.Fatal("error linking hosts")
	}

	gsnet1 := gsnet.NewFromLibp2pHost(host1)

	blockStore1 := make(map[ipld.Link][]byte)
	loader1, storer1 := testbridge.NewMockStore(blockStore1)
	bridge1 := ipldbridge.NewIPLDBridge()

	// initialize graphsync on first node to make requests
	requestor := New(ctx, gsnet1, bridge1, loader1, storer1)

	// setup receiving peer to just record message coming in
	gsnet2 := gsnet.NewFromLibp2pHost(host2)

	blockStore2 := make(map[ipld.Link][]byte)
	loader2, storer2 := testbridge.NewMockStore(blockStore2)
	bridge2 := ipldbridge.NewIPLDBridge()

	blockChainLength := 40
	blockChain := setupBlockChain(ctx, t, storer2, bridge2, 200000, blockChainLength)

	// initialize graphsync on second node to response to requests
	New(ctx, gsnet2, bridge2, loader2, storer2)

554 555 556 557 558 559
	ssb := builder.NewSelectorSpecBuilder(ipldfree.NodeBuilder())
	spec := ssb.ExploreRecursive(ipldselector.RecursionLimitDepth(blockChainLength),
		ssb.ExploreFields(func(efsb ipldbridge.ExploreFieldsSpecBuilder) {
			efsb.Insert("Parents", ssb.ExploreAll(
				ssb.ExploreRecursiveEdge()))
		})).Node()
560 561 562 563 564 565 566 567 568 569 570 571 572

	progressChan, errChan := requestor.Request(ctx, 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")
	}
}