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

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

11
	cidlink "github.com/ipld/go-ipld-prime/linking/cid"
12

13
	blocks "github.com/ipfs/go-block-format"
14
	cid "github.com/ipfs/go-cid"
15
	"github.com/ipfs/go-graphsync"
16

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

29 30 31 32 33
type receivedMessage struct {
	message gsmsg.GraphSyncMessage
	sender  peer.ID
}

34 35
// Receiver is an interface for receiving messages from the GraphSyncNetwork.
type receiver struct {
36
	messageReceived chan receivedMessage
37 38 39 40 41 42
}

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

44 45
	select {
	case <-ctx.Done():
46
	case r.messageReceived <- receivedMessage{incoming, sender}:
47 48 49 50 51 52
	}
}

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

53 54 55 56 57 58
func (r *receiver) Connected(p peer.ID) {
}

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

59 60 61 62 63 64 65 66 67
type blockChain struct {
	genisisNode ipld.Node
	genisisLink ipld.Link
	middleNodes []ipld.Node
	middleLinks []ipld.Link
	tipNode     ipld.Node
	tipLink     ipld.Link
}

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

func setupBlockChain(
	ctx context.Context,
	t *testing.T,
	storer ipldbridge.Storer,
85 86 87
	bridge ipldbridge.IPLDBridge,
	size int64,
	blockChainLength int) *blockChain {
88 89
	linkBuilder := cidlink.LinkBuilder{Prefix: cid.NewPrefixV1(cid.DagCBOR, mh.SHA2_256)}
	genisisNode, err := bridge.BuildNode(func(nb ipldbridge.NodeBuilder) ipld.Node {
90
		return createBlock(nb, []ipld.Link{}, size)
91 92 93 94 95 96 97 98 99 100 101 102 103
	})
	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++ {
		node, err := bridge.BuildNode(func(nb ipldbridge.NodeBuilder) ipld.Node {
104
			return createBlock(nb, []ipld.Link{parent}, size)
105 106 107 108 109 110 111 112 113 114 115 116 117
		})
		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
	}
	tipNode, err := bridge.BuildNode(func(nb ipldbridge.NodeBuilder) ipld.Node {
118
		return createBlock(nb, []ipld.Link{parent}, size)
119 120 121 122 123 124 125 126 127 128 129
	})
	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}
}

130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
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{
156
		messageReceived: make(chan receivedMessage),
157 158 159
	}
	gsnet2.SetDelegate(r)

160 161
	blockStore := make(map[ipld.Link][]byte)
	loader, storer := testbridge.NewMockStore(blockStore)
162
	bridge := ipldbridge.NewIPLDBridge()
163
	graphSync := New(ctx, gsnet1, bridge, loader, storer)
164

165 166 167
	blockChainLength := 100
	blockChain := setupBlockChain(ctx, t, storer, bridge, 100, blockChainLength)

168
	spec, err := bridge.BuildSelector(func(ssb ipldbridge.SelectorSpecBuilder) ipldbridge.SelectorSpec {
Edgar Lee's avatar
Edgar Lee committed
169
		return ssb.ExploreRecursive(ipldselector.RecursionLimitDepth(blockChainLength),
170 171 172 173 174 175 176 177
			ssb.ExploreFields(func(efsb ipldbridge.ExploreFieldsSpecBuilder) {
				efsb.Insert("Parents", ssb.ExploreAll(
					ssb.ExploreRecursiveEdge()))
			}))
	})
	if err != nil {
		t.Fatal("Failed creating selector")
	}
178 179 180 181 182 183 184 185

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

186 187
	requestCtx, requestCancel := context.WithCancel(ctx)
	defer requestCancel()
188
	graphSync.Request(requestCtx, host2.ID(), blockChain.tipLink, spec, extension)
189

190
	var message receivedMessage
191 192 193
	select {
	case <-ctx.Done():
		t.Fatal("did not receive message sent")
194
	case message = <-r.messageReceived:
195 196
	}

197
	sender := message.sender
198 199 200 201
	if sender != host1.ID() {
		t.Fatal("received message from wrong node")
	}

202
	received := message.message
203 204 205 206 207 208 209 210 211 212 213 214
	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")
	}
215 216 217 218
	_, err = bridge.ParseSelector(receivedSpec)
	if err != nil {
		t.Fatal("did not receive parsible selector on other side")
	}
219 220 221 222 223

	returnedData, found := receivedRequest.Extension(extensionName)
	if !found || !reflect.DeepEqual(extensionData, returnedData) {
		t.Fatal("Failed to encode extension")
	}
224
}
225 226 227 228 229 230 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

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)

256 257
	blockStore := make(map[ipld.Link][]byte)
	loader, storer := testbridge.NewMockStore(blockStore)
258
	bridge := ipldbridge.NewIPLDBridge()
259 260

	// initialize graphsync on second node to response to requests
261
	New(ctx, gsnet2, bridge, loader, storer)
262

263 264
	blockChainLength := 100
	blockChain := setupBlockChain(ctx, t, storer, bridge, 100, blockChainLength)
265
	spec, err := bridge.BuildSelector(func(ssb ipldbridge.SelectorSpecBuilder) ipldbridge.SelectorSpec {
Edgar Lee's avatar
Edgar Lee committed
266
		return ssb.ExploreRecursive(ipldselector.RecursionLimitDepth(blockChainLength),
267 268 269 270 271 272 273
			ssb.ExploreFields(func(efsb ipldbridge.ExploreFieldsSpecBuilder) {
				efsb.Insert("Parents", ssb.ExploreAll(
					ssb.ExploreRecursiveEdge()))
			}))
	})
	if err != nil {
		t.Fatal("Failed creating selector")
274 275 276 277 278 279
	}

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

	message := gsmsg.New()
283
	message.AddRequest(gsmsg.NewRequest(requestID, blockChain.tipLink.(cidlink.Link).Cid, selectorData, graphsync.Priority(math.MaxInt32)))
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
	// 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
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()
			if len(receivedResponses) != 1 {
				t.Fatal("Did not receive response")
			}
			if receivedResponses[0].RequestID() != requestID {
				t.Fatal("Sent response for incorrect request id")
			}
309
			if receivedResponses[0].Status() != graphsync.PartialResponse {
310 311 312 313 314
				break readAllMessages
			}
		}
	}

315
	if len(receivedBlocks) != blockChainLength {
316 317 318
		t.Fatal("Send incorrect number of blocks or there were duplicate blocks")
	}
}
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344

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)
345
	bridge1 := ipldbridge.NewIPLDBridge()
346

347
	// initialize graphsync on first node to make requests
348 349 350 351 352 353 354
	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)
355 356
	bridge2 := ipldbridge.NewIPLDBridge()

357 358
	blockChainLength := 100
	blockChain := setupBlockChain(ctx, t, storer2, bridge2, 100, blockChainLength)
359 360 361 362

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

363
	spec, err := bridge1.BuildSelector(func(ssb ipldbridge.SelectorSpecBuilder) ipldbridge.SelectorSpec {
Edgar Lee's avatar
Edgar Lee committed
364
		return ssb.ExploreRecursive(ipldselector.RecursionLimitDepth(blockChainLength),
365 366 367 368 369 370 371
			ssb.ExploreFields(func(efsb ipldbridge.ExploreFieldsSpecBuilder) {
				efsb.Insert("Parents", ssb.ExploreAll(
					ssb.ExploreRecursiveEdge()))
			}))
	})
	if err != nil {
		t.Fatal("Failed creating selector")
372 373
	}

374
	progressChan, errChan := requestor.Request(ctx, host2.ID(), blockChain.tipLink, spec)
375 376 377 378

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

379
	if len(responses) != blockChainLength*2 {
380 381
		t.Fatal("did not traverse all nodes")
	}
382 383
	if len(errs) != 0 {
		t.Fatal("errors during traverse")
384
	}
385
	if len(blockStore1) != blockChainLength {
386 387
		t.Fatal("did not store all blocks")
	}
388 389 390 391 392 393 394 395 396 397 398 399 400 401

	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"
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

// 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)

	spec, err := bridge1.BuildSelector(func(ssb ipldbridge.SelectorSpecBuilder) ipldbridge.SelectorSpec {
Edgar Lee's avatar
Edgar Lee committed
462
		return ssb.ExploreRecursive(ipldselector.RecursionLimitDepth(blockChainLength),
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
			ssb.ExploreFields(func(efsb ipldbridge.ExploreFieldsSpecBuilder) {
				efsb.Insert("Parents", ssb.ExploreAll(
					ssb.ExploreRecursiveEdge()))
			}))
	})
	if err != nil {
		t.Fatal("Failed creating selector")
	}

	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")
	}
}