graphsync_test.go 16.5 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
	"testing"
	"time"

16
	ipldfree "github.com/ipld/go-ipld-prime/impl/free"
Hannah Howard's avatar
Hannah Howard committed
17
	"github.com/stretchr/testify/require"
18

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

21
	blocks "github.com/ipfs/go-block-format"
22 23 24 25 26 27 28 29 30 31 32 33 34
	"github.com/ipfs/go-blockservice"
	"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"

35
	"github.com/ipfs/go-graphsync"
36

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

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

61
	blockChainLength := 100
62
	blockChain := testutil.SetupBlockChain(ctx, t, td.loader1, td.storer1, 100, blockChainLength)
63

64 65
	requestCtx, requestCancel := context.WithCancel(ctx)
	defer requestCancel()
66
	graphSync.Request(requestCtx, td.host2.ID(), blockChain.TipLink, blockChain.Selector(), td.extension)
67

68
	var message receivedMessage
Hannah Howard's avatar
Hannah Howard committed
69
	testutil.AssertReceive(ctx, t, r.messageReceived, &message, "did not receive message sent")
70

71
	sender := message.sender
Hannah Howard's avatar
Hannah Howard committed
72
	require.Equal(t, td.host1.ID(), sender, "received message from wrong node")
73

74
	received := message.message
75
	receivedRequests := received.Requests()
Hannah Howard's avatar
Hannah Howard committed
76
	require.Len(t, receivedRequests, 1, "Did not add request to received message")
77
	receivedRequest := receivedRequests[0]
78
	receivedSpec := receivedRequest.Selector()
Hannah Howard's avatar
Hannah Howard committed
79
	require.Equal(t, blockChain.Selector(), receivedSpec, "did not transmit selector spec correctly")
80
	_, err := ipldutil.ParseSelector(receivedSpec)
Hannah Howard's avatar
Hannah Howard committed
81
	require.NoError(t, err, "did not receive parsible selector on other side")
82

83
	returnedData, found := receivedRequest.Extension(td.extensionName)
Hannah Howard's avatar
Hannah Howard committed
84 85
	require.True(t, found)
	require.Equal(t, td.extensionData, returnedData, "Failed to encode extension")
86
}
87 88 89 90 91 92

func TestSendResponseToIncomingRequest(t *testing.T) {
	// create network
	ctx := context.Background()
	ctx, cancel := context.WithTimeout(ctx, 1*time.Second)
	defer cancel()
93
	td := newGsTestData(ctx, t)
94 95 96
	r := &receiver{
		messageReceived: make(chan receivedMessage),
	}
97
	td.gsnet1.SetDelegate(r)
98 99

	var receivedRequestData []byte
100
	// initialize graphsync on second node to response to requests
101
	gsnet := td.GraphSyncHost2()
102
	gsnet.RegisterRequestReceivedHook(
103
		func(p peer.ID, requestData graphsync.RequestData, hookActions graphsync.RequestReceivedHookActions) {
104
			var has bool
105
			receivedRequestData, has = requestData.Extension(td.extensionName)
Hannah Howard's avatar
Hannah Howard committed
106
			require.True(t, has, "did not have expected extension")
107
			hookActions.SendExtensionData(td.extensionResponse)
108 109
		},
	)
110

111
	blockChainLength := 100
112
	blockChain := testutil.SetupBlockChain(ctx, t, td.loader2, td.storer2, 100, blockChainLength)
113

114
	requestID := graphsync.RequestID(rand.Int31())
115 116

	message := gsmsg.New()
117
	message.AddRequest(gsmsg.NewRequest(requestID, blockChain.TipLink.(cidlink.Link).Cid, blockChain.Selector(), graphsync.Priority(math.MaxInt32), td.extension))
118
	// send request across network
119
	err := td.gsnet1.SendMessage(ctx, td.host2.ID(), message)
Hannah Howard's avatar
Hannah Howard committed
120
	require.NoError(t, err)
121 122 123
	// read the values sent back to requestor
	var received gsmsg.GraphSyncMessage
	var receivedBlocks []blocks.Block
124
	var receivedExtensions [][]byte
125
	for {
Hannah Howard's avatar
Hannah Howard committed
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
		var message receivedMessage
		testutil.AssertReceive(ctx, t, r.messageReceived, &message, "did not receive complete response")

		sender := message.sender
		require.Equal(t, td.host2.ID(), sender, "received message from wrong node")

		received = message.message
		receivedBlocks = append(receivedBlocks, received.Blocks()...)
		receivedResponses := received.Responses()
		receivedExtension, found := receivedResponses[0].Extension(td.extensionName)
		if found {
			receivedExtensions = append(receivedExtensions, receivedExtension)
		}
		require.Len(t, receivedResponses, 1, "Did not receive response")
		require.Equal(t, requestID, receivedResponses[0].RequestID(), "Sent response for incorrect request id")
		if receivedResponses[0].Status() != graphsync.PartialResponse {
			break
143 144 145
		}
	}

Hannah Howard's avatar
Hannah Howard committed
146 147 148 149
	require.Len(t, receivedBlocks, blockChainLength, "Send incorrect number of blocks or there were duplicate blocks")
	require.Equal(t, td.extensionData, receivedRequestData, "did not receive correct request extension data")
	require.Len(t, receivedExtensions, 1, "should have sent extension responses but didn't")
	require.Equal(t, td.extensionResponseData, receivedExtensions[0], "did not return correct extension data")
150
}
151

152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
func TestRejectRequestsByDefault(t *testing.T) {
	// create network
	ctx := context.Background()
	ctx, cancel := context.WithTimeout(ctx, 1*time.Second)
	defer cancel()
	td := newGsTestData(ctx, t)

	requestor := td.GraphSyncHost1()
	// setup responder to disable default validation, meaning all requests are rejected
	_ = td.GraphSyncHost2(RejectAllRequestsByDefault())

	blockChainLength := 5
	blockChain := testutil.SetupBlockChain(ctx, t, td.loader2, td.storer2, 5, blockChainLength)

	// send request across network
	progressChan, errChan := requestor.Request(ctx, td.host2.ID(), blockChain.TipLink, blockChain.Selector(), td.extension)

	testutil.VerifyEmptyResponse(ctx, t, progressChan)
	testutil.VerifySingleTerminalError(ctx, t, errChan)
}

173 174 175 176 177
func TestGraphsyncRoundTrip(t *testing.T) {
	// create network
	ctx := context.Background()
	ctx, cancel := context.WithTimeout(ctx, 1*time.Second)
	defer cancel()
178
	td := newGsTestData(ctx, t)
179

180
	// initialize graphsync on first node to make requests
181
	requestor := td.GraphSyncHost1()
182 183

	// setup receiving peer to just record message coming in
184
	blockChainLength := 100
185
	blockChain := testutil.SetupBlockChain(ctx, t, td.loader2, td.storer2, 100, blockChainLength)
186 187

	// initialize graphsync on second node to response to requests
188
	responder := td.GraphSyncHost2()
189 190 191 192

	var receivedResponseData []byte
	var receivedRequestData []byte

193
	requestor.RegisterResponseReceivedHook(
194
		func(p peer.ID, responseData graphsync.ResponseData) error {
195
			data, has := responseData.Extension(td.extensionName)
196 197 198 199 200 201
			if has {
				receivedResponseData = data
			}
			return nil
		})

202
	responder.RegisterRequestReceivedHook(func(p peer.ID, requestData graphsync.RequestData, hookActions graphsync.RequestReceivedHookActions) {
203
		var has bool
204
		receivedRequestData, has = requestData.Extension(td.extensionName)
205 206 207
		if !has {
			hookActions.TerminateWithError(errors.New("Missing extension"))
		} else {
208
			hookActions.SendExtensionData(td.extensionResponse)
209 210
		}
	})
211

212
	progressChan, errChan := requestor.Request(ctx, td.host2.ID(), blockChain.TipLink, blockChain.Selector(), td.extension)
213

Hannah Howard's avatar
Hannah Howard committed
214 215 216
	blockChain.VerifyWholeChain(ctx, progressChan)
	testutil.VerifyEmptyErrors(ctx, t, errChan)
	require.Len(t, td.blockStore1, blockChainLength, "did not store all blocks")
217 218

	// verify extension roundtrip
Hannah Howard's avatar
Hannah Howard committed
219 220
	require.Equal(t, td.extensionData, receivedRequestData, "did not receive correct extension request data")
	require.Equal(t, td.extensionResponseData, receivedResponseData, "did not receive correct extension response data")
221
}
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238

// 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()
239 240 241 242 243
	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()
244

245 246
	// setup receiving peer to just record message coming in
	blockChainLength := 40
247
	blockChain := testutil.SetupBlockChain(ctx, t, td.loader1, td.storer2, 200000, blockChainLength)
248 249 250 251

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

252
	progressChan, errChan := requestor.Request(ctx, td.host2.ID(), blockChain.TipLink, blockChain.Selector())
253

Hannah Howard's avatar
Hannah Howard committed
254 255
	blockChain.VerifyWholeChain(ctx, progressChan)
	testutil.VerifyEmptyErrors(ctx, t, errChan)
256 257
}

258 259 260 261 262 263 264 265 266 267 268 269 270 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 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
// 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"))
Hannah Howard's avatar
Hannah Howard committed
320
	require.NoError(t, err, "unable to create path for fixture file")
321 322

	f, err := os.Open(path)
Hannah Howard's avatar
Hannah Howard committed
323 324
	require.NoError(t, err, "unable to open fixture file")

325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
	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)))
Hannah Howard's avatar
Hannah Howard committed
340 341
	require.NoError(t, err, "unable to setup dag builder")

342
	nd, err := balanced.Layout(db)
Hannah Howard's avatar
Hannah Howard committed
343 344
	require.NoError(t, err, "unable to create unix fs node")

345
	err = bufferedDS.Commit()
Hannah Howard's avatar
Hannah Howard committed
346
	require.NoError(t, err, "unable to commit unix fs node")
347 348 349 350 351 352 353 354 355 356 357 358 359

	// 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)
360 361
	requestor := New(ctx, td.gsnet1, loader1, storer1)
	responder := New(ctx, td.gsnet2, loader2, storer2)
362
	extensionName := graphsync.ExtensionName("Free for all")
363
	responder.RegisterRequestReceivedHook(func(p peer.ID, requestData graphsync.RequestData, hookActions graphsync.RequestReceivedHookActions) {
364 365 366 367 368 369
		hookActions.ValidateRequest()
		hookActions.SendExtensionData(graphsync.ExtensionData{
			Name: extensionName,
			Data: nil,
		})
	})
370

371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
	// 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)
Hannah Howard's avatar
Hannah Howard committed
388
	testutil.VerifyEmptyErrors(ctx, t, errChan)
389 390 391 392 393 394

	// 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())
Hannah Howard's avatar
Hannah Howard committed
395
	require.NoError(t, err, "should have been able to read received root node but didn't")
396 397 398

	// Setup a UnixFS file reader
	n, err := unixfile.NewUnixfsFile(ctx, dagService1, otherNode)
Hannah Howard's avatar
Hannah Howard committed
399
	require.NoError(t, err, "should have been able to setup UnixFS file but wasn't")
400 401

	fn, ok := n.(files.File)
Hannah Howard's avatar
Hannah Howard committed
402
	require.True(t, ok, "file should be a regular file, but wasn't")
403 404 405

	// Read the bytes for the UnixFS File
	finalBytes, err := ioutil.ReadAll(fn)
Hannah Howard's avatar
Hannah Howard committed
406
	require.NoError(t, err, "should have been able to read all of unix FS file but wasn't")
407 408

	// verify original bytes match final bytes!
Hannah Howard's avatar
Hannah Howard committed
409
	require.Equal(t, origBytes, finalBytes, "should have gotten same bytes written as read but didn't")
410 411
}

412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
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
	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
433
	// setup network
434
	td.host1, err = td.mn.GenPeer()
Hannah Howard's avatar
Hannah Howard committed
435
	require.NoError(t, err, "error generating host")
436
	td.host2, err = td.mn.GenPeer()
Hannah Howard's avatar
Hannah Howard committed
437
	require.NoError(t, err, "error generating host")
438
	err = td.mn.LinkAll()
Hannah Howard's avatar
Hannah Howard committed
439
	require.NoError(t, err, "error linking hosts")
440

441 442 443
	td.gsnet1 = gsnet.NewFromLibp2pHost(td.host1)
	td.gsnet2 = gsnet.NewFromLibp2pHost(td.host2)
	td.blockStore1 = make(map[ipld.Link][]byte)
444
	td.loader1, td.storer1 = testutil.NewTestStore(td.blockStore1)
445
	td.blockStore2 = make(map[ipld.Link][]byte)
446
	td.loader2, td.storer2 = testutil.NewTestStore(td.blockStore2)
447 448 449 450 451 452 453 454 455 456 457 458
	// 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,
	}
459

460 461
	return td
}
462

463 464
func (td *gsTestData) GraphSyncHost1(options ...Option) graphsync.GraphExchange {
	return New(td.ctx, td.gsnet1, td.loader1, td.storer1, options...)
465
}
466

467
func (td *gsTestData) GraphSyncHost2(options ...Option) graphsync.GraphExchange {
468

469
	return New(td.ctx, td.gsnet2, td.loader2, td.storer2, options...)
470
}
471

472 473 474 475
type receivedMessage struct {
	message gsmsg.GraphSyncMessage
	sender  peer.ID
}
476

477 478 479 480
// Receiver is an interface for receiving messages from the GraphSyncNetwork.
type receiver struct {
	messageReceived chan receivedMessage
}
481

482 483 484 485
func (r *receiver) ReceiveMessage(
	ctx context.Context,
	sender peer.ID,
	incoming gsmsg.GraphSyncMessage) {
486

487 488 489 490 491
	select {
	case <-ctx.Done():
	case r.messageReceived <- receivedMessage{incoming, sender}:
	}
}
492

493 494
func (r *receiver) ReceiveError(err error) {
}
495

496 497 498 499 500
func (r *receiver) Connected(p peer.ID) {
}

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