unixfs_test.go 9.19 KB
Newer Older
1 2 3 4 5
package coreapi_test

import (
	"bytes"
	"context"
Łukasz Magiera's avatar
Łukasz Magiera committed
6
	"encoding/base64"
7
	"fmt"
8
	"io"
9
	"io/ioutil"
10
	"math"
11 12 13
	"strings"
	"testing"

14 15
	"github.com/ipfs/go-ipfs/core"
	"github.com/ipfs/go-ipfs/core/coreapi"
16
	coreiface "github.com/ipfs/go-ipfs/core/coreapi/interface"
17 18
	"github.com/ipfs/go-ipfs/core/coreapi/interface/options"
	"github.com/ipfs/go-ipfs/core/coreunix"
19
	mock "github.com/ipfs/go-ipfs/core/mock"
20 21
	"github.com/ipfs/go-ipfs/keystore"
	"github.com/ipfs/go-ipfs/repo"
22

23
	mh "gx/ipfs/QmPnFwZ2JXKnXgMw8CdBPxn7FWh6LLdjUjxV1fKHuJnkr8/go-multihash"
Steven Allen's avatar
Steven Allen committed
24
	ci "gx/ipfs/QmPvyPwuCgJ7pDmrKDxRtsScJgBaM5h4EpRL2qQJsmXf4n/go-libp2p-crypto"
Steven Allen's avatar
Steven Allen committed
25 26 27 28 29 30 31 32 33
	cbor "gx/ipfs/QmSywXfm2v4Qkp4DcFqo8eehj49dJK3bdUnaLVxrdFLMQn/go-ipld-cbor"
	unixfs "gx/ipfs/QmU4x3742bvgfxJsByEDpBnifJqjJdV6x528co4hwKCn46/go-unixfs"
	datastore "gx/ipfs/QmUyz7JTJzgegC6tiJrfby3mPhzcdswVtG4x58TQ6pq8jV/go-datastore"
	syncds "gx/ipfs/QmUyz7JTJzgegC6tiJrfby3mPhzcdswVtG4x58TQ6pq8jV/go-datastore/sync"
	config "gx/ipfs/QmVBUpxsHh53rNcufqxMpLAmz37eGyLJUaexDy1W9YkiNk/go-ipfs-config"
	mocknet "gx/ipfs/QmVsVARb86uSe1qYouewFMNd2p2sp2NGWm1JGPReVDWchW/go-libp2p/p2p/net/mock"
	peer "gx/ipfs/QmbNepETomvmXfz1X5pHNFD2QuPqnqi47dTd94QJWSorQ3/go-libp2p-peer"
	mdag "gx/ipfs/QmcBoNcAP6qDjgRBew7yjvCqHq7p5jMstE44jPUBWBxzsV/go-merkledag"
	pstore "gx/ipfs/QmfAQMFpgDU2U4BXG64qVr8HSiictfWvkSBz7Y2oDj65st/go-libp2p-peerstore"
34 35
)

36 37
const testPeerID = "QmTFauExutTsy4XP6JbMFcw2Wa9645HJt2bTqL6qYDCKfe"

Lars Gierth's avatar
Lars Gierth committed
38
// `echo -n 'hello, world!' | ipfs add`
39
var hello = "/ipfs/QmQy2Dw4Wk7rdJKjThjYXzfFJNaRKRHhHP5gHHXroJMYxk"
Lars Gierth's avatar
Lars Gierth committed
40 41
var helloStr = "hello, world!"

42 43
// `echo -n | ipfs add`

44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
func makeAPISwarm(ctx context.Context, fullIdentity bool, n int) ([]*core.IpfsNode, []coreiface.CoreAPI, error) {
	mn := mocknet.New(ctx)

	nodes := make([]*core.IpfsNode, n)
	apis := make([]coreiface.CoreAPI, n)

	for i := 0; i < n; i++ {
		var ident config.Identity
		if fullIdentity {
			sk, pk, err := ci.GenerateKeyPair(ci.RSA, 512)
			if err != nil {
				return nil, nil, err
			}

			id, err := peer.IDFromPublicKey(pk)
			if err != nil {
				return nil, nil, err
			}

			kbytes, err := sk.Bytes()
			if err != nil {
				return nil, nil, err
			}

			ident = config.Identity{
				PeerID:  id.Pretty(),
				PrivKey: base64.StdEncoding.EncodeToString(kbytes),
			}
		} else {
			ident = config.Identity{
				PeerID: testPeerID,
			}
Łukasz Magiera's avatar
Łukasz Magiera committed
76 77
		}

78 79 80 81 82 83 84 85
		c := config.Config{}
		c.Addresses.Swarm = []string{fmt.Sprintf("/ip4/127.0.%d.1/tcp/4001", i)}
		c.Identity = ident

		r := &repo.Mock{
			C: c,
			D: syncds.MutexWrap(datastore.NewMapDatastore()),
			K: keystore.NewMemKeystore(),
Łukasz Magiera's avatar
Łukasz Magiera committed
86 87
		}

88 89 90 91 92
		node, err := core.NewNode(ctx, &core.BuildCfg{
			Repo:   r,
			Host:   mock.MockHostOption(mn),
			Online: fullIdentity,
		})
Łukasz Magiera's avatar
Łukasz Magiera committed
93 94 95
		if err != nil {
			return nil, nil, err
		}
96 97 98
		nodes[i] = node
		apis[i] = coreapi.NewCoreAPI(node)
	}
Łukasz Magiera's avatar
Łukasz Magiera committed
99

100 101 102
	err := mn.LinkAll()
	if err != nil {
		return nil, nil, err
Łukasz Magiera's avatar
Łukasz Magiera committed
103 104
	}

105 106 107
	bsinf := core.BootstrapConfigWithPeers(
		[]pstore.PeerInfo{
			nodes[0].Peerstore.PeerInfo(nodes[0].Identity),
108
		},
109 110 111 112 113 114
	)

	for _, n := range nodes[1:] {
		if err := n.Bootstrap(bsinf); err != nil {
			return nil, nil, err
		}
115
	}
116 117 118 119 120 121

	return nodes, apis, nil
}

func makeAPI(ctx context.Context) (*core.IpfsNode, coreiface.CoreAPI, error) {
	nd, api, err := makeAPISwarm(ctx, false, 1)
122 123 124 125
	if err != nil {
		return nil, nil, err
	}

126
	return nd[0], api[0], nil
Łukasz Magiera's avatar
Łukasz Magiera committed
127 128
}

Lars Gierth's avatar
Lars Gierth committed
129 130 131 132 133 134 135
func TestAdd(t *testing.T) {
	ctx := context.Background()
	_, api, err := makeAPI(ctx)
	if err != nil {
		t.Error(err)
	}

136 137 138 139 140 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 167 168 169 170 171
	cases := []struct {
		name string
		data string
		path string
		err  string
		opts []options.UnixfsAddOption
	}{
		{
			name: "simpleAdd",
			data: helloStr,
			path: hello,
			opts: []options.UnixfsAddOption{},
		},
		{
			name: "addEmpty",
			data: "",
			path: "/ipfs/QmbFMke1KXqnYyBBWxB74N4c5SBnJMVAiMNRcGu6x1AwQH",
		},
		{
			name: "addCidV1",
			data: helloStr,
			path: "/ipfs/zb2rhdhmJjJZs9qkhQCpCQ7VREFkqWw3h1r8utjVvQugwHPFd",
			opts: []options.UnixfsAddOption{options.Unixfs.CidVersion(1)},
		},
		{
			name: "addCidSha3",
			data: helloStr,
			path: "/ipfs/zb2wwnYtXBxpndNABjtYxWAPt3cwWNRnc11iT63fvkYV78iRb",
			opts: []options.UnixfsAddOption{options.Unixfs.Hash(mh.SHA3_256)},
		},
		{
			name: "addCidSha3Cid0",
			data: helloStr,
			err:  "CIDv0 only supports sha2-256",
			opts: []options.UnixfsAddOption{options.Unixfs.CidVersion(0), options.Unixfs.Hash(mh.SHA3_256)},
		},
172 173
	}

174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
	for _, testCase := range cases {
		t.Run(testCase.name, func(t *testing.T) {
			str := strings.NewReader(testCase.data)
			p, err := api.Unixfs().Add(ctx, ioutil.NopCloser(str), testCase.opts...)
			if testCase.err != "" {
				if err == nil {
					t.Fatalf("expected an error: %s", testCase.err)
				}
				if err.Error() != testCase.err {
					t.Fatalf("expected an error: '%s' != '%s'", err.Error(), testCase.err)
				}
				return
			}
			if err != nil {
				t.Error(err)
			}
Lars Gierth's avatar
Lars Gierth committed
190

191 192 193
			if p.String() != testCase.path {
				t.Fatalf("expected path %s, got: %s", hello, p)
			}
194

195 196 197 198 199 200 201 202 203
			r, err := api.Unixfs().Cat(ctx, p)
			if err != nil {
				t.Fatal(err)
			}
			buf := make([]byte, len(testCase.data))
			_, err = io.ReadFull(r, buf)
			if err != nil {
				t.Error(err)
			}
204

205 206 207 208
			if string(buf) != testCase.data {
				t.Fatalf("expected [%s], got [%s] [err=%s]", helloStr, string(buf), err)
			}
		})
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
	}
}

func TestCatEmptyFile(t *testing.T) {
	ctx := context.Background()
	node, api, err := makeAPI(ctx)
	if err != nil {
		t.Fatal(err)
	}

	_, err = coreunix.Add(node, strings.NewReader(""))
	if err != nil {
		t.Fatal(err)
	}

224
	emptyFilePath, err := coreiface.ParsePath("/ipfs/QmbFMke1KXqnYyBBWxB74N4c5SBnJMVAiMNRcGu6x1AwQH")
225 226 227 228 229
	if err != nil {
		t.Fatal(err)
	}

	r, err := api.Unixfs().Cat(ctx, emptyFilePath)
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
	if err != nil {
		t.Fatal(err)
	}

	buf := make([]byte, 1) // non-zero so that Read() actually tries to read
	n, err := io.ReadFull(r, buf)
	if err != nil && err != io.EOF {
		t.Error(err)
	}
	if !bytes.HasPrefix(buf, []byte{0x00}) {
		t.Fatalf("expected empty data, got [%s] [read=%d]", buf, n)
	}
}

func TestCatDir(t *testing.T) {
	ctx := context.Background()
	node, api, err := makeAPI(ctx)
	if err != nil {
		t.Error(err)
	}
250 251
	edir := unixfs.EmptyDirNode()
	err = node.DAG.Add(ctx, edir)
252 253 254
	if err != nil {
		t.Error(err)
	}
255
	p := coreiface.IpfsPath(edir.Cid())
256

257
	emptyDir, err := api.Object().New(ctx, options.Object.Type("unixfs-dir"))
258 259
	if err != nil {
		t.Error(err)
260
	}
261

262
	if p.String() != coreiface.IpfsPath(emptyDir.Cid()).String() {
263 264 265
		t.Fatalf("expected path %s, got: %s", emptyDir.Cid(), p.String())
	}

266
	_, err = api.Unixfs().Cat(ctx, coreiface.IpfsPath(emptyDir.Cid()))
267 268 269 270 271 272 273 274 275 276 277 278
	if err != coreiface.ErrIsDir {
		t.Fatalf("expected ErrIsDir, got: %s", err)
	}
}

func TestCatNonUnixfs(t *testing.T) {
	ctx := context.Background()
	node, api, err := makeAPI(ctx)
	if err != nil {
		t.Error(err)
	}

279 280
	nd := new(mdag.ProtoNode)
	err = node.DAG.Add(ctx, nd)
281 282 283 284
	if err != nil {
		t.Error(err)
	}

285
	_, err = api.Unixfs().Cat(ctx, coreiface.IpfsPath(nd.Cid()))
286 287 288 289 290 291 292 293 294 295 296 297
	if !strings.Contains(err.Error(), "proto: required field") {
		t.Fatalf("expected protobuf error, got: %s", err)
	}
}

func TestCatOffline(t *testing.T) {
	ctx := context.Background()
	_, api, err := makeAPI(ctx)
	if err != nil {
		t.Error(err)
	}

298
	p, err := coreiface.ParsePath("/ipns/Qmfoobar")
299 300 301 302
	if err != nil {
		t.Error(err)
	}
	_, err = api.Unixfs().Cat(ctx, p)
303
	if err != coreiface.ErrOffline {
Jakub Sztandera's avatar
Jakub Sztandera committed
304
		t.Fatalf("expected ErrOffline, got: %s", err)
305 306 307 308 309 310 311 312 313 314 315
	}
}

func TestLs(t *testing.T) {
	ctx := context.Background()
	node, api, err := makeAPI(ctx)
	if err != nil {
		t.Error(err)
	}

	r := strings.NewReader("content-of-file")
316
	k, _, err := coreunix.AddWrapped(node, r, "name-of-file")
317 318 319
	if err != nil {
		t.Error(err)
	}
320
	parts := strings.Split(k, "/")
321
	if len(parts) != 2 {
Jakub Sztandera's avatar
Jakub Sztandera committed
322
		t.Errorf("unexpected path: %s", k)
323
	}
324
	p, err := coreiface.ParsePath("/ipfs/" + parts[0])
325 326 327
	if err != nil {
		t.Error(err)
	}
328

Łukasz Magiera's avatar
Łukasz Magiera committed
329
	links, err := api.Unixfs().Ls(ctx, p)
330 331 332 333 334 335 336 337 338 339 340 341 342 343
	if err != nil {
		t.Error(err)
	}

	if len(links) != 1 {
		t.Fatalf("expected 1 link, got %d", len(links))
	}
	if links[0].Size != 23 {
		t.Fatalf("expected size = 23, got %d", links[0].Size)
	}
	if links[0].Name != "name-of-file" {
		t.Fatalf("expected name = name-of-file, got %s", links[0].Name)
	}
	if links[0].Cid.String() != "QmX3qQVKxDGz3URVC3861Z3CKtQKGBn6ffXRBBWGMFz9Lr" {
344
		t.Fatalf("expected cid = QmX3qQVKxDGz3URVC3861Z3CKtQKGBn6ffXRBBWGMFz9Lr, got %s", links[0].Cid)
345 346 347 348 349 350 351 352 353 354
	}
}

func TestLsEmptyDir(t *testing.T) {
	ctx := context.Background()
	node, api, err := makeAPI(ctx)
	if err != nil {
		t.Error(err)
	}

355
	err = node.DAG.Add(ctx, unixfs.EmptyDirNode())
356 357 358 359
	if err != nil {
		t.Error(err)
	}

360
	emptyDir, err := api.Object().New(ctx, options.Object.Type("unixfs-dir"))
361 362 363 364
	if err != nil {
		t.Error(err)
	}

365
	links, err := api.Unixfs().Ls(ctx, coreiface.IpfsPath(emptyDir.Cid()))
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
	if err != nil {
		t.Error(err)
	}

	if len(links) != 0 {
		t.Fatalf("expected 0 links, got %d", len(links))
	}
}

// TODO(lgierth) this should test properly, with len(links) > 0
func TestLsNonUnixfs(t *testing.T) {
	ctx := context.Background()
	node, api, err := makeAPI(ctx)
	if err != nil {
		t.Error(err)
	}

383
	nd, err := cbor.WrapObject(map[string]interface{}{"foo": "bar"}, math.MaxUint64, -1)
Jeromy's avatar
Jeromy committed
384 385 386 387
	if err != nil {
		t.Fatal(err)
	}

388
	err = node.DAG.Add(ctx, nd)
389 390 391 392
	if err != nil {
		t.Error(err)
	}

393
	links, err := api.Unixfs().Ls(ctx, coreiface.IpfsPath(nd.Cid()))
394 395 396 397 398 399 400 401
	if err != nil {
		t.Error(err)
	}

	if len(links) != 0 {
		t.Fatalf("expected 0 links, got %d", len(links))
	}
}