graphsync_test.go 13.5 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
	requestCtx, requestCancel := context.WithCancel(ctx)
	defer requestCancel()
180
	graphSync.Request(requestCtx, host2.ID(), blockChain.tipLink, spec)
181

182
	var message receivedMessage
183 184 185
	select {
	case <-ctx.Done():
		t.Fatal("did not receive message sent")
186
	case message = <-r.messageReceived:
187 188
	}

189
	sender := message.sender
190 191 192 193
	if sender != host1.ID() {
		t.Fatal("received message from wrong node")
	}

194
	received := message.message
195 196 197 198 199 200 201 202 203 204 205 206
	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")
	}
207 208 209 210
	_, err = bridge.ParseSelector(receivedSpec)
	if err != nil {
		t.Fatal("did not receive parsible selector on other side")
	}
211
}
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242

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)

243 244
	blockStore := make(map[ipld.Link][]byte)
	loader, storer := testbridge.NewMockStore(blockStore)
245
	bridge := ipldbridge.NewIPLDBridge()
246 247

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

250 251
	blockChainLength := 100
	blockChain := setupBlockChain(ctx, t, storer, bridge, 100, blockChainLength)
252
	spec, err := bridge.BuildSelector(func(ssb ipldbridge.SelectorSpecBuilder) ipldbridge.SelectorSpec {
Edgar Lee's avatar
Edgar Lee committed
253
		return ssb.ExploreRecursive(ipldselector.RecursionLimitDepth(blockChainLength),
254 255 256 257 258 259 260
			ssb.ExploreFields(func(efsb ipldbridge.ExploreFieldsSpecBuilder) {
				efsb.Insert("Parents", ssb.ExploreAll(
					ssb.ExploreRecursiveEdge()))
			}))
	})
	if err != nil {
		t.Fatal("Failed creating selector")
261 262 263 264 265 266
	}

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

	message := gsmsg.New()
270
	message.AddRequest(gsmsg.NewRequest(requestID, blockChain.tipLink.(cidlink.Link).Cid, selectorData, graphsync.Priority(math.MaxInt32)))
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
	// 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")
			}
296
			if receivedResponses[0].Status() != graphsync.PartialResponse {
297 298 299 300 301
				break readAllMessages
			}
		}
	}

302
	if len(receivedBlocks) != blockChainLength {
303 304 305
		t.Fatal("Send incorrect number of blocks or there were duplicate blocks")
	}
}
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331

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

334
	// initialize graphsync on first node to make requests
335 336 337 338 339 340 341
	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)
342 343
	bridge2 := ipldbridge.NewIPLDBridge()

344 345
	blockChainLength := 100
	blockChain := setupBlockChain(ctx, t, storer2, bridge2, 100, blockChainLength)
346 347 348 349

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

350
	spec, err := bridge1.BuildSelector(func(ssb ipldbridge.SelectorSpecBuilder) ipldbridge.SelectorSpec {
Edgar Lee's avatar
Edgar Lee committed
351
		return ssb.ExploreRecursive(ipldselector.RecursionLimitDepth(blockChainLength),
352 353 354 355 356 357 358
			ssb.ExploreFields(func(efsb ipldbridge.ExploreFieldsSpecBuilder) {
				efsb.Insert("Parents", ssb.ExploreAll(
					ssb.ExploreRecursiveEdge()))
			}))
	})
	if err != nil {
		t.Fatal("Failed creating selector")
359 360
	}

361
	progressChan, errChan := requestor.Request(ctx, host2.ID(), blockChain.tipLink, spec)
362 363 364 365

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

366
	if len(responses) != blockChainLength*2 {
367 368
		t.Fatal("did not traverse all nodes")
	}
369 370
	if len(errs) != 0 {
		t.Fatal("errors during traverse")
371
	}
372
	if len(blockStore1) != blockChainLength {
373 374
		t.Fatal("did not store all blocks")
	}
375 376 377 378 379 380 381 382 383 384 385 386 387 388

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

// 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
449
		return ssb.ExploreRecursive(ipldselector.RecursionLimitDepth(blockChainLength),
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
			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")
	}
}