merkledag_test.go 10.8 KB
Newer Older
1
package merkledag_test
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
2 3

import (
4
	"bytes"
Jeromy's avatar
Jeromy committed
5
	"context"
6
	"errors"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
7
	"fmt"
8 9
	"io"
	"io/ioutil"
10
	"strings"
11
	"sync"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
12
	"testing"
13
	"time"
14

15
	blocks "github.com/ipfs/go-ipfs/blocks"
16
	bserv "github.com/ipfs/go-ipfs/blockservice"
17
	bstest "github.com/ipfs/go-ipfs/blockservice/test"
18 19 20 21
	offline "github.com/ipfs/go-ipfs/exchange/offline"
	imp "github.com/ipfs/go-ipfs/importer"
	chunk "github.com/ipfs/go-ipfs/importer/chunk"
	. "github.com/ipfs/go-ipfs/merkledag"
22
	mdpb "github.com/ipfs/go-ipfs/merkledag/pb"
23
	dstest "github.com/ipfs/go-ipfs/merkledag/test"
24
	uio "github.com/ipfs/go-ipfs/unixfs/io"
Jeromy's avatar
Jeromy committed
25

Jeromy's avatar
Jeromy committed
26
	node "gx/ipfs/QmRSU5EqqWVZSNdbU51yXmVoF1uNw3JgTNB6RaiL7DZM16/go-ipld-node"
27
	u "gx/ipfs/Qmb912gdngC1UWwTkhuW8knyRbcWeu5kqkxBpveLmW8bSr/go-ipfs-util"
Jeromy's avatar
Jeromy committed
28
	cid "gx/ipfs/QmcTcsTvfaeEBRFo1TkFgT8sRmgi1n1LTZpecfVP8fzpGD/go-cid"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
29 30 31 32
)

func TestNode(t *testing.T) {

33 34 35
	n1 := NodeWithData([]byte("beep"))
	n2 := NodeWithData([]byte("boop"))
	n3 := NodeWithData([]byte("beep boop"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
36 37 38 39 40 41 42
	if err := n3.AddNodeLink("beep-link", n1); err != nil {
		t.Error(err)
	}
	if err := n3.AddNodeLink("boop-link", n2); err != nil {
		t.Error(err)
	}

43
	printn := func(name string, n *ProtoNode) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
44
		fmt.Println(">", name)
45
		fmt.Println("data:", string(n.Data()))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
46 47

		fmt.Println("links:")
48 49
		for _, l := range n.Links() {
			fmt.Println("-", l.Name, l.Size, l.Cid)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
50 51
		}

52
		e, err := n.EncodeProtobuf(false)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
53 54 55 56 57 58
		if err != nil {
			t.Error(err)
		} else {
			fmt.Println("encoded:", e)
		}

Jeromy's avatar
Jeromy committed
59
		h := n.Multihash()
Jeromy's avatar
Jeromy committed
60 61
		k := n.Cid().Hash()
		if k.String() != h.String() {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
62 63 64 65
			t.Error("Key is not equivalent to multihash")
		} else {
			fmt.Println("key: ", k)
		}
66 67

		SubtestNodeStat(t, n)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
68 69 70 71 72 73
	}

	printn("beep", n1)
	printn("boop", n2)
	printn("beep boop", n3)
}
74

75
func SubtestNodeStat(t *testing.T, n *ProtoNode) {
76
	enc, err := n.EncodeProtobuf(true)
77
	if err != nil {
78
		t.Error("n.EncodeProtobuf(true) failed")
79 80 81 82 83 84 85 86 87
		return
	}

	cumSize, err := n.Size()
	if err != nil {
		t.Error("n.Size() failed")
		return
	}

Jeromy's avatar
Jeromy committed
88
	k := n.Cid()
89

Jeromy's avatar
Jeromy committed
90
	expected := node.NodeStat{
91
		NumLinks:       len(n.Links()),
92
		BlockSize:      len(enc),
93 94
		LinksSize:      len(enc) - len(n.Data()), // includes framing.
		DataSize:       len(n.Data()),
95
		CumulativeSize: int(cumSize),
Jeromy's avatar
Jeromy committed
96
		Hash:           k.String(),
97 98 99 100 101 102 103 104
	}

	actual, err := n.Stat()
	if err != nil {
		t.Error("n.Stat() failed")
		return
	}

105
	if expected != *actual {
106
		t.Errorf("n.Stat incorrect.\nexpect: %s\nactual: %s", expected, actual)
107 108 109 110 111
	} else {
		fmt.Printf("n.Stat correct: %s\n", actual)
	}
}

112 113 114
type devZero struct{}

func (_ devZero) Read(b []byte) (int, error) {
rht's avatar
rht committed
115
	for i := range b {
116 117 118 119 120
		b[i] = 0
	}
	return len(b), nil
}

121
func TestBatchFetch(t *testing.T) {
Jeromy's avatar
Jeromy committed
122 123
	read := io.LimitReader(u.NewTimeSeededRand(), 1024*32)
	runBatchFetchTest(t, read)
124
}
125 126

func TestBatchFetchDupBlock(t *testing.T) {
Jeromy's avatar
Jeromy committed
127 128
	read := io.LimitReader(devZero{}, 1024*32)
	runBatchFetchTest(t, read)
129 130
}

Jeromy's avatar
Jeromy committed
131
func runBatchFetchTest(t *testing.T, read io.Reader) {
132
	ctx := context.Background()
133
	var dagservs []DAGService
134
	for _, bsi := range bstest.Mocks(5) {
135 136
		dagservs = append(dagservs, NewDAGService(bsi))
	}
Jeromy's avatar
Jeromy committed
137

138
	spl := chunk.NewSizeSplitter(read, 512)
Jeromy's avatar
Jeromy committed
139

Jeromy's avatar
Jeromy committed
140
	root, err := imp.BuildDagFromReader(dagservs[0], spl)
Jeromy's avatar
Jeromy committed
141 142 143 144
	if err != nil {
		t.Fatal(err)
	}

145 146
	t.Log("finished setup.")

147
	dagr, err := uio.NewDagReader(ctx, root, dagservs[0])
148 149 150
	if err != nil {
		t.Fatal(err)
	}
Jeromy's avatar
Jeromy committed
151 152

	expected, err := ioutil.ReadAll(dagr)
153 154 155 156
	if err != nil {
		t.Fatal(err)
	}

157
	_, err = dagservs[0].Add(root)
158 159 160 161 162 163
	if err != nil {
		t.Fatal(err)
	}

	t.Log("Added file to first node.")

Jeromy's avatar
Jeromy committed
164
	c := root.Cid()
165

166
	wg := sync.WaitGroup{}
167 168
	errs := make(chan error)

169
	for i := 1; i < len(dagservs); i++ {
170
		wg.Add(1)
171
		go func(i int) {
172
			defer wg.Done()
Jeromy's avatar
Jeromy committed
173
			first, err := dagservs[i].Get(ctx, c)
174
			if err != nil {
175
				errs <- err
176 177 178
			}
			fmt.Println("Got first node back.")

179 180 181 182 183 184
			firstpb, ok := first.(*ProtoNode)
			if !ok {
				errs <- ErrNotProtobuf
			}

			read, err := uio.NewDagReader(ctx, firstpb, dagservs[i])
185
			if err != nil {
186
				errs <- err
187 188 189
			}
			datagot, err := ioutil.ReadAll(read)
			if err != nil {
190
				errs <- err
191 192 193
			}

			if !bytes.Equal(datagot, expected) {
194
				errs <- errors.New("Got bad data back!")
195 196 197 198
			}
		}(i)
	}

199 200 201 202 203 204 205 206 207 208
	go func() {
		wg.Wait()
		close(errs)
	}()

	for err := range errs {
		if err != nil {
			t.Fatal(err)
		}
	}
209
}
210

Jeromy's avatar
Jeromy committed
211
func assertCanGet(t *testing.T, ds DAGService, n node.Node) {
Jeromy's avatar
Jeromy committed
212
	if _, err := ds.Get(context.Background(), n.Cid()); err != nil {
213 214 215 216 217
		t.Fatal(err)
	}
}

func TestCantGet(t *testing.T) {
218
	ds := dstest.Mock()
219
	a := NodeWithData([]byte("A"))
220

Jeromy's avatar
Jeromy committed
221 222
	c := a.Cid()
	_, err := ds.Get(context.Background(), c)
223 224 225 226
	if !strings.Contains(err.Error(), "not found") {
		t.Fatal("expected err not found, got: ", err)
	}
}
227 228

func TestFetchGraph(t *testing.T) {
Jeromy's avatar
Jeromy committed
229
	var dservs []DAGService
230
	bsis := bstest.Mocks(2)
Jeromy's avatar
Jeromy committed
231 232 233
	for _, bsi := range bsis {
		dservs = append(dservs, NewDAGService(bsi))
	}
234 235

	read := io.LimitReader(u.NewTimeSeededRand(), 1024*32)
Jeromy's avatar
Jeromy committed
236
	root, err := imp.BuildDagFromReader(dservs[0], chunk.NewSizeSplitter(read, 512))
237 238 239 240
	if err != nil {
		t.Fatal(err)
	}

241
	err = FetchGraph(context.TODO(), root.Cid(), dservs[1])
242 243 244 245
	if err != nil {
		t.Fatal(err)
	}

Jeromy's avatar
Jeromy committed
246
	// create an offline dagstore and ensure all blocks were fetched
247
	bs := bserv.New(bsis[1].Blockstore(), offline.Exchange(bsis[1].Blockstore()))
248

Jeromy's avatar
Jeromy committed
249 250
	offline_ds := NewDAGService(bs)

251
	err = EnumerateChildren(context.Background(), offline_ds, root.Cid(), func(_ *cid.Cid) bool { return true }, false)
252 253 254 255 256 257
	if err != nil {
		t.Fatal(err)
	}
}

func TestEnumerateChildren(t *testing.T) {
258
	bsi := bstest.Mocks(1)
259 260 261
	ds := NewDAGService(bsi[0])

	read := io.LimitReader(u.NewTimeSeededRand(), 1024*1024)
Jeromy's avatar
Jeromy committed
262
	root, err := imp.BuildDagFromReader(ds, chunk.NewSizeSplitter(read, 512))
263 264 265 266
	if err != nil {
		t.Fatal(err)
	}

Jeromy's avatar
Jeromy committed
267
	set := cid.NewSet()
268
	err = EnumerateChildren(context.Background(), ds, root.Cid(), set.Visit, false)
269 270 271 272
	if err != nil {
		t.Fatal(err)
	}

Jeromy's avatar
Jeromy committed
273 274
	var traverse func(n node.Node)
	traverse = func(n node.Node) {
275
		// traverse dag and check
276 277
		for _, lnk := range n.Links() {
			c := lnk.Cid
Jeromy's avatar
Jeromy committed
278
			if !set.Has(c) {
279
				t.Fatal("missing key in set! ", lnk.Cid.String())
280
			}
Jeromy's avatar
Jeromy committed
281
			child, err := ds.Get(context.Background(), c)
282 283 284 285 286 287 288 289 290
			if err != nil {
				t.Fatal(err)
			}
			traverse(child)
		}
	}

	traverse(root)
}
291 292 293 294 295

func TestFetchFailure(t *testing.T) {
	ds := dstest.Mock()
	ds_bad := dstest.Mock()

296
	top := new(ProtoNode)
297
	for i := 0; i < 10; i++ {
298
		nd := NodeWithData([]byte{byte('a' + i)})
299 300 301 302 303 304 305 306 307 308 309 310
		_, err := ds.Add(nd)
		if err != nil {
			t.Fatal(err)
		}

		err = top.AddNodeLinkClean(fmt.Sprintf("AA%d", i), nd)
		if err != nil {
			t.Fatal(err)
		}
	}

	for i := 0; i < 10; i++ {
311
		nd := NodeWithData([]byte{'f', 'a' + byte(i)})
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
		_, err := ds_bad.Add(nd)
		if err != nil {
			t.Fatal(err)
		}

		err = top.AddNodeLinkClean(fmt.Sprintf("BB%d", i), nd)
		if err != nil {
			t.Fatal(err)
		}
	}

	getters := GetDAG(context.Background(), ds, top)
	for i, getter := range getters {
		_, err := getter.Get(context.Background())
		if err != nil && i < 10 {
			t.Fatal(err)
		}
		if err == nil && i >= 10 {
			t.Fatal("should have failed request")
		}
	}
}
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354

func TestUnmarshalFailure(t *testing.T) {
	badData := []byte("hello world")

	_, err := DecodeProtobuf(badData)
	if err == nil {
		t.Fatal("shouldnt succeed to parse this")
	}

	// now with a bad link
	pbn := &mdpb.PBNode{Links: []*mdpb.PBLink{{Hash: []byte("not a multihash")}}}
	badlink, err := pbn.Marshal()
	if err != nil {
		t.Fatal(err)
	}

	_, err = DecodeProtobuf(badlink)
	if err == nil {
		t.Fatal("should have failed to parse node with bad link")
	}

355
	n := &ProtoNode{}
356 357
	n.Marshal()
}
Jeromy's avatar
Jeromy committed
358 359 360

func TestBasicAddGet(t *testing.T) {
	ds := dstest.Mock()
361
	nd := new(ProtoNode)
Jeromy's avatar
Jeromy committed
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376

	c, err := ds.Add(nd)
	if err != nil {
		t.Fatal(err)
	}

	out, err := ds.Get(context.Background(), c)
	if err != nil {
		t.Fatal(err)
	}

	if !nd.Cid().Equals(out.Cid()) {
		t.Fatal("output didnt match input")
	}
}
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

func TestGetRawNodes(t *testing.T) {
	rn := NewRawNode([]byte("test"))

	ds := dstest.Mock()

	c, err := ds.Add(rn)
	if err != nil {
		t.Fatal(err)
	}

	if !c.Equals(rn.Cid()) {
		t.Fatal("output cids didnt match")
	}

	out, err := ds.Get(context.TODO(), c)
	if err != nil {
		t.Fatal(err)
	}

	if !bytes.Equal(out.RawData(), []byte("test")) {
		t.Fatal("raw block should match input data")
	}

	if out.Links() != nil {
		t.Fatal("raw blocks shouldnt have links")
	}

405
	if out.Tree("", -1) != nil {
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
		t.Fatal("tree should return no paths in a raw block")
	}

	size, err := out.Size()
	if err != nil {
		t.Fatal(err)
	}
	if size != 4 {
		t.Fatal("expected size to be 4")
	}

	ns, err := out.Stat()
	if err != nil {
		t.Fatal(err)
	}

	if ns.DataSize != 4 {
		t.Fatal("expected size to be 4, got: ", ns.DataSize)
	}

	_, _, err = out.Resolve([]string{"foo"})
	if err != ErrLinkNotFound {
		t.Fatal("shouldnt find links under raw blocks")
	}
}

func TestProtoNodeResolve(t *testing.T) {

	nd := new(ProtoNode)
	nd.SetLinks([]*node.Link{{Name: "foo"}})

437
	lnk, left, err := nd.ResolveLink([]string{"foo", "bar"})
438 439 440 441 442 443 444 445 446 447 448 449
	if err != nil {
		t.Fatal(err)
	}

	if len(left) != 1 || left[0] != "bar" {
		t.Fatal("expected the single path element 'bar' to remain")
	}

	if lnk.Name != "foo" {
		t.Fatal("how did we get anything else?")
	}

450
	tvals := nd.Tree("", -1)
451 452 453 454
	if len(tvals) != 1 || tvals[0] != "foo" {
		t.Fatal("expected tree to return []{\"foo\"}")
	}
}
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

func TestCidRetention(t *testing.T) {
	nd := new(ProtoNode)
	nd.SetData([]byte("fooooo"))

	pref := nd.Cid().Prefix()
	pref.Version = 1

	c2, err := pref.Sum(nd.RawData())
	if err != nil {
		t.Fatal(err)
	}

	blk, err := blocks.NewBlockWithCid(nd.RawData(), c2)
	if err != nil {
		t.Fatal(err)
	}

	bs := dstest.Bserv()
	_, err = bs.AddBlock(blk)
	if err != nil {
		t.Fatal(err)
	}

	ds := NewDAGService(bs)
	out, err := ds.Get(context.Background(), c2)
	if err != nil {
		t.Fatal(err)
	}

	if !out.Cid().Equals(c2) {
		t.Fatal("output cid didnt match")
	}
}
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506

func TestCidRawDoesnNeedData(t *testing.T) {
	srv := NewDAGService(dstest.Bserv())
	nd := NewRawNode([]byte("somedata"))

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

	// there is no data for this node in the blockservice
	// so dag service can't load it
	links, err := srv.GetLinks(ctx, nd.Cid())
	if err != nil {
		t.Fatal(err)
	}
	if len(links) != 0 {
		t.Fatal("raw node shouldn't have any links")
	}
}
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

func TestEnumerateAsyncFailsNotFound(t *testing.T) {
	a := NodeWithData([]byte("foo1"))
	b := NodeWithData([]byte("foo2"))
	c := NodeWithData([]byte("foo3"))
	d := NodeWithData([]byte("foo4"))

	ds := dstest.Mock()
	for _, n := range []node.Node{a, b, c} {
		_, err := ds.Add(n)
		if err != nil {
			t.Fatal(err)
		}
	}

	parent := new(ProtoNode)
	if err := parent.AddNodeLinkClean("a", a); err != nil {
		t.Fatal(err)
	}

	if err := parent.AddNodeLinkClean("b", b); err != nil {
		t.Fatal(err)
	}

	if err := parent.AddNodeLinkClean("c", c); err != nil {
		t.Fatal(err)
	}

	if err := parent.AddNodeLinkClean("d", d); err != nil {
		t.Fatal(err)
	}

	pcid, err := ds.Add(parent)
	if err != nil {
		t.Fatal(err)
	}

	cset := cid.NewSet()
	err = EnumerateChildrenAsync(context.Background(), ds, pcid, cset.Visit)
	if err == nil {
		t.Fatal("this should have failed")
	}
}