@cryptotaxi247 / kubo / commits / 65579081d

coreapi: extract interface

License: MIT Signed-off-by: Łukasz Magiera <magik6k@gmail.com>

Łukasz Magiera committed Feb 9, 2019 at 01:07 UTC 65579081d98c56ce11932cdbe1492925dbaee36d
35 files changed -5518
core/coreapi/interface/block.go deleted
-36
@@ -1,36 +0,0 @@
1 -package iface
2 -
3 -import (
4 - "context"
5 - "io"
6 -
7 - options "github.com/ipfs/go-ipfs/core/coreapi/interface/options"
8 -)
9 -
10 -// BlockStat contains information about a block
11 -type BlockStat interface {
12 - // Size is the size of a block
13 - Size() int
14 -
15 - // Path returns path to the block
16 - Path() ResolvedPath
17 -}
18 -
19 -// BlockAPI specifies the interface to the block layer
20 -type BlockAPI interface {
21 - // Put imports raw block data, hashing it using specified settings.
22 - Put(context.Context, io.Reader, ...options.BlockPutOption) (BlockStat, error)
23 -
24 - // Get attempts to resolve the path and return a reader for data in the block
25 - Get(context.Context, Path) (io.Reader, error)
26 -
27 - // Rm removes the block specified by the path from local blockstore.
28 - // By default an error will be returned if the block can't be found locally.
29 - //
30 - // NOTE: If the specified block is pinned it won't be removed and no error
31 - // will be returned
32 - Rm(context.Context, Path, ...options.BlockRmOption) error
33 -
34 - // Stat returns information on
35 - Stat(context.Context, Path) (BlockStat, error)
36 -}
core/coreapi/interface/coreapi.go deleted
-55
@@ -1,55 +0,0 @@
1 -// Package iface defines IPFS Core API which is a set of interfaces used to
2 -// interact with IPFS nodes.
3 -package iface
4 -
5 -import (
6 - "context"
7 -
8 - "github.com/ipfs/go-ipfs/core/coreapi/interface/options"
9 -
10 - ipld "gx/ipfs/QmRL22E4paat7ky7vx9MLpR97JHHbFPrg3ytFQw6qp1y1s/go-ipld-format"
11 -)
12 -
13 -// CoreAPI defines an unified interface to IPFS for Go programs
14 -type CoreAPI interface {
15 - // Unixfs returns an implementation of Unixfs API
16 - Unixfs() UnixfsAPI
17 -
18 - // Block returns an implementation of Block API
19 - Block() BlockAPI
20 -
21 - // Dag returns an implementation of Dag API
22 - Dag() APIDagService
23 -
24 - // Name returns an implementation of Name API
25 - Name() NameAPI
26 -
27 - // Key returns an implementation of Key API
28 - Key() KeyAPI
29 -
30 - // Pin returns an implementation of Pin API
31 - Pin() PinAPI
32 -
33 - // ObjectAPI returns an implementation of Object API
34 - Object() ObjectAPI
35 -
36 - // Dht returns an implementation of Dht API
37 - Dht() DhtAPI
38 -
39 - // Swarm returns an implementation of Swarm API
40 - Swarm() SwarmAPI
41 -
42 - // PubSub returns an implementation of PubSub API
43 - PubSub() PubSubAPI
44 -
45 - // ResolvePath resolves the path using Unixfs resolver
46 - ResolvePath(context.Context, Path) (ResolvedPath, error)
47 -
48 - // ResolveNode resolves the path (if not resolved already) using Unixfs
49 - // resolver, gets and returns the resolved Node
50 - ResolveNode(context.Context, Path) (ipld.Node, error)
51 -
52 - // WithOptions creates new instance of CoreAPI based on this instance with
53 - // a set of options applied
54 - WithOptions(...options.ApiOption) (CoreAPI, error)
55 -}
core/coreapi/interface/dag.go deleted
-13
@@ -1,13 +0,0 @@
1 -package iface
2 -
3 -import (
4 - ipld "gx/ipfs/QmRL22E4paat7ky7vx9MLpR97JHHbFPrg3ytFQw6qp1y1s/go-ipld-format"
5 -)
6 -
7 -// APIDagService extends ipld.DAGService
8 -type APIDagService interface {
9 - ipld.DAGService
10 -
11 - // Pinning returns special NodeAdder which recursively pins added nodes
12 - Pinning() ipld.NodeAdder
13 -}
core/coreapi/interface/dht.go deleted
-26
@@ -1,26 +0,0 @@
1 -package iface
2 -
3 -import (
4 - "context"
5 -
6 - "github.com/ipfs/go-ipfs/core/coreapi/interface/options"
7 -
8 - peer "gx/ipfs/QmPJxxDsX2UbchSHobbYuvz7qnyJTFKvaKMzE2rZWJ4x5B/go-libp2p-peer"
9 - pstore "gx/ipfs/QmQFFp4ntkd4C14sP3FaH9WJyBuetuGUVo6dShNHvnoEvC/go-libp2p-peerstore"
10 -)
11 -
12 -// DhtAPI specifies the interface to the DHT
13 -// Note: This API will likely get deprecated in near future, see
14 -// https://github.com/ipfs/interface-ipfs-core/issues/249 for more context.
15 -type DhtAPI interface {
16 - // FindPeer queries the DHT for all of the multiaddresses associated with a
17 - // Peer ID
18 - FindPeer(context.Context, peer.ID) (pstore.PeerInfo, error)
19 -
20 - // FindProviders finds peers in the DHT who can provide a specific value
21 - // given a key.
22 - FindProviders(context.Context, Path, ...options.DhtFindProvidersOption) (<-chan pstore.PeerInfo, error)
23 -
24 - // Provide announces to the network that you are providing given values
25 - Provide(context.Context, Path, ...options.DhtProvideOption) error
26 -}
core/coreapi/interface/errors.go deleted
-9
@@ -1,9 +0,0 @@
1 -package iface
2 -
3 -import "errors"
4 -
5 -var (
6 - ErrIsDir = errors.New("this dag node is a directory")
7 - ErrNotFile = errors.New("this dag node is not a regular file")
8 - ErrOffline = errors.New("this action must be run in online mode, try running 'ipfs daemon' first")
9 -)
core/coreapi/interface/key.go deleted
-41
@@ -1,41 +0,0 @@
1 -package iface
2 -
3 -import (
4 - "context"
5 -
6 - options "github.com/ipfs/go-ipfs/core/coreapi/interface/options"
7 -
8 - "gx/ipfs/QmPJxxDsX2UbchSHobbYuvz7qnyJTFKvaKMzE2rZWJ4x5B/go-libp2p-peer"
9 -)
10 -
11 -// Key specifies the interface to Keys in KeyAPI Keystore
12 -type Key interface {
13 - // Key returns key name
14 - Name() string
15 -
16 - // Path returns key path
17 - Path() Path
18 -
19 - // ID returns key PeerID
20 - ID() peer.ID
21 -}
22 -
23 -// KeyAPI specifies the interface to Keystore
24 -type KeyAPI interface {
25 - // Generate generates new key, stores it in the keystore under the specified
26 - // name and returns a base58 encoded multihash of it's public key
27 - Generate(ctx context.Context, name string, opts ...options.KeyGenerateOption) (Key, error)
28 -
29 - // Rename renames oldName key to newName. Returns the key and whether another
30 - // key was overwritten, or an error
31 - Rename(ctx context.Context, oldName string, newName string, opts ...options.KeyRenameOption) (Key, bool, error)
32 -
33 - // List lists keys stored in keystore
34 - List(ctx context.Context) ([]Key, error)
35 -
36 - // Self returns the 'main' node key
37 - Self(ctx context.Context) (Key, error)
38 -
39 - // Remove removes keys from keystore. Returns ipns path of the removed key
40 - Remove(ctx context.Context, name string) (Key, error)
41 -}
core/coreapi/interface/name.go deleted
-46
@@ -1,46 +0,0 @@
1 -package iface
2 -
3 -import (
4 - "context"
5 - "errors"
6 -
7 - options "github.com/ipfs/go-ipfs/core/coreapi/interface/options"
8 -)
9 -
10 -var ErrResolveFailed = errors.New("could not resolve name")
11 -
12 -// IpnsEntry specifies the interface to IpnsEntries
13 -type IpnsEntry interface {
14 - // Name returns IpnsEntry name
15 - Name() string
16 - // Value returns IpnsEntry value
17 - Value() Path
18 -}
19 -
20 -type IpnsResult struct {
21 - Path
22 - Err error
23 -}
24 -
25 -// NameAPI specifies the interface to IPNS.
26 -//
27 -// IPNS is a PKI namespace, where names are the hashes of public keys, and the
28 -// private key enables publishing new (signed) values. In both publish and
29 -// resolve, the default name used is the node's own PeerID, which is the hash of
30 -// its public key.
31 -//
32 -// You can use .Key API to list and generate more names and their respective keys.
33 -type NameAPI interface {
34 - // Publish announces new IPNS name
35 - Publish(ctx context.Context, path Path, opts ...options.NamePublishOption) (IpnsEntry, error)
36 -
37 - // Resolve attempts to resolve the newest version of the specified name
38 - Resolve(ctx context.Context, name string, opts ...options.NameResolveOption) (Path, error)
39 -
40 - // Search is a version of Resolve which outputs paths as they are discovered,
41 - // reducing the time to first entry
42 - //
43 - // Note: by default, all paths read from the channel are considered unsafe,
44 - // except the latest (last path in channel read buffer).
45 - Search(ctx context.Context, name string, opts ...options.NameResolveOption) (<-chan IpnsResult, error)
46 -}
core/coreapi/interface/object.go deleted
-106
@@ -1,106 +0,0 @@
1 -package iface
2 -
3 -import (
4 - "context"
5 - "io"
6 -
7 - options "github.com/ipfs/go-ipfs/core/coreapi/interface/options"
8 -
9 - cid "gx/ipfs/QmR8BauakNcBa3RbE4nbQu76PDiJgoQgz8AJdhJuiU4TAw/go-cid"
10 - ipld "gx/ipfs/QmRL22E4paat7ky7vx9MLpR97JHHbFPrg3ytFQw6qp1y1s/go-ipld-format"
11 -)
12 -
13 -// ObjectStat provides information about dag nodes
14 -type ObjectStat struct {
15 - // Cid is the CID of the node
16 - Cid cid.Cid
17 -
18 - // NumLinks is number of links the node contains
19 - NumLinks int
20 -
21 - // BlockSize is size of the raw serialized node
22 - BlockSize int
23 -
24 - // LinksSize is size of the links block section
25 - LinksSize int
26 -
27 - // DataSize is the size of data block section
28 - DataSize int
29 -
30 - // CumulativeSize is size of the tree (BlockSize + link sizes)
31 - CumulativeSize int
32 -}
33 -
34 -// ChangeType denotes type of change in ObjectChange
35 -type ChangeType int
36 -
37 -const (
38 - // DiffAdd is set when a link was added to the graph
39 - DiffAdd ChangeType = iota
40 -
41 - // DiffRemove is set when a link was removed from the graph
42 - DiffRemove
43 -
44 - // DiffMod is set when a link was changed in the graph
45 - DiffMod
46 -)
47 -
48 -// ObjectChange represents a change ia a graph
49 -type ObjectChange struct {
50 - // Type of the change, either:
51 - // * DiffAdd - Added a link
52 - // * DiffRemove - Removed a link
53 - // * DiffMod - Modified a link
54 - Type ChangeType
55 -
56 - // Path to the changed link
57 - Path string
58 -
59 - // Before holds the link path before the change. Note that when a link is
60 - // added, this will be nil.
61 - Before ResolvedPath
62 -
63 - // After holds the link path after the change. Note that when a link is
64 - // removed, this will be nil.
65 - After ResolvedPath
66 -}
67 -
68 -// ObjectAPI specifies the interface to MerkleDAG and contains useful utilities
69 -// for manipulating MerkleDAG data structures.
70 -type ObjectAPI interface {
71 - // New creates new, empty (by default) dag-node.
72 - New(context.Context, ...options.ObjectNewOption) (ipld.Node, error)
73 -
74 - // Put imports the data into merkledag
75 - Put(context.Context, io.Reader, ...options.ObjectPutOption) (ResolvedPath, error)
76 -
77 - // Get returns the node for the path
78 - Get(context.Context, Path) (ipld.Node, error)
79 -
80 - // Data returns reader for data of the node
81 - Data(context.Context, Path) (io.Reader, error)
82 -
83 - // Links returns lint or links the node contains
84 - Links(context.Context, Path) ([]*ipld.Link, error)
85 -
86 - // Stat returns information about the node
87 - Stat(context.Context, Path) (*ObjectStat, error)
88 -
89 - // AddLink adds a link under the specified path. child path can point to a
90 - // subdirectory within the patent which must be present (can be overridden
91 - // with WithCreate option).
92 - AddLink(ctx context.Context, base Path, name string, child Path, opts ...options.ObjectAddLinkOption) (ResolvedPath, error)
93 -
94 - // RmLink removes a link from the node
95 - RmLink(ctx context.Context, base Path, link string) (ResolvedPath, error)
96 -
97 - // AppendData appends data to the node
98 - AppendData(context.Context, Path, io.Reader) (ResolvedPath, error)
99 -
100 - // SetData sets the data contained in the node
101 - SetData(context.Context, Path, io.Reader) (ResolvedPath, error)
102 -
103 - // Diff returns a set of changes needed to transform the first object into the
104 - // second.
105 - Diff(context.Context, Path, Path) ([]ObjectChange, error)
106 -}
core/coreapi/interface/options/block.go deleted
-126
@@ -1,126 +0,0 @@
1 -package options
2 -
3 -import (
4 - "fmt"
5 - cid "gx/ipfs/QmR8BauakNcBa3RbE4nbQu76PDiJgoQgz8AJdhJuiU4TAw/go-cid"
6 - mh "gx/ipfs/QmerPMzPk1mJVowm8KgmoknWa4yCYvvugMPsgWmDNUvDLW/go-multihash"
7 -)
8 -
9 -type BlockPutSettings struct {
10 - Codec string
11 - MhType uint64
12 - MhLength int
13 - Pin bool
14 -}
15 -
16 -type BlockRmSettings struct {
17 - Force bool
18 -}
19 -
20 -type BlockPutOption func(*BlockPutSettings) error
21 -type BlockRmOption func(*BlockRmSettings) error
22 -
23 -func BlockPutOptions(opts ...BlockPutOption) (*BlockPutSettings, cid.Prefix, error) {
24 - options := &BlockPutSettings{
25 - Codec: "",
26 - MhType: mh.SHA2_256,
27 - MhLength: -1,
28 - Pin: false,
29 - }
30 -
31 - for _, opt := range opts {
32 - err := opt(options)
33 - if err != nil {
34 - return nil, cid.Prefix{}, err
35 - }
36 - }
37 -
38 - var pref cid.Prefix
39 - pref.Version = 1
40 -
41 - if options.Codec == "" {
42 - if options.MhType != mh.SHA2_256 || (options.MhLength != -1 && options.MhLength != 32) {
43 - options.Codec = "protobuf"
44 - } else {
45 - options.Codec = "v0"
46 - }
47 - }
48 -
49 - if options.Codec == "v0" && options.MhType == mh.SHA2_256 {
50 - pref.Version = 0
51 - }
52 -
53 - formatval, ok := cid.Codecs[options.Codec]
54 - if !ok {
55 - return nil, cid.Prefix{}, fmt.Errorf("unrecognized format: %s", options.Codec)
56 - }
57 -
58 - if options.Codec == "v0" {
59 - if options.MhType != mh.SHA2_256 || (options.MhLength != -1 && options.MhLength != 32) {
60 - return nil, cid.Prefix{}, fmt.Errorf("only sha2-255-32 is allowed with CIDv0")
61 - }
62 - }
63 -
64 - pref.Codec = formatval
65 -
66 - pref.MhType = options.MhType
67 - pref.MhLength = options.MhLength
68 -
69 - return options, pref, nil
70 -}
71 -
72 -func BlockRmOptions(opts ...BlockRmOption) (*BlockRmSettings, error) {
73 - options := &BlockRmSettings{
74 - Force: false,
75 - }
76 -
77 - for _, opt := range opts {
78 - err := opt(options)
79 - if err != nil {
80 - return nil, err
81 - }
82 - }
83 - return options, nil
84 -}
85 -
86 -type blockOpts struct{}
87 -
88 -var Block blockOpts
89 -
90 -// Format is an option for Block.Put which specifies the multicodec to use to
91 -// serialize the object. Default is "v0"
92 -func (blockOpts) Format(codec string) BlockPutOption {
93 - return func(settings *BlockPutSettings) error {
94 - settings.Codec = codec
95 - return nil
96 - }
97 -}
98 -
99 -// Hash is an option for Block.Put which specifies the multihash settings to use
100 -// when hashing the object. Default is mh.SHA2_256 (0x12).
101 -// If mhLen is set to -1, default length for the hash will be used
102 -func (blockOpts) Hash(mhType uint64, mhLen int) BlockPutOption {
103 - return func(settings *BlockPutSettings) error {
104 - settings.MhType = mhType
105 - settings.MhLength = mhLen
106 - return nil
107 - }
108 -}
109 -
110 -// Pin is an option for Block.Put which specifies whether to (recursively) pin
111 -// added blocks
112 -func (blockOpts) Pin(pin bool) BlockPutOption {
113 - return func(settings *BlockPutSettings) error {
114 - settings.Pin = pin
115 - return nil
116 - }
117 -}
118 -
119 -// Force is an option for Block.Rm which, when set to true, will ignore
120 -// non-existing blocks
121 -func (blockOpts) Force(force bool) BlockRmOption {
122 - return func(settings *BlockRmSettings) error {
123 - settings.Force = force
124 - return nil
125 - }
126 -}
core/coreapi/interface/options/dht.go deleted
-62
@@ -1,62 +0,0 @@
1 -package options
2 -
3 -type DhtProvideSettings struct {
4 - Recursive bool
5 -}
6 -
7 -type DhtFindProvidersSettings struct {
8 - NumProviders int
9 -}
10 -
11 -type DhtProvideOption func(*DhtProvideSettings) error
12 -type DhtFindProvidersOption func(*DhtFindProvidersSettings) error
13 -
14 -func DhtProvideOptions(opts ...DhtProvideOption) (*DhtProvideSettings, error) {
15 - options := &DhtProvideSettings{
16 - Recursive: false,
17 - }
18 -
19 - for _, opt := range opts {
20 - err := opt(options)
21 - if err != nil {
22 - return nil, err
23 - }
24 - }
25 - return options, nil
26 -}
27 -
28 -func DhtFindProvidersOptions(opts ...DhtFindProvidersOption) (*DhtFindProvidersSettings, error) {
29 - options := &DhtFindProvidersSettings{
30 - NumProviders: 20,
31 - }
32 -
33 - for _, opt := range opts {
34 - err := opt(options)
35 - if err != nil {
36 - return nil, err
37 - }
38 - }
39 - return options, nil
40 -}
41 -
42 -type dhtOpts struct{}
43 -
44 -var Dht dhtOpts
45 -
46 -// Recursive is an option for Dht.Provide which specifies whether to provide
47 -// the given path recursively
48 -func (dhtOpts) Recursive(recursive bool) DhtProvideOption {
49 - return func(settings *DhtProvideSettings) error {
50 - settings.Recursive = recursive
51 - return nil
52 - }
53 -}
54 -
55 -// NumProviders is an option for Dht.FindProviders which specifies the
56 -// number of peers to look for. Default is 20
57 -func (dhtOpts) NumProviders(numProviders int) DhtFindProvidersOption {
58 - return func(settings *DhtFindProvidersSettings) error {
59 - settings.NumProviders = numProviders
60 - return nil
61 - }
62 -}
core/coreapi/interface/options/global.go deleted
-47
@@ -1,47 +0,0 @@
1 -package options
2 -
3 -type ApiSettings struct {
4 - Offline bool
5 - FetchBlocks bool
6 -}
7 -
8 -type ApiOption func(*ApiSettings) error
9 -
10 -func ApiOptions(opts ...ApiOption) (*ApiSettings, error) {
11 - options := &ApiSettings{
12 - Offline: false,
13 - FetchBlocks: true,
14 - }
15 -
16 - return ApiOptionsTo(options, opts...)
17 -}
18 -
19 -func ApiOptionsTo(options *ApiSettings, opts ...ApiOption) (*ApiSettings, error) {
20 - for _, opt := range opts {
21 - err := opt(options)
22 - if err != nil {
23 - return nil, err
24 - }
25 - }
26 - return options, nil
27 -}
28 -
29 -type apiOpts struct{}
30 -
31 -var Api apiOpts
32 -
33 -func (apiOpts) Offline(offline bool) ApiOption {
34 - return func(settings *ApiSettings) error {
35 - settings.Offline = offline
36 - return nil
37 - }
38 -}
39 -
40 -// FetchBlocks when set to false prevents api from fetching blocks from the
41 -// network while allowing other services such as IPNS to still be online
42 -func (apiOpts) FetchBlocks(fetch bool) ApiOption {
43 - return func(settings *ApiSettings) error {
44 - settings.FetchBlocks = fetch
45 - return nil
46 - }
47 -}
core/coreapi/interface/options/key.go deleted
-87
@@ -1,87 +0,0 @@
1 -package options
2 -
3 -const (
4 - RSAKey = "rsa"
5 - Ed25519Key = "ed25519"
6 -
7 - DefaultRSALen = 2048
8 -)
9 -
10 -type KeyGenerateSettings struct {
11 - Algorithm string
12 - Size int
13 -}
14 -
15 -type KeyRenameSettings struct {
16 - Force bool
17 -}
18 -
19 -type KeyGenerateOption func(*KeyGenerateSettings) error
20 -type KeyRenameOption func(*KeyRenameSettings) error
21 -
22 -func KeyGenerateOptions(opts ...KeyGenerateOption) (*KeyGenerateSettings, error) {
23 - options := &KeyGenerateSettings{
24 - Algorithm: RSAKey,
25 - Size: -1,
26 - }
27 -
28 - for _, opt := range opts {
29 - err := opt(options)
30 - if err != nil {
31 - return nil, err
32 - }
33 - }
34 - return options, nil
35 -}
36 -
37 -func KeyRenameOptions(opts ...KeyRenameOption) (*KeyRenameSettings, error) {
38 - options := &KeyRenameSettings{
39 - Force: false,
40 - }
41 -
42 - for _, opt := range opts {
43 - err := opt(options)
44 - if err != nil {
45 - return nil, err
46 - }
47 - }
48 - return options, nil
49 -}
50 -
51 -type keyOpts struct{}
52 -
53 -var Key keyOpts
54 -
55 -// Type is an option for Key.Generate which specifies which algorithm
56 -// should be used for the key. Default is options.RSAKey
57 -//
58 -// Supported key types:
59 -// * options.RSAKey
60 -// * options.Ed25519Key
61 -func (keyOpts) Type(algorithm string) KeyGenerateOption {
62 - return func(settings *KeyGenerateSettings) error {
63 - settings.Algorithm = algorithm
64 - return nil
65 - }
66 -}
67 -
68 -// Size is an option for Key.Generate which specifies the size of the key to
69 -// generated. Default is -1
70 -//
71 -// value of -1 means 'use default size for key type':
72 -// * 2048 for RSA
73 -func (keyOpts) Size(size int) KeyGenerateOption {
74 - return func(settings *KeyGenerateSettings) error {
75 - settings.Size = size
76 - return nil
77 - }
78 -}
79 -
80 -// Force is an option for Key.Rename which specifies whether to allow to
81 -// replace existing keys.
82 -func (keyOpts) Force(force bool) KeyRenameOption {
83 - return func(settings *KeyRenameSettings) error {
84 - settings.Force = force
85 - return nil
86 - }
87 -}
core/coreapi/interface/options/name.go deleted
-122
@@ -1,122 +0,0 @@
1 -package options
2 -
3 -import (
4 - "time"
5 -
6 - ropts "github.com/ipfs/go-ipfs/core/coreapi/interface/options/namesys"
7 -)
8 -
9 -const (
10 - DefaultNameValidTime = 24 * time.Hour
11 -)
12 -
13 -type NamePublishSettings struct {
14 - ValidTime time.Duration
15 - Key string
16 -
17 - TTL *time.Duration
18 -
19 - AllowOffline bool
20 -}
21 -
22 -type NameResolveSettings struct {
23 - Cache bool
24 -
25 - ResolveOpts []ropts.ResolveOpt
26 -}
27 -
28 -type NamePublishOption func(*NamePublishSettings) error
29 -type NameResolveOption func(*NameResolveSettings) error
30 -
31 -func NamePublishOptions(opts ...NamePublishOption) (*NamePublishSettings, error) {
32 - options := &NamePublishSettings{
33 - ValidTime: DefaultNameValidTime,
34 - Key: "self",
35 -
36 - AllowOffline: false,
37 - }
38 -
39 - for _, opt := range opts {
40 - err := opt(options)
41 - if err != nil {
42 - return nil, err
43 - }
44 - }
45 -
46 - return options, nil
47 -}
48 -
49 -func NameResolveOptions(opts ...NameResolveOption) (*NameResolveSettings, error) {
50 - options := &NameResolveSettings{
51 - Cache: true,
52 - }
53 -
54 - for _, opt := range opts {
55 - err := opt(options)
56 - if err != nil {
57 - return nil, err
58 - }
59 - }
60 -
61 - return options, nil
62 -}
63 -
64 -type nameOpts struct{}
65 -
66 -var Name nameOpts
67 -
68 -// ValidTime is an option for Name.Publish which specifies for how long the
69 -// entry will remain valid. Default value is 24h
70 -func (nameOpts) ValidTime(validTime time.Duration) NamePublishOption {
71 - return func(settings *NamePublishSettings) error {
72 - settings.ValidTime = validTime
73 - return nil
74 - }
75 -}
76 -
77 -// Key is an option for Name.Publish which specifies the key to use for
78 -// publishing. Default value is "self" which is the node's own PeerID.
79 -// The key parameter must be either PeerID or keystore key alias.
80 -//
81 -// You can use KeyAPI to list and generate more names and their respective keys.
82 -func (nameOpts) Key(key string) NamePublishOption {
83 - return func(settings *NamePublishSettings) error {
84 - settings.Key = key
85 - return nil
86 - }
87 -}
88 -
89 -// AllowOffline is an option for Name.Publish which specifies whether to allow
90 -// publishing when the node is offline. Default value is false
91 -func (nameOpts) AllowOffline(allow bool) NamePublishOption {
92 - return func(settings *NamePublishSettings) error {
93 - settings.AllowOffline = allow
94 - return nil
95 - }
96 -}
97 -
98 -// TTL is an option for Name.Publish which specifies the time duration the
99 -// published record should be cached for (caution: experimental).
100 -func (nameOpts) TTL(ttl time.Duration) NamePublishOption {
101 - return func(settings *NamePublishSettings) error {
102 - settings.TTL = &ttl
103 - return nil
104 - }
105 -}
106 -
107 -// Cache is an option for Name.Resolve which specifies if cache should be used.
108 -// Default value is true
109 -func (nameOpts) Cache(cache bool) NameResolveOption {
110 - return func(settings *NameResolveSettings) error {
111 - settings.Cache = cache
112 - return nil
113 - }
114 -}
115 -
116 -//
117 -func (nameOpts) ResolveOption(opt ropts.ResolveOpt) NameResolveOption {
118 - return func(settings *NameResolveSettings) error {
119 - settings.ResolveOpts = append(settings.ResolveOpts, opt)
120 - return nil
121 - }
122 -}
core/coreapi/interface/options/namesys/opts.go deleted
-74
@@ -1,74 +0,0 @@
1 -package nsopts
2 -
3 -import (
4 - "time"
5 -)
6 -
7 -const (
8 - // DefaultDepthLimit is the default depth limit used by Resolve.
9 - DefaultDepthLimit = 32
10 -
11 - // UnlimitedDepth allows infinite recursion in Resolve. You
12 - // probably don't want to use this, but it's here if you absolutely
13 - // trust resolution to eventually complete and can't put an upper
14 - // limit on how many steps it will take.
15 - UnlimitedDepth = 0
16 -)
17 -
18 -// ResolveOpts specifies options for resolving an IPNS path
19 -type ResolveOpts struct {
20 - // Recursion depth limit
21 - Depth uint
22 - // The number of IPNS records to retrieve from the DHT
23 - // (the best record is selected from this set)
24 - DhtRecordCount uint
25 - // The amount of time to wait for DHT records to be fetched
26 - // and verified. A zero value indicates that there is no explicit
27 - // timeout (although there is an implicit timeout due to dial
28 - // timeouts within the DHT)
29 - DhtTimeout time.Duration
30 -}
31 -
32 -// DefaultResolveOpts returns the default options for resolving
33 -// an IPNS path
34 -func DefaultResolveOpts() ResolveOpts {
35 - return ResolveOpts{
36 - Depth: DefaultDepthLimit,
37 - DhtRecordCount: 16,
38 - DhtTimeout: time.Minute,
39 - }
40 -}
41 -
42 -// ResolveOpt is used to set an option
43 -type ResolveOpt func(*ResolveOpts)
44 -
45 -// Depth is the recursion depth limit
46 -func Depth(depth uint) ResolveOpt {
47 - return func(o *ResolveOpts) {
48 - o.Depth = depth
49 - }
50 -}
51 -
52 -// DhtRecordCount is the number of IPNS records to retrieve from the DHT
53 -func DhtRecordCount(count uint) ResolveOpt {
54 - return func(o *ResolveOpts) {
55 - o.DhtRecordCount = count
56 - }
57 -}
58 -
59 -// DhtTimeout is the amount of time to wait for DHT records to be fetched
60 -// and verified. A zero value indicates that there is no explicit timeout
61 -func DhtTimeout(timeout time.Duration) ResolveOpt {
62 - return func(o *ResolveOpts) {
63 - o.DhtTimeout = timeout
64 - }
65 -}
66 -
67 -// ProcessOpts converts an array of ResolveOpt into a ResolveOpts object
68 -func ProcessOpts(opts []ResolveOpt) ResolveOpts {
69 - rsopts := DefaultResolveOpts()
70 - for _, option := range opts {
71 - option(&rsopts)
72 - }
73 - return rsopts
74 -}
core/coreapi/interface/options/object.go deleted
-124
@@ -1,124 +0,0 @@
1 -package options
2 -
3 -type ObjectNewSettings struct {
4 - Type string
5 -}
6 -
7 -type ObjectPutSettings struct {
8 - InputEnc string
9 - DataType string
10 - Pin bool
11 -}
12 -
13 -type ObjectAddLinkSettings struct {
14 - Create bool
15 -}
16 -
17 -type ObjectNewOption func(*ObjectNewSettings) error
18 -type ObjectPutOption func(*ObjectPutSettings) error
19 -type ObjectAddLinkOption func(*ObjectAddLinkSettings) error
20 -
21 -func ObjectNewOptions(opts ...ObjectNewOption) (*ObjectNewSettings, error) {
22 - options := &ObjectNewSettings{
23 - Type: "empty",
24 - }
25 -
26 - for _, opt := range opts {
27 - err := opt(options)
28 - if err != nil {
29 - return nil, err
30 - }
31 - }
32 - return options, nil
33 -}
34 -
35 -func ObjectPutOptions(opts ...ObjectPutOption) (*ObjectPutSettings, error) {
36 - options := &ObjectPutSettings{
37 - InputEnc: "json",
38 - DataType: "text",
39 - Pin: false,
40 - }
41 -
42 - for _, opt := range opts {
43 - err := opt(options)
44 - if err != nil {
45 - return nil, err
46 - }
47 - }
48 - return options, nil
49 -}
50 -
51 -func ObjectAddLinkOptions(opts ...ObjectAddLinkOption) (*ObjectAddLinkSettings, error) {
52 - options := &ObjectAddLinkSettings{
53 - Create: false,
54 - }
55 -
56 - for _, opt := range opts {
57 - err := opt(options)
58 - if err != nil {
59 - return nil, err
60 - }
61 - }
62 - return options, nil
63 -}
64 -
65 -type objectOpts struct{}
66 -
67 -var Object objectOpts
68 -
69 -// Type is an option for Object.New which allows to change the type of created
70 -// dag node.
71 -//
72 -// Supported types:
73 -// * 'empty' - Empty node
74 -// * 'unixfs-dir' - Empty UnixFS directory
75 -func (objectOpts) Type(t string) ObjectNewOption {
76 - return func(settings *ObjectNewSettings) error {
77 - settings.Type = t
78 - return nil
79 - }
80 -}
81 -
82 -// InputEnc is an option for Object.Put which specifies the input encoding of the
83 -// data. Default is "json".
84 -//
85 -// Supported encodings:
86 -// * "protobuf"
87 -// * "json"
88 -func (objectOpts) InputEnc(e string) ObjectPutOption {
89 - return func(settings *ObjectPutSettings) error {
90 - settings.InputEnc = e
91 - return nil
92 - }
93 -}
94 -
95 -// DataType is an option for Object.Put which specifies the encoding of data
96 -// field when using Json or XML input encoding.
97 -//
98 -// Supported types:
99 -// * "text" (default)
100 -// * "base64"
101 -func (objectOpts) DataType(t string) ObjectPutOption {
102 - return func(settings *ObjectPutSettings) error {
103 - settings.DataType = t
104 - return nil
105 - }
106 -}
107 -
108 -// Pin is an option for Object.Put which specifies whether to pin the added
109 -// objects, default is false
110 -func (objectOpts) Pin(pin bool) ObjectPutOption {
111 - return func(settings *ObjectPutSettings) error {
112 - settings.Pin = pin
113 - return nil
114 - }
115 -}
116 -
117 -// Create is an option for Object.AddLink which specifies whether create required
118 -// directories for the child
119 -func (objectOpts) Create(create bool) ObjectAddLinkOption {
120 - return func(settings *ObjectAddLinkSettings) error {
121 - settings.Create = create
122 - return nil
123 - }
124 -}
core/coreapi/interface/options/pin.go deleted
-161
@@ -1,161 +0,0 @@
1 -package options
2 -
3 -type PinAddSettings struct {
4 - Recursive bool
5 -}
6 -
7 -type PinLsSettings struct {
8 - Type string
9 -}
10 -
11 -// PinRmSettings represents the settings of pin rm command
12 -type PinRmSettings struct {
13 - Recursive bool
14 -}
15 -
16 -type PinUpdateSettings struct {
17 - Unpin bool
18 -}
19 -
20 -type PinAddOption func(*PinAddSettings) error
21 -
22 -// PinRmOption pin rm option func
23 -type PinRmOption func(*PinRmSettings) error
24 -
25 -// PinLsOption pin ls option func
26 -type PinLsOption func(*PinLsSettings) error
27 -type PinUpdateOption func(*PinUpdateSettings) error
28 -
29 -func PinAddOptions(opts ...PinAddOption) (*PinAddSettings, error) {
30 - options := &PinAddSettings{
31 - Recursive: true,
32 - }
33 -
34 - for _, opt := range opts {
35 - err := opt(options)
36 - if err != nil {
37 - return nil, err
38 - }
39 - }
40 -
41 - return options, nil
42 -}
43 -
44 -// PinRmOptions pin rm options
45 -func PinRmOptions(opts ...PinRmOption) (*PinRmSettings, error) {
46 - options := &PinRmSettings{
47 - Recursive: true,
48 - }
49 -
50 - for _, opt := range opts {
51 - if err := opt(options); err != nil {
52 - return nil, err
53 - }
54 - }
55 -
56 - return options, nil
57 -}
58 -
59 -func PinLsOptions(opts ...PinLsOption) (*PinLsSettings, error) {
60 - options := &PinLsSettings{
61 - Type: "all",
62 - }
63 -
64 - for _, opt := range opts {
65 - err := opt(options)
66 - if err != nil {
67 - return nil, err
68 - }
69 - }
70 -
71 - return options, nil
72 -}
73 -
74 -func PinUpdateOptions(opts ...PinUpdateOption) (*PinUpdateSettings, error) {
75 - options := &PinUpdateSettings{
76 - Unpin: true,
77 - }
78 -
79 - for _, opt := range opts {
80 - err := opt(options)
81 - if err != nil {
82 - return nil, err
83 - }
84 - }
85 -
86 - return options, nil
87 -}
88 -
89 -type pinType struct{}
90 -
91 -type pinOpts struct {
92 - Type pinType
93 -}
94 -
95 -var Pin pinOpts
96 -
97 -// All is an option for Pin.Ls which will make it return all pins. It is
98 -// the default
99 -func (pinType) All() PinLsOption {
100 - return Pin.pinType("all")
101 -}
102 -
103 -// Recursive is an option for Pin.Ls which will make it only return recursive
104 -// pins
105 -func (pinType) Recursive() PinLsOption {
106 - return Pin.pinType("recursive")
107 -}
108 -
109 -// Direct is an option for Pin.Ls which will make it only return direct (non
110 -// recursive) pins
111 -func (pinType) Direct() PinLsOption {
112 - return Pin.pinType("direct")
113 -}
114 -
115 -// Indirect is an option for Pin.Ls which will make it only return indirect pins
116 -// (objects referenced by other recursively pinned objects)
117 -func (pinType) Indirect() PinLsOption {
118 - return Pin.pinType("indirect")
119 -}
120 -
121 -// Recursive is an option for Pin.Add which specifies whether to pin an entire
122 -// object tree or just one object. Default: true
123 -func (pinOpts) Recursive(recursive bool) PinAddOption {
124 - return func(settings *PinAddSettings) error {
125 - settings.Recursive = recursive
126 - return nil
127 - }
128 -}
129 -
130 -// RmRecursive is an option for Pin.Rm
131 -func (pinOpts) RmRecursive(recursive bool) PinRmOption {
132 - return func(settings *PinRmSettings) error {
133 - settings.Recursive = recursive
134 - return nil
135 - }
136 -}
137 -
138 -// Type is an option for Pin.Ls which allows to specify which pin types should
139 -// be returned
140 -//
141 -// Supported values:
142 -// * "direct" - directly pinned objects
143 -// * "recursive" - roots of recursive pins
144 -// * "indirect" - indirectly pinned objects (referenced by recursively pinned
145 -// objects)
146 -// * "all" - all pinned objects (default)
147 -func (pinOpts) pinType(t string) PinLsOption {
148 - return func(settings *PinLsSettings) error {
149 - settings.Type = t
150 - return nil
151 - }
152 -}
153 -
154 -// Unpin is an option for Pin.Update which specifies whether to remove the old pin.
155 -// Default is true.
156 -func (pinOpts) Unpin(unpin bool) PinUpdateOption {
157 - return func(settings *PinUpdateSettings) error {
158 - settings.Unpin = unpin
159 - return nil
160 - }
161 -}
core/coreapi/interface/options/pubsub.go deleted
-58
@@ -1,58 +0,0 @@
1 -package options
2 -
3 -type PubSubPeersSettings struct {
4 - Topic string
5 -}
6 -
7 -type PubSubSubscribeSettings struct {
8 - Discover bool
9 -}
10 -
11 -type PubSubPeersOption func(*PubSubPeersSettings) error
12 -type PubSubSubscribeOption func(*PubSubSubscribeSettings) error
13 -
14 -func PubSubPeersOptions(opts ...PubSubPeersOption) (*PubSubPeersSettings, error) {
15 - options := &PubSubPeersSettings{
16 - Topic: "",
17 - }
18 -
19 - for _, opt := range opts {
20 - err := opt(options)
21 - if err != nil {
22 - return nil, err
23 - }
24 - }
25 - return options, nil
26 -}
27 -
28 -func PubSubSubscribeOptions(opts ...PubSubSubscribeOption) (*PubSubSubscribeSettings, error) {
29 - options := &PubSubSubscribeSettings{
30 - Discover: false,
31 - }
32 -
33 - for _, opt := range opts {
34 - err := opt(options)
35 - if err != nil {
36 - return nil, err
37 - }
38 - }
39 - return options, nil
40 -}
41 -
42 -type pubsubOpts struct{}
43 -
44 -var PubSub pubsubOpts
45 -
46 -func (pubsubOpts) Topic(topic string) PubSubPeersOption {
47 - return func(settings *PubSubPeersSettings) error {
48 - settings.Topic = topic
49 - return nil
50 - }
51 -}
52 -
53 -func (pubsubOpts) Discover(discover bool) PubSubSubscribeOption {
54 - return func(settings *PubSubSubscribeSettings) error {
55 - settings.Discover = discover
56 - return nil
57 - }
58 -}
core/coreapi/interface/options/unixfs.go deleted
-319
@@ -1,319 +0,0 @@
1 -package options
2 -
3 -import (
4 - "errors"
5 - "fmt"
6 -
7 - cid "gx/ipfs/QmR8BauakNcBa3RbE4nbQu76PDiJgoQgz8AJdhJuiU4TAw/go-cid"
8 - dag "gx/ipfs/QmUtsx89yiCY6F8mbpP6ecXckiSzCBH7EvkKZuZEHBcr1m/go-merkledag"
9 - mh "gx/ipfs/QmerPMzPk1mJVowm8KgmoknWa4yCYvvugMPsgWmDNUvDLW/go-multihash"
10 -)
11 -
12 -type Layout int
13 -
14 -const (
15 - BalancedLayout Layout = iota
16 - TrickleLayout
17 -)
18 -
19 -type UnixfsAddSettings struct {
20 - CidVersion int
21 - MhType uint64
22 -
23 - Inline bool
24 - InlineLimit int
25 - RawLeaves bool
26 - RawLeavesSet bool
27 -
28 - Chunker string
29 - Layout Layout
30 -
31 - Pin bool
32 - OnlyHash bool
33 - FsCache bool
34 - NoCopy bool
35 -
36 - Wrap bool
37 - Hidden bool
38 - StdinName string
39 -
40 - Events chan<- interface{}
41 - Silent bool
42 - Progress bool
43 -}
44 -
45 -type UnixfsLsSettings struct {
46 - ResolveChildren bool
47 -}
48 -
49 -type UnixfsAddOption func(*UnixfsAddSettings) error
50 -type UnixfsLsOption func(*UnixfsLsSettings) error
51 -
52 -func UnixfsAddOptions(opts ...UnixfsAddOption) (*UnixfsAddSettings, cid.Prefix, error) {
53 - options := &UnixfsAddSettings{
54 - CidVersion: -1,
55 - MhType: mh.SHA2_256,
56 -
57 - Inline: false,
58 - InlineLimit: 32,
59 - RawLeaves: false,
60 - RawLeavesSet: false,
61 -
62 - Chunker: "size-262144",
63 - Layout: BalancedLayout,
64 -
65 - Pin: false,
66 - OnlyHash: false,
67 - FsCache: false,
68 - NoCopy: false,
69 -
70 - Wrap: false,
71 - Hidden: false,
72 - StdinName: "",
73 -
74 - Events: nil,
75 - Silent: false,
76 - Progress: false,
77 - }
78 -
79 - for _, opt := range opts {
80 - err := opt(options)
81 - if err != nil {
82 - return nil, cid.Prefix{}, err
83 - }
84 - }
85 -
86 - // nocopy -> rawblocks
87 - if options.NoCopy && !options.RawLeaves {
88 - // fixed?
89 - if options.RawLeavesSet {
90 - return nil, cid.Prefix{}, fmt.Errorf("nocopy option requires '--raw-leaves' to be enabled as well")
91 - }
92 -
93 - // No, satisfy mandatory constraint.
94 - options.RawLeaves = true
95 - }
96 -
97 - // (hash != "sha2-256") -> CIDv1
98 - if options.MhType != mh.SHA2_256 {
99 - switch options.CidVersion {
100 - case 0:
101 - return nil, cid.Prefix{}, errors.New("CIDv0 only supports sha2-256")
102 - case 1, -1:
103 - options.CidVersion = 1
104 - default:
105 - return nil, cid.Prefix{}, fmt.Errorf("unknown CID version: %d", options.CidVersion)
106 - }
107 - } else {
108 - if options.CidVersion < 0 {
109 - // Default to CIDv0
110 - options.CidVersion = 0
111 - }
112 - }
113 -
114 - // cidV1 -> raw blocks (by default)
115 - if options.CidVersion > 0 && !options.RawLeavesSet {
116 - options.RawLeaves = true
117 - }
118 -
119 - prefix, err := dag.PrefixForCidVersion(options.CidVersion)
120 - if err != nil {
121 - return nil, cid.Prefix{}, err
122 - }
123 -
124 - prefix.MhType = options.MhType
125 - prefix.MhLength = -1
126 -
127 - return options, prefix, nil
128 -}
129 -
130 -func UnixfsLsOptions(opts ...UnixfsLsOption) (*UnixfsLsSettings, error) {
131 - options := &UnixfsLsSettings{
132 - ResolveChildren: true,
133 - }
134 -
135 - for _, opt := range opts {
136 - err := opt(options)
137 - if err != nil {
138 - return nil, err
139 - }
140 - }
141 -
142 - return options, nil
143 -}
144 -
145 -type unixfsOpts struct{}
146 -
147 -var Unixfs unixfsOpts
148 -
149 -// CidVersion specifies which CID version to use. Defaults to 0 unless an option
150 -// that depends on CIDv1 is passed.
151 -func (unixfsOpts) CidVersion(version int) UnixfsAddOption {
152 - return func(settings *UnixfsAddSettings) error {
153 - settings.CidVersion = version
154 - return nil
155 - }
156 -}
157 -
158 -// Hash function to use. Implies CIDv1 if not set to sha2-256 (default).
159 -//
160 -// Table of functions is declared in https://github.com/multiformats/go-multihash/blob/master/multihash.go
161 -func (unixfsOpts) Hash(mhtype uint64) UnixfsAddOption {
162 - return func(settings *UnixfsAddSettings) error {
163 - settings.MhType = mhtype
164 - return nil
165 - }
166 -}
167 -
168 -// RawLeaves specifies whether to use raw blocks for leaves (data nodes with no
169 -// links) instead of wrapping them with unixfs structures.
170 -func (unixfsOpts) RawLeaves(enable bool) UnixfsAddOption {
171 - return func(settings *UnixfsAddSettings) error {
172 - settings.RawLeaves = enable
173 - settings.RawLeavesSet = true
174 - return nil
175 - }
176 -}
177 -
178 -// Inline tells the adder to inline small blocks into CIDs
179 -func (unixfsOpts) Inline(enable bool) UnixfsAddOption {
180 - return func(settings *UnixfsAddSettings) error {
181 - settings.Inline = enable
182 - return nil
183 - }
184 -}
185 -
186 -// InlineLimit sets the amount of bytes below which blocks will be encoded
187 -// directly into CID instead of being stored and addressed by it's hash.
188 -// Specifying this option won't enable block inlining. For that use `Inline`
189 -// option. Default: 32 bytes
190 -//
191 -// Note that while there is no hard limit on the number of bytes, it should be
192 -// kept at a reasonably low value, such as 64; implementations may choose to
193 -// reject anything larger.
194 -func (unixfsOpts) InlineLimit(limit int) UnixfsAddOption {
195 - return func(settings *UnixfsAddSettings) error {
196 - settings.InlineLimit = limit
197 - return nil
198 - }
199 -}
200 -
201 -// Chunker specifies settings for the chunking algorithm to use.
202 -//
203 -// Default: size-262144, formats:
204 -// size-[bytes] - Simple chunker splitting data into blocks of n bytes
205 -// rabin-[min]-[avg]-[max] - Rabin chunker
206 -func (unixfsOpts) Chunker(chunker string) UnixfsAddOption {
207 - return func(settings *UnixfsAddSettings) error {
208 - settings.Chunker = chunker
209 - return nil
210 - }
211 -}
212 -
213 -// Layout tells the adder how to balance data between leaves.
214 -// options.BalancedLayout is the default, it's optimized for static seekable
215 -// files.
216 -// options.TrickleLayout is optimized for streaming data,
217 -func (unixfsOpts) Layout(layout Layout) UnixfsAddOption {
218 - return func(settings *UnixfsAddSettings) error {
219 - settings.Layout = layout
220 - return nil
221 - }
222 -}
223 -
224 -// Pin tells the adder to pin the file root recursively after adding
225 -func (unixfsOpts) Pin(pin bool) UnixfsAddOption {
226 - return func(settings *UnixfsAddSettings) error {
227 - settings.Pin = pin
228 - return nil
229 - }
230 -}
231 -
232 -// HashOnly will make the adder calculate data hash without storing it in the
233 -// blockstore or announcing it to the network
234 -func (unixfsOpts) HashOnly(hashOnly bool) UnixfsAddOption {
235 - return func(settings *UnixfsAddSettings) error {
236 - settings.OnlyHash = hashOnly
237 - return nil
238 - }
239 -}
240 -
241 -// Wrap tells the adder to wrap the added file structure with an additional
242 -// directory.
243 -func (unixfsOpts) Wrap(wrap bool) UnixfsAddOption {
244 - return func(settings *UnixfsAddSettings) error {
245 - settings.Wrap = wrap
246 - return nil
247 - }
248 -}
249 -
250 -// Hidden enables adding of hidden files (files prefixed with '.')
251 -func (unixfsOpts) Hidden(hidden bool) UnixfsAddOption {
252 - return func(settings *UnixfsAddSettings) error {
253 - settings.Hidden = hidden
254 - return nil
255 - }
256 -}
257 -
258 -// StdinName is the name set for files which don specify FilePath as
259 -// os.Stdin.Name()
260 -func (unixfsOpts) StdinName(name string) UnixfsAddOption {
261 - return func(settings *UnixfsAddSettings) error {
262 - settings.StdinName = name
263 - return nil
264 - }
265 -}
266 -
267 -// Events specifies channel which will be used to report events about ongoing
268 -// Add operation.
269 -//
270 -// Note that if this channel blocks it may slowdown the adder
271 -func (unixfsOpts) Events(sink chan<- interface{}) UnixfsAddOption {
272 - return func(settings *UnixfsAddSettings) error {
273 - settings.Events = sink
274 - return nil
275 - }
276 -}
277 -
278 -// Silent reduces event output
279 -func (unixfsOpts) Silent(silent bool) UnixfsAddOption {
280 - return func(settings *UnixfsAddSettings) error {
281 - settings.Silent = silent
282 - return nil
283 - }
284 -}
285 -
286 -// Progress tells the adder whether to enable progress events
287 -func (unixfsOpts) Progress(enable bool) UnixfsAddOption {
288 - return func(settings *UnixfsAddSettings) error {
289 - settings.Progress = enable
290 - return nil
291 - }
292 -}
293 -
294 -// FsCache tells the adder to check the filestore for pre-existing blocks
295 -//
296 -// Experimental
297 -func (unixfsOpts) FsCache(enable bool) UnixfsAddOption {
298 - return func(settings *UnixfsAddSettings) error {
299 - settings.FsCache = enable
300 - return nil
301 - }
302 -}
303 -
304 -// NoCopy tells the adder to add the files using filestore. Implies RawLeaves.
305 -//
306 -// Experimental
307 -func (unixfsOpts) Nocopy(enable bool) UnixfsAddOption {
308 - return func(settings *UnixfsAddSettings) error {
309 - settings.NoCopy = enable
310 - return nil
311 - }
312 -}
313 -
314 -func (unixfsOpts) ResolveChildren(resolve bool) UnixfsLsOption {
315 - return func(settings *UnixfsLsSettings) error {
316 - settings.ResolveChildren = resolve
317 - return nil
318 - }
319 -}
core/coreapi/interface/path.go deleted
-182
@@ -1,182 +0,0 @@
1 -package iface
2 -
3 -import (
4 - ipfspath "gx/ipfs/QmQ3YSqfxunT5QBg6KBVskKyRE26q6hjSMyhpxchpm7jEN/go-path"
5 - "gx/ipfs/QmR8BauakNcBa3RbE4nbQu76PDiJgoQgz8AJdhJuiU4TAw/go-cid"
6 -)
7 -
8 -//TODO: merge with ipfspath so we don't depend on it
9 -
10 -// Path is a generic wrapper for paths used in the API. A path can be resolved
11 -// to a CID using one of Resolve functions in the API.
12 -//
13 -// Paths must be prefixed with a valid prefix:
14 -//
15 -// * /ipfs - Immutable unixfs path (files)
16 -// * /ipld - Immutable ipld path (data)
17 -// * /ipns - Mutable names. Usually resolves to one of the immutable paths
18 -//TODO: /local (MFS)
19 -type Path interface {
20 - // String returns the path as a string.
21 - String() string
22 -
23 - // Namespace returns the first component of the path.
24 - //
25 - // For example path "/ipfs/QmHash", calling Namespace() will return "ipfs"
26 - Namespace() string
27 -
28 - // Mutable returns false if the data pointed to by this path in guaranteed
29 - // to not change.
30 - //
31 - // Note that resolved mutable path can be immutable.
32 - Mutable() bool
33 -}
34 -
35 -// ResolvedPath is a path which was resolved to the last resolvable node
36 -type ResolvedPath interface {
37 - // Cid returns the CID of the node referenced by the path. Remainder of the
38 - // path is guaranteed to be within the node.
39 - //
40 - // Examples:
41 - // If you have 3 linked objects: QmRoot -> A -> B:
42 - //
43 - // cidB := {"foo": {"bar": 42 }}
44 - // cidA := {"B": {"/": cidB }}
45 - // cidRoot := {"A": {"/": cidA }}
46 - //
47 - // And resolve paths:
48 - //
49 - // * "/ipfs/${cidRoot}"
50 - // * Calling Cid() will return `cidRoot`
51 - // * Calling Root() will return `cidRoot`
52 - // * Calling Remainder() will return ``
53 - //
54 - // * "/ipfs/${cidRoot}/A"
55 - // * Calling Cid() will return `cidA`
56 - // * Calling Root() will return `cidRoot`
57 - // * Calling Remainder() will return ``
58 - //
59 - // * "/ipfs/${cidRoot}/A/B/foo"
60 - // * Calling Cid() will return `cidB`
61 - // * Calling Root() will return `cidRoot`
62 - // * Calling Remainder() will return `foo`
63 - //
64 - // * "/ipfs/${cidRoot}/A/B/foo/bar"
65 - // * Calling Cid() will return `cidB`
66 - // * Calling Root() will return `cidRoot`
67 - // * Calling Remainder() will return `foo/bar`
68 - Cid() cid.Cid
69 -
70 - // Root returns the CID of the root object of the path
71 - //
72 - // Example:
73 - // If you have 3 linked objects: QmRoot -> A -> B, and resolve path
74 - // "/ipfs/QmRoot/A/B", the Root method will return the CID of object QmRoot
75 - //
76 - // For more examples see the documentation of Cid() method
77 - Root() cid.Cid
78 -
79 - // Remainder returns unresolved part of the path
80 - //
81 - // Example:
82 - // If you have 2 linked objects: QmRoot -> A, where A is a CBOR node
83 - // containing the following data:
84 - //
85 - // {"foo": {"bar": 42 }}
86 - //
87 - // When resolving "/ipld/QmRoot/A/foo/bar", Remainder will return "foo/bar"
88 - //
89 - // For more examples see the documentation of Cid() method
90 - Remainder() string
91 -
92 - Path
93 -}
94 -
95 -// path implements coreiface.Path
96 -type path struct {
97 - path ipfspath.Path
98 -}
99 -
100 -// resolvedPath implements coreiface.resolvedPath
101 -type resolvedPath struct {
102 - path
103 - cid cid.Cid
104 - root cid.Cid
105 - remainder string
106 -}
107 -
108 -// Join appends provided segments to the base path
109 -func Join(base Path, a ...string) Path {
110 - s := ipfspath.Join(append([]string{base.String()}, a...))
111 - return &path{path: ipfspath.FromString(s)}
112 -}
113 -
114 -// IpfsPath creates new /ipfs path from the provided CID
115 -func IpfsPath(c cid.Cid) ResolvedPath {
116 - return &resolvedPath{
117 - path: path{ipfspath.Path("/ipfs/" + c.String())},
118 - cid: c,
119 - root: c,
120 - remainder: "",
121 - }
122 -}
123 -
124 -// IpldPath creates new /ipld path from the provided CID
125 -func IpldPath(c cid.Cid) ResolvedPath {
126 - return &resolvedPath{
127 - path: path{ipfspath.Path("/ipld/" + c.String())},
128 - cid: c,
129 - root: c,
130 - remainder: "",
131 - }
132 -}
133 -
134 -// ParsePath parses string path to a Path
135 -func ParsePath(p string) (Path, error) {
136 - pp, err := ipfspath.ParsePath(p)
137 - if err != nil {
138 - return nil, err
139 - }
140 -
141 - return &path{path: pp}, nil
142 -}
143 -
144 -// NewResolvedPath creates new ResolvedPath. This function performs no checks
145 -// and is intended to be used by resolver implementations. Incorrect inputs may
146 -// cause panics. Handle with care.
147 -func NewResolvedPath(ipath ipfspath.Path, c cid.Cid, root cid.Cid, remainder string) ResolvedPath {
148 - return &resolvedPath{
149 - path: path{ipath},
150 - cid: c,
151 - root: root,
152 - remainder: remainder,
153 - }
154 -}
155 -
156 -func (p *path) String() string {
157 - return p.path.String()
158 -}
159 -
160 -func (p *path) Namespace() string {
161 - if len(p.path.Segments()) < 1 {
162 - panic("path without namespace") //this shouldn't happen under any scenario
163 - }
164 - return p.path.Segments()[0]
165 -}
166 -
167 -func (p *path) Mutable() bool {
168 - //TODO: MFS: check for /local
169 - return p.Namespace() == "ipns"
170 -}
171 -
172 -func (p *resolvedPath) Cid() cid.Cid {
173 - return p.cid
174 -}
175 -
176 -func (p *resolvedPath) Root() cid.Cid {
177 - return p.root
178 -}
179 -
180 -func (p *resolvedPath) Remainder() string {
181 - return p.remainder
182 -}
core/coreapi/interface/pin.go deleted
-54
@@ -1,54 +0,0 @@
1 -package iface
2 -
3 -import (
4 - "context"
5 -
6 - options "github.com/ipfs/go-ipfs/core/coreapi/interface/options"
7 -)
8 -
9 -// Pin holds information about pinned resource
10 -type Pin interface {
11 - // Path to the pinned object
12 - Path() ResolvedPath
13 -
14 - // Type of the pin
15 - Type() string
16 -}
17 -
18 -// PinStatus holds information about pin health
19 -type PinStatus interface {
20 - // Ok indicates whether the pin has been verified to be correct
21 - Ok() bool
22 -
23 - // BadNodes returns any bad (usually missing) nodes from the pin
24 - BadNodes() []BadPinNode
25 -}
26 -
27 -// BadPinNode is a node that has been marked as bad by Pin.Verify
28 -type BadPinNode interface {
29 - // Path is the path of the node
30 - Path() ResolvedPath
31 -
32 - // Err is the reason why the node has been marked as bad
33 - Err() error
34 -}
35 -
36 -// PinAPI specifies the interface to pining
37 -type PinAPI interface {
38 - // Add creates new pin, be default recursive - pinning the whole referenced
39 - // tree
40 - Add(context.Context, Path, ...options.PinAddOption) error
41 -
42 - // Ls returns list of pinned objects on this node
43 - Ls(context.Context, ...options.PinLsOption) ([]Pin, error)
44 -
45 - // Rm removes pin for object specified by the path
46 - Rm(context.Context, Path, ...options.PinRmOption) error
47 -
48 - // Update changes one pin to another, skipping checks for matching paths in
49 - // the old tree
50 - Update(ctx context.Context, from Path, to Path, opts ...options.PinUpdateOption) error
51 -
52 - // Verify verifies the integrity of pinned objects
53 - Verify(context.Context) (<-chan PinStatus, error)
54 -}
core/coreapi/interface/pubsub.go deleted
-48
@@ -1,48 +0,0 @@
1 -package iface
2 -
3 -import (
4 - "context"
5 - "io"
6 -
7 - options "github.com/ipfs/go-ipfs/core/coreapi/interface/options"
8 -
9 - peer "gx/ipfs/QmPJxxDsX2UbchSHobbYuvz7qnyJTFKvaKMzE2rZWJ4x5B/go-libp2p-peer"
10 -)
11 -
12 -// PubSubSubscription is an active PubSub subscription
13 -type PubSubSubscription interface {
14 - io.Closer
15 -
16 - // Next return the next incoming message
17 - Next(context.Context) (PubSubMessage, error)
18 -}
19 -
20 -// PubSubMessage is a single PubSub message
21 -type PubSubMessage interface {
22 - // From returns id of a peer from which the message has arrived
23 - From() peer.ID
24 -
25 - // Data returns the message body
26 - Data() []byte
27 -
28 - // Seq returns message identifier
29 - Seq() []byte
30 -
31 - // Topics returns list of topics this message was set to
32 - Topics() []string
33 -}
34 -
35 -// PubSubAPI specifies the interface to PubSub
36 -type PubSubAPI interface {
37 - // Ls lists subscribed topics by name
38 - Ls(context.Context) ([]string, error)
39 -
40 - // Peers list peers we are currently pubsubbing with
41 - Peers(context.Context, ...options.PubSubPeersOption) ([]peer.ID, error)
42 -
43 - // Publish a message to a given pubsub topic
44 - Publish(context.Context, string, []byte) error
45 -
46 - // Subscribe to messages on a given topic
47 - Subscribe(context.Context, string, ...options.PubSubSubscribeOption) (PubSubSubscription, error)
48 -}
core/coreapi/interface/swarm.go deleted
-57
@@ -1,57 +0,0 @@
1 -package iface
2 -
3 -import (
4 - "context"
5 - "errors"
6 - "time"
7 -
8 - ma "gx/ipfs/QmNTCey11oxhb1AxDnQBRHtdhap6Ctud872NjAYPYYXPuc/go-multiaddr"
9 - "gx/ipfs/QmPJxxDsX2UbchSHobbYuvz7qnyJTFKvaKMzE2rZWJ4x5B/go-libp2p-peer"
10 - pstore "gx/ipfs/QmQFFp4ntkd4C14sP3FaH9WJyBuetuGUVo6dShNHvnoEvC/go-libp2p-peerstore"
11 - net "gx/ipfs/QmZ7cBWUXkyWTMN4qH6NGoyMVs7JugyFChBNP4ZUp5rJHH/go-libp2p-net"
12 - "gx/ipfs/QmZNkThpqfVXs9GNbexPrfBbXSLNYeKrE7jwFM2oqHbyqN/go-libp2p-protocol"
13 -)
14 -
15 -var (
16 - ErrNotConnected = errors.New("not connected")
17 - ErrConnNotFound = errors.New("conn not found")
18 -)
19 -
20 -// ConnectionInfo contains information about a peer
21 -type ConnectionInfo interface {
22 - // ID returns PeerID
23 - ID() peer.ID
24 -
25 - // Address returns the multiaddress via which we are connected with the peer
26 - Address() ma.Multiaddr
27 -
28 - // Direction returns which way the connection was established
29 - Direction() net.Direction
30 -
31 - // Latency returns last known round trip time to the peer
32 - Latency() (time.Duration, error)
33 -
34 - // Streams returns list of streams established with the peer
35 - Streams() ([]protocol.ID, error)
36 -}
37 -
38 -// SwarmAPI specifies the interface to libp2p swarm
39 -type SwarmAPI interface {
40 - // Connect to a given peer
41 - Connect(context.Context, pstore.PeerInfo) error
42 -
43 - // Disconnect from a given address
44 - Disconnect(context.Context, ma.Multiaddr) error
45 -
46 - // Peers returns the list of peers we are connected to
47 - Peers(context.Context) ([]ConnectionInfo, error)
48 -
49 - // KnownAddrs returns the list of all addresses this node is aware of
50 - KnownAddrs(context.Context) (map[peer.ID][]ma.Multiaddr, error)
51 -
52 - // LocalAddrs returns the list of announced listening addresses
53 - LocalAddrs(context.Context) ([]ma.Multiaddr, error)
54 -
55 - // ListenAddrs returns the list of all listening addresses
56 - ListenAddrs(context.Context) ([]ma.Multiaddr, error)
57 -}
core/coreapi/interface/tests/api.go deleted
-94
@@ -1,94 +0,0 @@
1 -package tests
2 -
3 -import (
4 - "context"
5 - "errors"
6 - "testing"
7 - "time"
8 -
9 - coreiface "github.com/ipfs/go-ipfs/core/coreapi/interface"
10 -)
11 -
12 -var apiNotImplemented = errors.New("api not implemented")
13 -
14 -func (tp *provider) makeAPI(ctx context.Context) (coreiface.CoreAPI, error) {
15 - api, err := tp.MakeAPISwarm(ctx, false, 1)
16 - if err != nil {
17 - return nil, err
18 - }
19 -
20 - return api[0], nil
21 -}
22 -
23 -type Provider interface {
24 - // Make creates n nodes. fullIdentity set to false can be ignored
25 - MakeAPISwarm(ctx context.Context, fullIdentity bool, n int) ([]coreiface.CoreAPI, error)
26 -}
27 -
28 -func (tp *provider) MakeAPISwarm(ctx context.Context, fullIdentity bool, n int) ([]coreiface.CoreAPI, error) {
29 - tp.apis <- 1
30 - go func() {
31 - <-ctx.Done()
32 - tp.apis <- -1
33 - }()
34 -
35 - return tp.Provider.MakeAPISwarm(ctx, fullIdentity, n)
36 -}
37 -
38 -type provider struct {
39 - Provider
40 -
41 - apis chan int
42 -}
43 -
44 -func TestApi(p Provider) func(t *testing.T) {
45 - running := 1
46 - apis := make(chan int)
47 - zeroRunning := make(chan struct{})
48 - go func() {
49 - for i := range apis {
50 - running += i
51 - if running < 1 {
52 - close(zeroRunning)
53 - return
54 - }
55 - }
56 - }()
57 -
58 - tp := &provider{Provider: p, apis: apis}
59 -
60 - return func(t *testing.T) {
61 - t.Run("Block", tp.TestBlock)
62 - t.Run("Dag", tp.TestDag)
63 - t.Run("Dht", tp.TestDht)
64 - t.Run("Key", tp.TestKey)
65 - t.Run("Name", tp.TestName)
66 - t.Run("Object", tp.TestObject)
67 - t.Run("Path", tp.TestPath)
68 - t.Run("Pin", tp.TestPin)
69 - t.Run("PubSub", tp.TestPubSub)
70 - t.Run("Unixfs", tp.TestUnixfs)
71 -
72 - apis <- -1
73 - t.Run("TestsCancelCtx", func(t *testing.T) {
74 - select {
75 - case <-zeroRunning:
76 - case <-time.After(time.Second):
77 - t.Errorf("%d test swarms(s) not closed", running)
78 - }
79 - })
80 - }
81 -}
82 -
83 -func (tp *provider) hasApi(t *testing.T, tf func(coreiface.CoreAPI) error) {
84 - ctx, cancel := context.WithCancel(context.Background())
85 - defer cancel()
86 - api, err := tp.makeAPI(ctx)
87 - if err != nil {
88 - t.Fatal(err)
89 - }
90 -
91 - if err := tf(api); err != nil {
92 - t.Fatal(api)
93 - }
94 -}
core/coreapi/interface/tests/block.go deleted
-243
@@ -1,243 +0,0 @@
1 -package tests
2 -
3 -import (
4 - "context"
5 - "io/ioutil"
6 - "strings"
7 - "testing"
8 -
9 - coreiface "github.com/ipfs/go-ipfs/core/coreapi/interface"
10 - opt "github.com/ipfs/go-ipfs/core/coreapi/interface/options"
11 -
12 - mh "gx/ipfs/QmerPMzPk1mJVowm8KgmoknWa4yCYvvugMPsgWmDNUvDLW/go-multihash"
13 -)
14 -
15 -func (tp *provider) TestBlock(t *testing.T) {
16 - tp.hasApi(t, func(api coreiface.CoreAPI) error {
17 - if api.Block() == nil {
18 - return apiNotImplemented
19 - }
20 - return nil
21 - })
22 -
23 - t.Run("TestBlockPut", tp.TestBlockPut)
24 - t.Run("TestBlockPutFormat", tp.TestBlockPutFormat)
25 - t.Run("TestBlockPutHash", tp.TestBlockPutHash)
26 - t.Run("TestBlockGet", tp.TestBlockGet)
27 - t.Run("TestBlockRm", tp.TestBlockRm)
28 - t.Run("TestBlockStat", tp.TestBlockStat)
29 - t.Run("TestBlockPin", tp.TestBlockPin)
30 -}
31 -
32 -func (tp *provider) TestBlockPut(t *testing.T) {
33 - ctx, cancel := context.WithCancel(context.Background())
34 - defer cancel()
35 - api, err := tp.makeAPI(ctx)
36 - if err != nil {
37 - t.Fatal(err)
38 - }
39 -
40 - res, err := api.Block().Put(ctx, strings.NewReader(`Hello`))
41 - if err != nil {
42 - t.Fatal(err)
43 - }
44 -
45 - if res.Path().Cid().String() != "QmPyo15ynbVrSTVdJL9th7JysHaAbXt9dM9tXk1bMHbRtk" {
46 - t.Errorf("got wrong cid: %s", res.Path().Cid().String())
47 - }
48 -}
49 -
50 -func (tp *provider) TestBlockPutFormat(t *testing.T) {
51 - ctx, cancel := context.WithCancel(context.Background())
52 - defer cancel()
53 - api, err := tp.makeAPI(ctx)
54 - if err != nil {
55 - t.Error(err)
56 - }
57 -
58 - res, err := api.Block().Put(ctx, strings.NewReader(`Hello`), opt.Block.Format("cbor"))
59 - if err != nil {
60 - t.Fatal(err)
61 - }
62 -
63 - if res.Path().Cid().String() != "zdpuAn4amuLWo8Widi5v6VQpuo2dnpnwbVE3oB6qqs7mDSeoa" {
64 - t.Errorf("got wrong cid: %s", res.Path().Cid().String())
65 - }
66 -}
67 -
68 -func (tp *provider) TestBlockPutHash(t *testing.T) {
69 - ctx, cancel := context.WithCancel(context.Background())
70 - defer cancel()
71 - api, err := tp.makeAPI(ctx)
72 - if err != nil {
73 - t.Error(err)
74 - }
75 -
76 - res, err := api.Block().Put(ctx, strings.NewReader(`Hello`), opt.Block.Hash(mh.KECCAK_512, -1))
77 - if err != nil {
78 - t.Fatal(err)
79 - }
80 -
81 - if res.Path().Cid().String() != "zBurKB9YZkcDf6xa53WBE8CFX4ydVqAyf9KPXBFZt5stJzEstaS8Hukkhu4gwpMtc1xHNDbzP7sPtQKyWsP3C8fbhkmrZ" {
82 - t.Errorf("got wrong cid: %s", res.Path().Cid().String())
83 - }
84 -}
85 -
86 -func (tp *provider) TestBlockGet(t *testing.T) {
87 - ctx, cancel := context.WithCancel(context.Background())
88 - defer cancel()
89 - api, err := tp.makeAPI(ctx)
90 - if err != nil {
91 - t.Error(err)
92 - }
93 -
94 - res, err := api.Block().Put(ctx, strings.NewReader(`Hello`), opt.Block.Hash(mh.KECCAK_512, -1))
95 - if err != nil {
96 - t.Fatal(err)
97 - }
98 -
99 - r, err := api.Block().Get(ctx, res.Path())
100 - if err != nil {
101 - t.Error(err)
102 - }
103 -
104 - d, err := ioutil.ReadAll(r)
105 - if err != nil {
106 - t.Error(err)
107 - }
108 -
109 - if string(d) != "Hello" {
110 - t.Error("didn't get correct data back")
111 - }
112 -
113 - p, err := coreiface.ParsePath("/ipfs/" + res.Path().Cid().String())
114 - if err != nil {
115 - t.Error(err)
116 - }
117 -
118 - rp, err := api.ResolvePath(ctx, p)
119 - if err != nil {
120 - t.Fatal(err)
121 - }
122 - if rp.Cid().String() != res.Path().Cid().String() {
123 - t.Error("paths didn't match")
124 - }
125 -}
126 -
127 -func (tp *provider) TestBlockRm(t *testing.T) {
128 - ctx, cancel := context.WithCancel(context.Background())
129 - defer cancel()
130 - api, err := tp.makeAPI(ctx)
131 - if err != nil {
132 - t.Error(err)
133 - }
134 -
135 - res, err := api.Block().Put(ctx, strings.NewReader(`Hello`))
136 - if err != nil {
137 - t.Fatal(err)
138 - }
139 -
140 - r, err := api.Block().Get(ctx, res.Path())
141 - if err != nil {
142 - t.Error(err)
143 - }
144 -
145 - d, err := ioutil.ReadAll(r)
146 - if err != nil {
147 - t.Error(err)
148 - }
149 -
150 - if string(d) != "Hello" {
151 - t.Error("didn't get correct data back")
152 - }
153 -
154 - err = api.Block().Rm(ctx, res.Path())
155 - if err != nil {
156 - t.Error(err)
157 - }
158 -
159 - _, err = api.Block().Get(ctx, res.Path())
160 - if err == nil {
161 - t.Error("expected err to exist")
162 - }
163 - if !strings.Contains(err.Error(), "blockservice: key not found") {
164 - t.Errorf("unexpected error; %s", err.Error())
165 - }
166 -
167 - err = api.Block().Rm(ctx, res.Path())
168 - if err == nil {
169 - t.Error("expected err to exist")
170 - }
171 - if !strings.Contains(err.Error(), "blockstore: block not found") {
172 - t.Errorf("unexpected error; %s", err.Error())
173 - }
174 -
175 - err = api.Block().Rm(ctx, res.Path(), opt.Block.Force(true))
176 - if err != nil {
177 - t.Error(err)
178 - }
179 -}
180 -
181 -func (tp *provider) TestBlockStat(t *testing.T) {
182 - ctx, cancel := context.WithCancel(context.Background())
183 - defer cancel()
184 - api, err := tp.makeAPI(ctx)
185 - if err != nil {
186 - t.Error(err)
187 - }
188 -
189 - res, err := api.Block().Put(ctx, strings.NewReader(`Hello`))
190 - if err != nil {
191 - t.Fatal(err)
192 - }
193 -
194 - stat, err := api.Block().Stat(ctx, res.Path())
195 - if err != nil {
196 - t.Error(err)
197 - }
198 -
199 - if stat.Path().String() != res.Path().String() {
200 - t.Error("paths don't match")
201 - }
202 -
203 - if stat.Size() != len("Hello") {
204 - t.Error("length doesn't match")
205 - }
206 -}
207 -
208 -func (tp *provider) TestBlockPin(t *testing.T) {
209 - ctx, cancel := context.WithCancel(context.Background())
210 - defer cancel()
211 - api, err := tp.makeAPI(ctx)
212 - if err != nil {
213 - t.Error(err)
214 - }
215 -
216 - _, err = api.Block().Put(ctx, strings.NewReader(`Hello`))
217 - if err != nil {
218 - t.Fatal(err)
219 - }
220 -
221 - if pins, err := api.Pin().Ls(ctx); err != nil || len(pins) != 0 {
222 - t.Fatal("expected 0 pins")
223 - }
224 -
225 - res, err := api.Block().Put(ctx, strings.NewReader(`Hello`), opt.Block.Pin(true))
226 - if err != nil {
227 - t.Fatal(err)
228 - }
229 -
230 - pins, err := api.Pin().Ls(ctx)
231 - if err != nil {
232 - return
233 - }
234 - if len(pins) != 1 {
235 - t.Fatal("expected 1 pin")
236 - }
237 - if pins[0].Type() != "recursive" {
238 - t.Error("expected a recursive pin")
239 - }
240 - if pins[0].Path().String() != res.Path().String() {
241 - t.Error("pin path didn't match")
242 - }
243 -}
core/coreapi/interface/tests/dag.go deleted
-201
@@ -1,201 +0,0 @@
1 -package tests
2 -
3 -import (
4 - "context"
5 - "math"
6 - "path"
7 - "strings"
8 - "testing"
9 -
10 - coreiface "github.com/ipfs/go-ipfs/core/coreapi/interface"
11 -
12 - ipld "gx/ipfs/QmRL22E4paat7ky7vx9MLpR97JHHbFPrg3ytFQw6qp1y1s/go-ipld-format"
13 - ipldcbor "gx/ipfs/QmRZxJ7oybgnnwriuRub9JXp5YdFM9wiGSyRq38QC7swpS/go-ipld-cbor"
14 - mh "gx/ipfs/QmerPMzPk1mJVowm8KgmoknWa4yCYvvugMPsgWmDNUvDLW/go-multihash"
15 -)
16 -
17 -func (tp *provider) TestDag(t *testing.T) {
18 - tp.hasApi(t, func(api coreiface.CoreAPI) error {
19 - if api.Dag() == nil {
20 - return apiNotImplemented
21 - }
22 - return nil
23 - })
24 -
25 - t.Run("TestPut", tp.TestPut)
26 - t.Run("TestPutWithHash", tp.TestPutWithHash)
27 - t.Run("TestPath", tp.TestDagPath)
28 - t.Run("TestTree", tp.TestTree)
29 - t.Run("TestBatch", tp.TestBatch)
30 -}
31 -
32 -var (
33 - treeExpected = map[string]struct{}{
34 - "a": {},
35 - "b": {},
36 - "c": {},
37 - "c/d": {},
38 - "c/e": {},
39 - }
40 -)
41 -
42 -func (tp *provider) TestPut(t *testing.T) {
43 - ctx, cancel := context.WithCancel(context.Background())
44 - defer cancel()
45 - api, err := tp.makeAPI(ctx)
46 - if err != nil {
47 - t.Error(err)
48 - }
49 -
50 - nd, err := ipldcbor.FromJSON(strings.NewReader(`"Hello"`), math.MaxUint64, -1)
51 - if err != nil {
52 - t.Error(err)
53 - }
54 -
55 - err = api.Dag().Add(ctx, nd)
56 - if err != nil {
57 - t.Fatal(err)
58 - }
59 -
60 - if nd.Cid().String() != "zdpuAqckYF3ToF3gcJNxPZXmnmGuXd3gxHCXhq81HGxBejEvv" {
61 - t.Errorf("got wrong cid: %s", nd.Cid().String())
62 - }
63 -}
64 -
65 -func (tp *provider) TestPutWithHash(t *testing.T) {
66 - ctx, cancel := context.WithCancel(context.Background())
67 - defer cancel()
68 - api, err := tp.makeAPI(ctx)
69 - if err != nil {
70 - t.Error(err)
71 - }
72 -
73 - nd, err := ipldcbor.FromJSON(strings.NewReader(`"Hello"`), mh.ID, -1)
74 - if err != nil {
75 - t.Error(err)
76 - }
77 -
78 - err = api.Dag().Add(ctx, nd)
79 - if err != nil {
80 - t.Fatal(err)
81 - }
82 -
83 - if nd.Cid().String() != "z5hRLNd2sv4z1c" {
84 - t.Errorf("got wrong cid: %s", nd.Cid().String())
85 - }
86 -}
87 -
88 -func (tp *provider) TestDagPath(t *testing.T) {
89 - ctx, cancel := context.WithCancel(context.Background())
90 - defer cancel()
91 - api, err := tp.makeAPI(ctx)
92 - if err != nil {
93 - t.Error(err)
94 - }
95 -
96 - snd, err := ipldcbor.FromJSON(strings.NewReader(`"foo"`), math.MaxUint64, -1)
97 - if err != nil {
98 - t.Error(err)
99 - }
100 -
101 - err = api.Dag().Add(ctx, snd)
102 - if err != nil {
103 - t.Fatal(err)
104 - }
105 -
106 - nd, err := ipldcbor.FromJSON(strings.NewReader(`{"lnk": {"/": "`+snd.Cid().String()+`"}}`), math.MaxUint64, -1)
107 - if err != nil {
108 - t.Error(err)
109 - }
110 -
111 - err = api.Dag().Add(ctx, nd)
112 - if err != nil {
113 - t.Fatal(err)
114 - }
115 -
116 - p, err := coreiface.ParsePath(path.Join(nd.Cid().String(), "lnk"))
117 - if err != nil {
118 - t.Error(err)
119 - }
120 -
121 - rp, err := api.ResolvePath(ctx, p)
122 - if err != nil {
123 - t.Error(err)
124 - }
125 -
126 - ndd, err := api.Dag().Get(ctx, rp.Cid())
127 - if err != nil {
128 - t.Error(err)
129 - }
130 -
131 - if ndd.Cid().String() != snd.Cid().String() {
132 - t.Errorf("got unexpected cid %s, expected %s", ndd.Cid().String(), snd.Cid().String())
133 - }
134 -}
135 -
136 -func (tp *provider) TestTree(t *testing.T) {
137 - ctx, cancel := context.WithCancel(context.Background())
138 - defer cancel()
139 - api, err := tp.makeAPI(ctx)
140 - if err != nil {
141 - t.Error(err)
142 - }
143 -
144 - nd, err := ipldcbor.FromJSON(strings.NewReader(`{"a": 123, "b": "foo", "c": {"d": 321, "e": 111}}`), math.MaxUint64, -1)
145 - if err != nil {
146 - t.Error(err)
147 - }
148 -
149 - err = api.Dag().Add(ctx, nd)
150 - if err != nil {
151 - t.Fatal(err)
152 - }
153 -
154 - res, err := api.Dag().Get(ctx, nd.Cid())
155 - if err != nil {
156 - t.Error(err)
157 - }
158 -
159 - lst := res.Tree("", -1)
160 - if len(lst) != len(treeExpected) {
161 - t.Errorf("tree length of %d doesn't match expected %d", len(lst), len(treeExpected))
162 - }
163 -
164 - for _, ent := range lst {
165 - if _, ok := treeExpected[ent]; !ok {
166 - t.Errorf("unexpected tree entry %s", ent)
167 - }
168 - }
169 -}
170 -
171 -func (tp *provider) TestBatch(t *testing.T) {
172 - ctx, cancel := context.WithCancel(context.Background())
173 - defer cancel()
174 - api, err := tp.makeAPI(ctx)
175 - if err != nil {
176 - t.Error(err)
177 - }
178 -
179 - nd, err := ipldcbor.FromJSON(strings.NewReader(`"Hello"`), math.MaxUint64, -1)
180 - if err != nil {
181 - t.Error(err)
182 - }
183 -
184 - if nd.Cid().String() != "zdpuAqckYF3ToF3gcJNxPZXmnmGuXd3gxHCXhq81HGxBejEvv" {
185 - t.Errorf("got wrong cid: %s", nd.Cid().String())
186 - }
187 -
188 - _, err = api.Dag().Get(ctx, nd.Cid())
189 - if err == nil || !strings.Contains(err.Error(), "not found") {
190 - t.Error(err)
191 - }
192 -
193 - if err := api.Dag().AddMany(ctx, []ipld.Node{nd}); err != nil {
194 - t.Error(err)
195 - }
196 -
197 - _, err = api.Dag().Get(ctx, nd.Cid())
198 - if err != nil {
199 - t.Error(err)
200 - }
201 -}
core/coreapi/interface/tests/dht.go deleted
-159
@@ -1,159 +0,0 @@
1 -package tests
2 -
3 -import (
4 - "context"
5 - "io"
6 - "testing"
7 -
8 - "github.com/ipfs/go-ipfs/core/coreapi/interface"
9 - "github.com/ipfs/go-ipfs/core/coreapi/interface/options"
10 -)
11 -
12 -func (tp *provider) TestDht(t *testing.T) {
13 - tp.hasApi(t, func(api iface.CoreAPI) error {
14 - if api.Dht() == nil {
15 - return apiNotImplemented
16 - }
17 - return nil
18 - })
19 -
20 - t.Run("TestDhtFindPeer", tp.TestDhtFindPeer)
21 - t.Run("TestDhtFindProviders", tp.TestDhtFindProviders)
22 - t.Run("TestDhtProvide", tp.TestDhtProvide)
23 -}
24 -
25 -func (tp *provider) TestDhtFindPeer(t *testing.T) {
26 - ctx, cancel := context.WithCancel(context.Background())
27 - defer cancel()
28 - apis, err := tp.MakeAPISwarm(ctx, true, 5)
29 - if err != nil {
30 - t.Fatal(err)
31 - }
32 -
33 - self0, err := apis[0].Key().Self(ctx)
34 - if err != nil {
35 - t.Fatal(err)
36 - }
37 -
38 - laddrs0, err := apis[0].Swarm().LocalAddrs(ctx)
39 - if err != nil {
40 - t.Fatal(err)
41 - }
42 - if len(laddrs0) != 1 {
43 - t.Fatal("unexpected number of local addrs")
44 - }
45 -
46 - pi, err := apis[2].Dht().FindPeer(ctx, self0.ID())
47 - if err != nil {
48 - t.Fatal(err)
49 - }
50 -
51 - if pi.Addrs[0].String() != laddrs0[0].String() {
52 - t.Errorf("got unexpected address from FindPeer: %s", pi.Addrs[0].String())
53 - }
54 -
55 - self2, err := apis[2].Key().Self(ctx)
56 - if err != nil {
57 - t.Fatal(err)
58 - }
59 -
60 - pi, err = apis[1].Dht().FindPeer(ctx, self2.ID())
61 - if err != nil {
62 - t.Fatal(err)
63 - }
64 -
65 - laddrs2, err := apis[2].Swarm().LocalAddrs(ctx)
66 - if err != nil {
67 - t.Fatal(err)
68 - }
69 - if len(laddrs2) != 1 {
70 - t.Fatal("unexpected number of local addrs")
71 - }
72 -
73 - if pi.Addrs[0].String() != laddrs2[0].String() {
74 - t.Errorf("got unexpected address from FindPeer: %s", pi.Addrs[0].String())
75 - }
76 -}
77 -
78 -func (tp *provider) TestDhtFindProviders(t *testing.T) {
79 - ctx, cancel := context.WithCancel(context.Background())
80 - defer cancel()
81 - apis, err := tp.MakeAPISwarm(ctx, true, 5)
82 - if err != nil {
83 - t.Fatal(err)
84 - }
85 -
86 - p, err := addTestObject(ctx, apis[0])
87 - if err != nil {
88 - t.Fatal(err)
89 - }
90 -
91 - out, err := apis[2].Dht().FindProviders(ctx, p, options.Dht.NumProviders(1))
92 - if err != nil {
93 - t.Fatal(err)
94 - }
95 -
96 - provider := <-out
97 -
98 - self0, err := apis[0].Key().Self(ctx)
99 - if err != nil {
100 - t.Fatal(err)
101 - }
102 -
103 - if provider.ID.String() != self0.ID().String() {
104 - t.Errorf("got wrong provider: %s != %s", provider.ID.String(), self0.ID().String())
105 - }
106 -}
107 -
108 -func (tp *provider) TestDhtProvide(t *testing.T) {
109 - ctx, cancel := context.WithCancel(context.Background())
110 - defer cancel()
111 - apis, err := tp.MakeAPISwarm(ctx, true, 5)
112 - if err != nil {
113 - t.Fatal(err)
114 - }
115 -
116 - off0, err := apis[0].WithOptions(options.Api.Offline(true))
117 - if err != nil {
118 - t.Fatal(err)
119 - }
120 -
121 - s, err := off0.Block().Put(ctx, &io.LimitedReader{R: rnd, N: 4092})
122 - if err != nil {
123 - t.Fatal(err)
124 - }
125 -
126 - p := s.Path()
127 -
128 - out, err := apis[2].Dht().FindProviders(ctx, p, options.Dht.NumProviders(1))
129 - if err != nil {
130 - t.Fatal(err)
131 - }
132 -
133 - provider := <-out
134 -
135 - self0, err := apis[0].Key().Self(ctx)
136 - if err != nil {
137 - t.Fatal(err)
138 - }
139 -
140 - if provider.ID.String() != "<peer.ID >" {
141 - t.Errorf("got wrong provider: %s != %s", provider.ID.String(), self0.ID().String())
142 - }
143 -
144 - err = apis[0].Dht().Provide(ctx, p)
145 - if err != nil {
146 - t.Fatal(err)
147 - }
148 -
149 - out, err = apis[2].Dht().FindProviders(ctx, p, options.Dht.NumProviders(1))
150 - if err != nil {
151 - t.Fatal(err)
152 - }
153 -
154 - provider = <-out
155 -
156 - if provider.ID.String() != self0.ID().String() {
157 - t.Errorf("got wrong provider: %s != %s", provider.ID.String(), self0.ID().String())
158 - }
159 -}
core/coreapi/interface/tests/key.go deleted
-523
@@ -1,523 +0,0 @@
1 -package tests
2 -
3 -import (
4 - "context"
5 - "strings"
6 - "testing"
7 -
8 - "github.com/ipfs/go-ipfs/core/coreapi/interface"
9 - opt "github.com/ipfs/go-ipfs/core/coreapi/interface/options"
10 -)
11 -
12 -func (tp *provider) TestKey(t *testing.T) {
13 - tp.hasApi(t, func(api iface.CoreAPI) error {
14 - if api.Key() == nil {
15 - return apiNotImplemented
16 - }
17 - return nil
18 - })
19 -
20 - t.Run("TestListSelf", tp.TestListSelf)
21 - t.Run("TestRenameSelf", tp.TestRenameSelf)
22 - t.Run("TestRemoveSelf", tp.TestRemoveSelf)
23 - t.Run("TestGenerate", tp.TestGenerate)
24 - t.Run("TestGenerateSize", tp.TestGenerateSize)
25 - t.Run("TestGenerateType", tp.TestGenerateType)
26 - t.Run("TestGenerateExisting", tp.TestGenerateExisting)
27 - t.Run("TestList", tp.TestList)
28 - t.Run("TestRename", tp.TestRename)
29 - t.Run("TestRenameToSelf", tp.TestRenameToSelf)
30 - t.Run("TestRenameToSelfForce", tp.TestRenameToSelfForce)
31 - t.Run("TestRenameOverwriteNoForce", tp.TestRenameOverwriteNoForce)
32 - t.Run("TestRenameOverwrite", tp.TestRenameOverwrite)
33 - t.Run("TestRenameSameNameNoForce", tp.TestRenameSameNameNoForce)
34 - t.Run("TestRenameSameName", tp.TestRenameSameName)
35 - t.Run("TestRemove", tp.TestRemove)
36 -}
37 -
38 -func (tp *provider) TestListSelf(t *testing.T) {
39 - ctx, cancel := context.WithCancel(context.Background())
40 - defer cancel()
41 - api, err := tp.makeAPI(ctx)
42 - if err != nil {
43 - t.Fatal(err)
44 - return
45 - }
46 -
47 - self, err := api.Key().Self(ctx)
48 - if err != nil {
49 - t.Fatal(err)
50 - }
51 -
52 - keys, err := api.Key().List(ctx)
53 - if err != nil {
54 - t.Fatalf("failed to list keys: %s", err)
55 - return
56 - }
57 -
58 - if len(keys) != 1 {
59 - t.Fatalf("there should be 1 key (self), got %d", len(keys))
60 - return
61 - }
62 -
63 - if keys[0].Name() != "self" {
64 - t.Errorf("expected the key to be called 'self', got '%s'", keys[0].Name())
65 - }
66 -
67 - if keys[0].Path().String() != "/ipns/"+self.ID().Pretty() {
68 - t.Errorf("expected the key to have path '/ipns/%s', got '%s'", self.ID().Pretty(), keys[0].Path().String())
69 - }
70 -}
71 -
72 -func (tp *provider) TestRenameSelf(t *testing.T) {
73 - ctx, cancel := context.WithCancel(context.Background())
74 - defer cancel()
75 - api, err := tp.makeAPI(ctx)
76 - if err != nil {
77 - t.Fatal(err)
78 - return
79 - }
80 -
81 - _, _, err = api.Key().Rename(ctx, "self", "foo")
82 - if err == nil {
83 - t.Error("expected error to not be nil")
84 - } else {
85 - if !strings.Contains(err.Error(), "cannot rename key with name 'self'") {
86 - t.Fatalf("expected error 'cannot rename key with name 'self'', got '%s'", err.Error())
87 - }
88 - }
89 -
90 - _, _, err = api.Key().Rename(ctx, "self", "foo", opt.Key.Force(true))
91 - if err == nil {
92 - t.Error("expected error to not be nil")
93 - } else {
94 - if !strings.Contains(err.Error(), "cannot rename key with name 'self'") {
95 - t.Fatalf("expected error 'cannot rename key with name 'self'', got '%s'", err.Error())
96 - }
97 - }
98 -}
99 -
100 -func (tp *provider) TestRemoveSelf(t *testing.T) {
101 - ctx, cancel := context.WithCancel(context.Background())
102 - defer cancel()
103 - api, err := tp.makeAPI(ctx)
104 - if err != nil {
105 - t.Fatal(err)
106 - return
107 - }
108 -
109 - _, err = api.Key().Remove(ctx, "self")
110 - if err == nil {
111 - t.Error("expected error to not be nil")
112 - } else {
113 - if !strings.Contains(err.Error(), "cannot remove key with name 'self'") {
114 - t.Fatalf("expected error 'cannot remove key with name 'self'', got '%s'", err.Error())
115 - }
116 - }
117 -}
118 -
119 -func (tp *provider) TestGenerate(t *testing.T) {
120 - ctx, cancel := context.WithCancel(context.Background())
121 - defer cancel()
122 - api, err := tp.makeAPI(ctx)
123 - if err != nil {
124 - t.Error(err)
125 - }
126 -
127 - k, err := api.Key().Generate(ctx, "foo")
128 - if err != nil {
129 - t.Fatal(err)
130 - return
131 - }
132 -
133 - if k.Name() != "foo" {
134 - t.Errorf("expected the key to be called 'foo', got '%s'", k.Name())
135 - }
136 -
137 - if !strings.HasPrefix(k.Path().String(), "/ipns/Qm") {
138 - t.Errorf("expected the key to be prefixed with '/ipns/Qm', got '%s'", k.Path().String())
139 - }
140 -}
141 -
142 -func (tp *provider) TestGenerateSize(t *testing.T) {
143 - ctx, cancel := context.WithCancel(context.Background())
144 - defer cancel()
145 - api, err := tp.makeAPI(ctx)
146 - if err != nil {
147 - t.Error(err)
148 - }
149 -
150 - k, err := api.Key().Generate(ctx, "foo", opt.Key.Size(1024))
151 - if err != nil {
152 - t.Fatal(err)
153 - return
154 - }
155 -
156 - if k.Name() != "foo" {
157 - t.Errorf("expected the key to be called 'foo', got '%s'", k.Name())
158 - }
159 -
160 - if !strings.HasPrefix(k.Path().String(), "/ipns/Qm") {
161 - t.Errorf("expected the key to be prefixed with '/ipns/Qm', got '%s'", k.Path().String())
162 - }
163 -}
164 -
165 -func (tp *provider) TestGenerateType(t *testing.T) {
166 - ctx, cancel := context.WithCancel(context.Background())
167 - defer cancel()
168 - t.Skip("disabled until libp2p/specs#111 is fixed")
169 -
170 - api, err := tp.makeAPI(ctx)
171 - if err != nil {
172 - t.Error(err)
173 - }
174 -
175 - k, err := api.Key().Generate(ctx, "bar", opt.Key.Type(opt.Ed25519Key))
176 - if err != nil {
177 - t.Fatal(err)
178 - return
179 - }
180 -
181 - if k.Name() != "bar" {
182 - t.Errorf("expected the key to be called 'foo', got '%s'", k.Name())
183 - }
184 -
185 - // Expected to be an inlined identity hash.
186 - if !strings.HasPrefix(k.Path().String(), "/ipns/12") {
187 - t.Errorf("expected the key to be prefixed with '/ipns/12', got '%s'", k.Path().String())
188 - }
189 -}
190 -
191 -func (tp *provider) TestGenerateExisting(t *testing.T) {
192 - ctx, cancel := context.WithCancel(context.Background())
193 - defer cancel()
194 - api, err := tp.makeAPI(ctx)
195 - if err != nil {
196 - t.Error(err)
197 - }
198 -
199 - _, err = api.Key().Generate(ctx, "foo")
200 - if err != nil {
201 - t.Fatal(err)
202 - return
203 - }
204 -
205 - _, err = api.Key().Generate(ctx, "foo")
206 - if err == nil {
207 - t.Error("expected error to not be nil")
208 - } else {
209 - if !strings.Contains(err.Error(), "key with name 'foo' already exists") {
210 - t.Fatalf("expected error 'key with name 'foo' already exists', got '%s'", err.Error())
211 - }
212 - }
213 -
214 - _, err = api.Key().Generate(ctx, "self")
215 - if err == nil {
216 - t.Error("expected error to not be nil")
217 - } else {
218 - if !strings.Contains(err.Error(), "cannot create key with name 'self'") {
219 - t.Fatalf("expected error 'cannot create key with name 'self'', got '%s'", err.Error())
220 - }
221 - }
222 -}
223 -
224 -func (tp *provider) TestList(t *testing.T) {
225 - ctx, cancel := context.WithCancel(context.Background())
226 - defer cancel()
227 - api, err := tp.makeAPI(ctx)
228 - if err != nil {
229 - t.Error(err)
230 - }
231 -
232 - _, err = api.Key().Generate(ctx, "foo")
233 - if err != nil {
234 - t.Fatal(err)
235 - return
236 - }
237 -
238 - l, err := api.Key().List(ctx)
239 - if err != nil {
240 - t.Fatal(err)
241 - return
242 - }
243 -
244 - if len(l) != 2 {
245 - t.Fatalf("expected to get 2 keys, got %d", len(l))
246 - return
247 - }
248 -
249 - if l[0].Name() != "self" {
250 - t.Fatalf("expected key 0 to be called 'self', got '%s'", l[0].Name())
251 - return
252 - }
253 -
254 - if l[1].Name() != "foo" {
255 - t.Fatalf("expected key 1 to be called 'foo', got '%s'", l[1].Name())
256 - return
257 - }
258 -
259 - if !strings.HasPrefix(l[0].Path().String(), "/ipns/Qm") {
260 - t.Fatalf("expected key 0 to be prefixed with '/ipns/Qm', got '%s'", l[0].Name())
261 - return
262 - }
263 -
264 - if !strings.HasPrefix(l[1].Path().String(), "/ipns/Qm") {
265 - t.Fatalf("expected key 1 to be prefixed with '/ipns/Qm', got '%s'", l[1].Name())
266 - return
267 - }
268 -}
269 -
270 -func (tp *provider) TestRename(t *testing.T) {
271 - ctx, cancel := context.WithCancel(context.Background())
272 - defer cancel()
273 - api, err := tp.makeAPI(ctx)
274 - if err != nil {
275 - t.Error(err)
276 - }
277 -
278 - _, err = api.Key().Generate(ctx, "foo")
279 - if err != nil {
280 - t.Fatal(err)
281 - return
282 - }
283 -
284 - k, overwrote, err := api.Key().Rename(ctx, "foo", "bar")
285 - if err != nil {
286 - t.Fatal(err)
287 - return
288 - }
289 -
290 - if overwrote {
291 - t.Error("overwrote should be false")
292 - }
293 -
294 - if k.Name() != "bar" {
295 - t.Errorf("returned key should be called 'bar', got '%s'", k.Name())
296 - }
297 -}
298 -
299 -func (tp *provider) TestRenameToSelf(t *testing.T) {
300 - ctx, cancel := context.WithCancel(context.Background())
301 - defer cancel()
302 - api, err := tp.makeAPI(ctx)
303 - if err != nil {
304 - t.Error(err)
305 - }
306 -
307 - _, err = api.Key().Generate(ctx, "foo")
308 - if err != nil {
309 - t.Fatal(err)
310 - return
311 - }
312 -
313 - _, _, err = api.Key().Rename(ctx, "foo", "self")
314 - if err == nil {
315 - t.Error("expected error to not be nil")
316 - } else {
317 - if !strings.Contains(err.Error(), "cannot overwrite key with name 'self'") {
318 - t.Fatalf("expected error 'cannot overwrite key with name 'self'', got '%s'", err.Error())
319 - }
320 - }
321 -}
322 -
323 -func (tp *provider) TestRenameToSelfForce(t *testing.T) {
324 - ctx, cancel := context.WithCancel(context.Background())
325 - defer cancel()
326 - api, err := tp.makeAPI(ctx)
327 - if err != nil {
328 - t.Error(err)
329 - }
330 -
331 - _, err = api.Key().Generate(ctx, "foo")
332 - if err != nil {
333 - t.Fatal(err)
334 - return
335 - }
336 -
337 - _, _, err = api.Key().Rename(ctx, "foo", "self", opt.Key.Force(true))
338 - if err == nil {
339 - t.Error("expected error to not be nil")
340 - } else {
341 - if !strings.Contains(err.Error(), "cannot overwrite key with name 'self'") {
342 - t.Fatalf("expected error 'cannot overwrite key with name 'self'', got '%s'", err.Error())
343 - }
344 - }
345 -}
346 -
347 -func (tp *provider) TestRenameOverwriteNoForce(t *testing.T) {
348 - ctx, cancel := context.WithCancel(context.Background())
349 - defer cancel()
350 - api, err := tp.makeAPI(ctx)
351 - if err != nil {
352 - t.Error(err)
353 - }
354 -
355 - _, err = api.Key().Generate(ctx, "foo")
356 - if err != nil {
357 - t.Fatal(err)
358 - return
359 - }
360 -
361 - _, err = api.Key().Generate(ctx, "bar")
362 - if err != nil {
363 - t.Fatal(err)
364 - return
365 - }
366 -
367 - _, _, err = api.Key().Rename(ctx, "foo", "bar")
368 - if err == nil {
369 - t.Error("expected error to not be nil")
370 - } else {
371 - if !strings.Contains(err.Error(), "key by that name already exists, refusing to overwrite") {
372 - t.Fatalf("expected error 'key by that name already exists, refusing to overwrite', got '%s'", err.Error())
373 - }
374 - }
375 -}
376 -
377 -func (tp *provider) TestRenameOverwrite(t *testing.T) {
378 - ctx, cancel := context.WithCancel(context.Background())
379 - defer cancel()
380 - api, err := tp.makeAPI(ctx)
381 - if err != nil {
382 - t.Error(err)
383 - }
384 -
385 - kfoo, err := api.Key().Generate(ctx, "foo")
386 - if err != nil {
387 - t.Fatal(err)
388 - return
389 - }
390 -
391 - _, err = api.Key().Generate(ctx, "bar")
392 - if err != nil {
393 - t.Fatal(err)
394 - return
395 - }
396 -
397 - k, overwrote, err := api.Key().Rename(ctx, "foo", "bar", opt.Key.Force(true))
398 - if err != nil {
399 - t.Fatal(err)
400 - return
401 - }
402 -
403 - if !overwrote {
404 - t.Error("overwrote should be true")
405 - }
406 -
407 - if k.Name() != "bar" {
408 - t.Errorf("returned key should be called 'bar', got '%s'", k.Name())
409 - }
410 -
411 - if k.Path().String() != kfoo.Path().String() {
412 - t.Errorf("k and kfoo should have equal paths, '%s'!='%s'", k.Path().String(), kfoo.Path().String())
413 - }
414 -}
415 -
416 -func (tp *provider) TestRenameSameNameNoForce(t *testing.T) {
417 - ctx, cancel := context.WithCancel(context.Background())
418 - defer cancel()
419 - api, err := tp.makeAPI(ctx)
420 - if err != nil {
421 - t.Error(err)
422 - }
423 -
424 - _, err = api.Key().Generate(ctx, "foo")
425 - if err != nil {
426 - t.Fatal(err)
427 - return
428 - }
429 -
430 - k, overwrote, err := api.Key().Rename(ctx, "foo", "foo")
431 - if err != nil {
432 - t.Fatal(err)
433 - return
434 - }
435 -
436 - if overwrote {
437 - t.Error("overwrote should be false")
438 - }
439 -
440 - if k.Name() != "foo" {
441 - t.Errorf("returned key should be called 'foo', got '%s'", k.Name())
442 - }
443 -}
444 -
445 -func (tp *provider) TestRenameSameName(t *testing.T) {
446 - ctx, cancel := context.WithCancel(context.Background())
447 - defer cancel()
448 - api, err := tp.makeAPI(ctx)
449 - if err != nil {
450 - t.Error(err)
451 - }
452 -
453 - _, err = api.Key().Generate(ctx, "foo")
454 - if err != nil {
455 - t.Fatal(err)
456 - return
457 - }
458 -
459 - k, overwrote, err := api.Key().Rename(ctx, "foo", "foo", opt.Key.Force(true))
460 - if err != nil {
461 - t.Fatal(err)
462 - return
463 - }
464 -
465 - if overwrote {
466 - t.Error("overwrote should be false")
467 - }
468 -
469 - if k.Name() != "foo" {
470 - t.Errorf("returned key should be called 'foo', got '%s'", k.Name())
471 - }
472 -}
473 -
474 -func (tp *provider) TestRemove(t *testing.T) {
475 - ctx, cancel := context.WithCancel(context.Background())
476 - defer cancel()
477 - api, err := tp.makeAPI(ctx)
478 - if err != nil {
479 - t.Error(err)
480 - }
481 -
482 - k, err := api.Key().Generate(ctx, "foo")
483 - if err != nil {
484 - t.Fatal(err)
485 - return
486 - }
487 -
488 - l, err := api.Key().List(ctx)
489 - if err != nil {
490 - t.Fatal(err)
491 - return
492 - }
493 -
494 - if len(l) != 2 {
495 - t.Fatalf("expected to get 2 keys, got %d", len(l))
496 - return
497 - }
498 -
499 - p, err := api.Key().Remove(ctx, "foo")
500 - if err != nil {
501 - t.Fatal(err)
502 - return
503 - }
504 -
505 - if k.Path().String() != p.Path().String() {
506 - t.Errorf("k and p should have equal paths, '%s'!='%s'", k.Path().String(), p.Path().String())
507 - }
508 -
509 - l, err = api.Key().List(ctx)
510 - if err != nil {
511 - t.Fatal(err)
512 - return
513 - }
514 -
515 - if len(l) != 1 {
516 - t.Fatalf("expected to get 1 key, got %d", len(l))
517 - return
518 - }
519 -
520 - if l[0].Name() != "self" {
521 - t.Errorf("expected the key to be called 'self', got '%s'", l[0].Name())
522 - }
523 -}
core/coreapi/interface/tests/name.go deleted
-278
@@ -1,278 +0,0 @@
1 -package tests
2 -
3 -import (
4 - "context"
5 - "io"
6 - "math/rand"
7 - "path"
8 - "testing"
9 - "time"
10 -
11 - ipath "gx/ipfs/QmQ3YSqfxunT5QBg6KBVskKyRE26q6hjSMyhpxchpm7jEN/go-path"
12 - "gx/ipfs/QmaXvvAVAQ5ABqM5xtjYmV85xmN5MkWAZsX9H9Fwo4FVXp/go-ipfs-files"
13 -
14 - coreiface "github.com/ipfs/go-ipfs/core/coreapi/interface"
15 - opt "github.com/ipfs/go-ipfs/core/coreapi/interface/options"
16 -)
17 -
18 -func (tp *provider) TestName(t *testing.T) {
19 - tp.hasApi(t, func(api coreiface.CoreAPI) error {
20 - if api.Name() == nil {
21 - return apiNotImplemented
22 - }
23 - return nil
24 - })
25 -
26 - t.Run("TestPublishResolve", tp.TestPublishResolve)
27 - t.Run("TestBasicPublishResolveKey", tp.TestBasicPublishResolveKey)
28 - t.Run("TestBasicPublishResolveTimeout", tp.TestBasicPublishResolveTimeout)
29 -}
30 -
31 -var rnd = rand.New(rand.NewSource(0x62796532303137))
32 -
33 -func addTestObject(ctx context.Context, api coreiface.CoreAPI) (coreiface.Path, error) {
34 - return api.Unixfs().Add(ctx, files.NewReaderFile(&io.LimitedReader{R: rnd, N: 4092}))
35 -}
36 -
37 -func appendPath(p coreiface.Path, sub string) coreiface.Path {
38 - p, err := coreiface.ParsePath(path.Join(p.String(), sub))
39 - if err != nil {
40 - panic(err)
41 - }
42 - return p
43 -}
44 -
45 -func (tp *provider) TestPublishResolve(t *testing.T) {
46 - ctx, cancel := context.WithCancel(context.Background())
47 - defer cancel()
48 - init := func() (coreiface.CoreAPI, coreiface.Path) {
49 - apis, err := tp.MakeAPISwarm(ctx, true, 5)
50 - if err != nil {
51 - t.Fatal(err)
52 - return nil, nil
53 - }
54 - api := apis[0]
55 -
56 - p, err := addTestObject(ctx, api)
57 - if err != nil {
58 - t.Fatal(err)
59 - return nil, nil
60 - }
61 - return api, p
62 - }
63 -
64 - run := func(t *testing.T, ropts []opt.NameResolveOption) {
65 - t.Run("basic", func(t *testing.T) {
66 - api, p := init()
67 - e, err := api.Name().Publish(ctx, p)
68 - if err != nil {
69 - t.Fatal(err)
70 - }
71 -
72 - self, err := api.Key().Self(ctx)
73 - if err != nil {
74 - t.Fatal(err)
75 - }
76 -
77 - if e.Name() != self.ID().Pretty() {
78 - t.Errorf("expected e.Name to equal '%s', got '%s'", self.ID().Pretty(), e.Name())
79 - }
80 -
81 - if e.Value().String() != p.String() {
82 - t.Errorf("expected paths to match, '%s'!='%s'", e.Value().String(), p.String())
83 - }
84 -
85 - resPath, err := api.Name().Resolve(ctx, e.Name(), ropts...)
86 - if err != nil {
87 - t.Fatal(err)
88 - }
89 -
90 - if resPath.String() != p.String() {
91 - t.Errorf("expected paths to match, '%s'!='%s'", resPath.String(), p.String())
92 - }
93 - })
94 -
95 - t.Run("publishPath", func(t *testing.T) {
96 - api, p := init()
97 - e, err := api.Name().Publish(ctx, appendPath(p, "/test"))
98 - if err != nil {
99 - t.Fatal(err)
100 - }
101 -
102 - self, err := api.Key().Self(ctx)
103 - if err != nil {
104 - t.Fatal(err)
105 - }
106 -
107 - if e.Name() != self.ID().Pretty() {
108 - t.Errorf("expected e.Name to equal '%s', got '%s'", self.ID().Pretty(), e.Name())
109 - }
110 -
111 - if e.Value().String() != p.String()+"/test" {
112 - t.Errorf("expected paths to match, '%s'!='%s'", e.Value().String(), p.String())
113 - }
114 -
115 - resPath, err := api.Name().Resolve(ctx, e.Name(), ropts...)
116 - if err != nil {
117 - t.Fatal(err)
118 - }
119 -
120 - if resPath.String() != p.String()+"/test" {
121 - t.Errorf("expected paths to match, '%s'!='%s'", resPath.String(), p.String()+"/test")
122 - }
123 - })
124 -
125 - t.Run("revolvePath", func(t *testing.T) {
126 - api, p := init()
127 - e, err := api.Name().Publish(ctx, p)
128 - if err != nil {
129 - t.Fatal(err)
130 - }
131 -
132 - self, err := api.Key().Self(ctx)
133 - if err != nil {
134 - t.Fatal(err)
135 - }
136 -
137 - if e.Name() != self.ID().Pretty() {
138 - t.Errorf("expected e.Name to equal '%s', got '%s'", self.ID().Pretty(), e.Name())
139 - }
140 -
141 - if e.Value().String() != p.String() {
142 - t.Errorf("expected paths to match, '%s'!='%s'", e.Value().String(), p.String())
143 - }
144 -
145 - resPath, err := api.Name().Resolve(ctx, e.Name()+"/test", ropts...)
146 - if err != nil {
147 - t.Fatal(err)
148 - }
149 -
150 - if resPath.String() != p.String()+"/test" {
151 - t.Errorf("expected paths to match, '%s'!='%s'", resPath.String(), p.String()+"/test")
152 - }
153 - })
154 -
155 - t.Run("publishRevolvePath", func(t *testing.T) {
156 - api, p := init()
157 - e, err := api.Name().Publish(ctx, appendPath(p, "/a"))
158 - if err != nil {
159 - t.Fatal(err)
160 - }
161 -
162 - self, err := api.Key().Self(ctx)
163 - if err != nil {
164 - t.Fatal(err)
165 - }
166 -
167 - if e.Name() != self.ID().Pretty() {
168 - t.Errorf("expected e.Name to equal '%s', got '%s'", self.ID().Pretty(), e.Name())
169 - }
170 -
171 - if e.Value().String() != p.String()+"/a" {
172 - t.Errorf("expected paths to match, '%s'!='%s'", e.Value().String(), p.String())
173 - }
174 -
175 - resPath, err := api.Name().Resolve(ctx, e.Name()+"/b", ropts...)
176 - if err != nil {
177 - t.Fatal(err)
178 - }
179 -
180 - if resPath.String() != p.String()+"/a/b" {
181 - t.Errorf("expected paths to match, '%s'!='%s'", resPath.String(), p.String()+"/a/b")
182 - }
183 - })
184 - }
185 -
186 - t.Run("default", func(t *testing.T) {
187 - run(t, []opt.NameResolveOption{})
188 - })
189 -
190 - t.Run("nocache", func(t *testing.T) {
191 - run(t, []opt.NameResolveOption{opt.Name.Cache(false)})
192 - })
193 -}
194 -
195 -func (tp *provider) TestBasicPublishResolveKey(t *testing.T) {
196 - ctx, cancel := context.WithCancel(context.Background())
197 - defer cancel()
198 - apis, err := tp.MakeAPISwarm(ctx, true, 5)
199 - if err != nil {
200 - t.Fatal(err)
201 - }
202 - api := apis[0]
203 -
204 - k, err := api.Key().Generate(ctx, "foo")
205 - if err != nil {
206 - t.Fatal(err)
207 - }
208 -
209 - p, err := addTestObject(ctx, api)
210 - if err != nil {
211 - t.Fatal(err)
212 - }
213 -
214 - e, err := api.Name().Publish(ctx, p, opt.Name.Key(k.Name()))
215 - if err != nil {
216 - t.Fatal(err)
217 - }
218 -
219 - if ipath.Join([]string{"/ipns", e.Name()}) != k.Path().String() {
220 - t.Errorf("expected e.Name to equal '%s', got '%s'", e.Name(), k.Path().String())
221 - }
222 -
223 - if e.Value().String() != p.String() {
224 - t.Errorf("expected paths to match, '%s'!='%s'", e.Value().String(), p.String())
225 - }
226 -
227 - resPath, err := api.Name().Resolve(ctx, e.Name())
228 - if err != nil {
229 - t.Fatal(err)
230 - }
231 -
232 - if resPath.String() != p.String() {
233 - t.Errorf("expected paths to match, '%s'!='%s'", resPath.String(), p.String())
234 - }
235 -}
236 -
237 -func (tp *provider) TestBasicPublishResolveTimeout(t *testing.T) {
238 - t.Skip("ValidTime doesn't appear to work at this time resolution")
239 -
240 - ctx, cancel := context.WithCancel(context.Background())
241 - defer cancel()
242 - apis, err := tp.MakeAPISwarm(ctx, true, 5)
243 - if err != nil {
244 - t.Fatal(err)
245 - }
246 - api := apis[0]
247 - p, err := addTestObject(ctx, api)
248 - if err != nil {
249 - t.Fatal(err)
250 - }
251 -
252 - e, err := api.Name().Publish(ctx, p, opt.Name.ValidTime(time.Millisecond*100))
253 - if err != nil {
254 - t.Fatal(err)
255 - }
256 -
257 - self, err := api.Key().Self(ctx)
258 - if err != nil {
259 - t.Fatal(err)
260 - }
261 -
262 - if e.Name() != self.ID().Pretty() {
263 - t.Errorf("expected e.Name to equal '%s', got '%s'", self.ID().Pretty(), e.Name())
264 - }
265 -
266 - if e.Value().String() != p.String() {
267 - t.Errorf("expected paths to match, '%s'!='%s'", e.Value().String(), p.String())
268 - }
269 -
270 - time.Sleep(time.Second)
271 -
272 - _, err = api.Name().Resolve(ctx, e.Name())
273 - if err == nil {
274 - t.Fatal("Expected an error")
275 - }
276 -}
277 -
278 -//TODO: When swarm api is created, add multinode tests
core/coreapi/interface/tests/object.go deleted
-461
@@ -1,461 +0,0 @@
1 -package tests
2 -
3 -import (
4 - "bytes"
5 - "context"
6 - "encoding/hex"
7 - "io/ioutil"
8 - "strings"
9 - "testing"
10 -
11 - "github.com/ipfs/go-ipfs/core/coreapi/interface"
12 - opt "github.com/ipfs/go-ipfs/core/coreapi/interface/options"
13 -)
14 -
15 -func (tp *provider) TestObject(t *testing.T) {
16 - tp.hasApi(t, func(api iface.CoreAPI) error {
17 - if api.Object() == nil {
18 - return apiNotImplemented
19 - }
20 - return nil
21 - })
22 -
23 - t.Run("TestNew", tp.TestNew)
24 - t.Run("TestObjectPut", tp.TestObjectPut)
25 - t.Run("TestObjectGet", tp.TestObjectGet)
26 - t.Run("TestObjectData", tp.TestObjectData)
27 - t.Run("TestObjectLinks", tp.TestObjectLinks)
28 - t.Run("TestObjectStat", tp.TestObjectStat)
29 - t.Run("TestObjectAddLink", tp.TestObjectAddLink)
30 - t.Run("TestObjectAddLinkCreate", tp.TestObjectAddLinkCreate)
31 - t.Run("TestObjectRmLink", tp.TestObjectRmLink)
32 - t.Run("TestObjectAddData", tp.TestObjectAddData)
33 - t.Run("TestObjectSetData", tp.TestObjectSetData)
34 - t.Run("TestDiffTest", tp.TestDiffTest)
35 -}
36 -
37 -func (tp *provider) TestNew(t *testing.T) {
38 - ctx, cancel := context.WithCancel(context.Background())
39 - defer cancel()
40 - api, err := tp.makeAPI(ctx)
41 - if err != nil {
42 - t.Fatal(err)
43 - }
44 -
45 - emptyNode, err := api.Object().New(ctx)
46 - if err != nil {
47 - t.Fatal(err)
48 - }
49 -
50 - dirNode, err := api.Object().New(ctx, opt.Object.Type("unixfs-dir"))
51 - if err != nil {
52 - t.Fatal(err)
53 - }
54 -
55 - if emptyNode.String() != "QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n" {
56 - t.Errorf("Unexpected emptyNode path: %s", emptyNode.String())
57 - }
58 -
59 - if dirNode.String() != "QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn" {
60 - t.Errorf("Unexpected dirNode path: %s", dirNode.String())
61 - }
62 -}
63 -
64 -func (tp *provider) TestObjectPut(t *testing.T) {
65 - ctx, cancel := context.WithCancel(context.Background())
66 - defer cancel()
67 - api, err := tp.makeAPI(ctx)
68 - if err != nil {
69 - t.Fatal(err)
70 - }
71 -
72 - p1, err := api.Object().Put(ctx, strings.NewReader(`{"Data":"foo"}`))
73 - if err != nil {
74 - t.Fatal(err)
75 - }
76 -
77 - p2, err := api.Object().Put(ctx, strings.NewReader(`{"Data":"YmFy"}`), opt.Object.DataType("base64")) //bar
78 - if err != nil {
79 - t.Fatal(err)
80 - }
81 -
82 - pbBytes, err := hex.DecodeString("0a0362617a")
83 - if err != nil {
84 - t.Fatal(err)
85 - }
86 -
87 - p3, err := api.Object().Put(ctx, bytes.NewReader(pbBytes), opt.Object.InputEnc("protobuf"))
88 - if err != nil {
89 - t.Fatal(err)
90 - }
91 -
92 - if p1.String() != "/ipfs/QmQeGyS87nyijii7kFt1zbe4n2PsXTFimzsdxyE9qh9TST" {
93 - t.Errorf("unexpected path: %s", p1.String())
94 - }
95 -
96 - if p2.String() != "/ipfs/QmNeYRbCibmaMMK6Du6ChfServcLqFvLJF76PzzF76SPrZ" {
97 - t.Errorf("unexpected path: %s", p2.String())
98 - }
99 -
100 - if p3.String() != "/ipfs/QmZreR7M2t7bFXAdb1V5FtQhjk4t36GnrvueLJowJbQM9m" {
101 - t.Errorf("unexpected path: %s", p3.String())
102 - }
103 -}
104 -
105 -func (tp *provider) TestObjectGet(t *testing.T) {
106 - ctx, cancel := context.WithCancel(context.Background())
107 - defer cancel()
108 - api, err := tp.makeAPI(ctx)
109 - if err != nil {
110 - t.Fatal(err)
111 - }
112 -
113 - p1, err := api.Object().Put(ctx, strings.NewReader(`{"Data":"foo"}`))
114 - if err != nil {
115 - t.Fatal(err)
116 - }
117 -
118 - nd, err := api.Object().Get(ctx, p1)
119 - if err != nil {
120 - t.Fatal(err)
121 - }
122 -
123 - if string(nd.RawData()[len(nd.RawData())-3:]) != "foo" {
124 - t.Fatal("got non-matching data")
125 - }
126 -}
127 -
128 -func (tp *provider) TestObjectData(t *testing.T) {
129 - ctx, cancel := context.WithCancel(context.Background())
130 - defer cancel()
131 - api, err := tp.makeAPI(ctx)
132 - if err != nil {
133 - t.Fatal(err)
134 - }
135 -
136 - p1, err := api.Object().Put(ctx, strings.NewReader(`{"Data":"foo"}`))
137 - if err != nil {
138 - t.Fatal(err)
139 - }
140 -
141 - r, err := api.Object().Data(ctx, p1)
142 - if err != nil {
143 - t.Fatal(err)
144 - }
145 -
146 - data, err := ioutil.ReadAll(r)
147 - if err != nil {
148 - t.Fatal(err)
149 - }
150 -
151 - if string(data) != "foo" {
152 - t.Fatal("got non-matching data")
153 - }
154 -}
155 -
156 -func (tp *provider) TestObjectLinks(t *testing.T) {
157 - ctx, cancel := context.WithCancel(context.Background())
158 - defer cancel()
159 - api, err := tp.makeAPI(ctx)
160 - if err != nil {
161 - t.Fatal(err)
162 - }
163 -
164 - p1, err := api.Object().Put(ctx, strings.NewReader(`{"Data":"foo"}`))
165 - if err != nil {
166 - t.Fatal(err)
167 - }
168 -
169 - p2, err := api.Object().Put(ctx, strings.NewReader(`{"Links":[{"Name":"bar", "Hash":"`+p1.Cid().String()+`"}]}`))
170 - if err != nil {
171 - t.Fatal(err)
172 - }
173 -
174 - links, err := api.Object().Links(ctx, p2)
175 - if err != nil {
176 - t.Fatal(err)
177 - }
178 -
179 - if len(links) != 1 {
180 - t.Errorf("unexpected number of links: %d", len(links))
181 - }
182 -
183 - if links[0].Cid.String() != p1.Cid().String() {
184 - t.Fatal("cids didn't batch")
185 - }
186 -
187 - if links[0].Name != "bar" {
188 - t.Fatal("unexpected link name")
189 - }
190 -}
191 -
192 -func (tp *provider) TestObjectStat(t *testing.T) {
193 - ctx, cancel := context.WithCancel(context.Background())
194 - defer cancel()
195 - api, err := tp.makeAPI(ctx)
196 - if err != nil {
197 - t.Fatal(err)
198 - }
199 -
200 - p1, err := api.Object().Put(ctx, strings.NewReader(`{"Data":"foo"}`))
201 - if err != nil {
202 - t.Fatal(err)
203 - }
204 -
205 - p2, err := api.Object().Put(ctx, strings.NewReader(`{"Data":"bazz", "Links":[{"Name":"bar", "Hash":"`+p1.Cid().String()+`", "Size":3}]}`))
206 - if err != nil {
207 - t.Fatal(err)
208 - }
209 -
210 - stat, err := api.Object().Stat(ctx, p2)
211 - if err != nil {
212 - t.Fatal(err)
213 - }
214 -
215 - if stat.Cid.String() != p2.Cid().String() {
216 - t.Error("unexpected stat.Cid")
217 - }
218 -
219 - if stat.NumLinks != 1 {
220 - t.Errorf("unexpected stat.NumLinks")
221 - }
222 -
223 - if stat.BlockSize != 51 {
224 - t.Error("unexpected stat.BlockSize")
225 - }
226 -
227 - if stat.LinksSize != 47 {
228 - t.Errorf("unexpected stat.LinksSize: %d", stat.LinksSize)
229 - }
230 -
231 - if stat.DataSize != 4 {
232 - t.Error("unexpected stat.DataSize")
233 - }
234 -
235 - if stat.CumulativeSize != 54 {
236 - t.Error("unexpected stat.DataSize")
237 - }
238 -}
239 -
240 -func (tp *provider) TestObjectAddLink(t *testing.T) {
241 - ctx, cancel := context.WithCancel(context.Background())
242 - defer cancel()
243 - api, err := tp.makeAPI(ctx)
244 - if err != nil {
245 - t.Fatal(err)
246 - }
247 -
248 - p1, err := api.Object().Put(ctx, strings.NewReader(`{"Data":"foo"}`))
249 - if err != nil {
250 - t.Fatal(err)
251 - }
252 -
253 - p2, err := api.Object().Put(ctx, strings.NewReader(`{"Data":"bazz", "Links":[{"Name":"bar", "Hash":"`+p1.Cid().String()+`", "Size":3}]}`))
254 - if err != nil {
255 - t.Fatal(err)
256 - }
257 -
258 - p3, err := api.Object().AddLink(ctx, p2, "abc", p2)
259 - if err != nil {
260 - t.Fatal(err)
261 - }
262 -
263 - links, err := api.Object().Links(ctx, p3)
264 - if err != nil {
265 - t.Fatal(err)
266 - }
267 -
268 - if len(links) != 2 {
269 - t.Errorf("unexpected number of links: %d", len(links))
270 - }
271 -
272 - if links[0].Name != "abc" {
273 - t.Errorf("unexpected link 0 name: %s", links[0].Name)
274 - }
275 -
276 - if links[1].Name != "bar" {
277 - t.Errorf("unexpected link 1 name: %s", links[1].Name)
278 - }
279 -}
280 -
281 -func (tp *provider) TestObjectAddLinkCreate(t *testing.T) {
282 - ctx, cancel := context.WithCancel(context.Background())
283 - defer cancel()
284 - api, err := tp.makeAPI(ctx)
285 - if err != nil {
286 - t.Fatal(err)
287 - }
288 -
289 - p1, err := api.Object().Put(ctx, strings.NewReader(`{"Data":"foo"}`))
290 - if err != nil {
291 - t.Fatal(err)
292 - }
293 -
294 - p2, err := api.Object().Put(ctx, strings.NewReader(`{"Data":"bazz", "Links":[{"Name":"bar", "Hash":"`+p1.Cid().String()+`", "Size":3}]}`))
295 - if err != nil {
296 - t.Fatal(err)
297 - }
298 -
299 - p3, err := api.Object().AddLink(ctx, p2, "abc/d", p2)
300 - if err == nil {
301 - t.Fatal("expected an error")
302 - }
303 - if !strings.Contains(err.Error(), "no link by that name") {
304 - t.Fatalf("unexpected error: %s", err.Error())
305 - }
306 -
307 - p3, err = api.Object().AddLink(ctx, p2, "abc/d", p2, opt.Object.Create(true))
308 - if err != nil {
309 - t.Fatal(err)
310 - }
311 -
312 - links, err := api.Object().Links(ctx, p3)
313 - if err != nil {
314 - t.Fatal(err)
315 - }
316 -
317 - if len(links) != 2 {
318 - t.Errorf("unexpected number of links: %d", len(links))
319 - }
320 -
321 - if links[0].Name != "abc" {
322 - t.Errorf("unexpected link 0 name: %s", links[0].Name)
323 - }
324 -
325 - if links[1].Name != "bar" {
326 - t.Errorf("unexpected link 1 name: %s", links[1].Name)
327 - }
328 -}
329 -
330 -func (tp *provider) TestObjectRmLink(t *testing.T) {
331 - ctx, cancel := context.WithCancel(context.Background())
332 - defer cancel()
333 - api, err := tp.makeAPI(ctx)
334 - if err != nil {
335 - t.Fatal(err)
336 - }
337 -
338 - p1, err := api.Object().Put(ctx, strings.NewReader(`{"Data":"foo"}`))
339 - if err != nil {
340 - t.Fatal(err)
341 - }
342 -
343 - p2, err := api.Object().Put(ctx, strings.NewReader(`{"Data":"bazz", "Links":[{"Name":"bar", "Hash":"`+p1.Cid().String()+`", "Size":3}]}`))
344 - if err != nil {
345 - t.Fatal(err)
346 - }
347 -
348 - p3, err := api.Object().RmLink(ctx, p2, "bar")
349 - if err != nil {
350 - t.Fatal(err)
351 - }
352 -
353 - links, err := api.Object().Links(ctx, p3)
354 - if err != nil {
355 - t.Fatal(err)
356 - }
357 -
358 - if len(links) != 0 {
359 - t.Errorf("unexpected number of links: %d", len(links))
360 - }
361 -}
362 -
363 -func (tp *provider) TestObjectAddData(t *testing.T) {
364 - ctx, cancel := context.WithCancel(context.Background())
365 - defer cancel()
366 - api, err := tp.makeAPI(ctx)
367 - if err != nil {
368 - t.Fatal(err)
369 - }
370 -
371 - p1, err := api.Object().Put(ctx, strings.NewReader(`{"Data":"foo"}`))
372 - if err != nil {
373 - t.Fatal(err)
374 - }
375 -
376 - p2, err := api.Object().AppendData(ctx, p1, strings.NewReader("bar"))
377 - if err != nil {
378 - t.Fatal(err)
379 - }
380 -
381 - r, err := api.Object().Data(ctx, p2)
382 - if err != nil {
383 - t.Fatal(err)
384 - }
385 -
386 - data, err := ioutil.ReadAll(r)
387 -
388 - if string(data) != "foobar" {
389 - t.Error("unexpected data")
390 - }
391 -}
392 -
393 -func (tp *provider) TestObjectSetData(t *testing.T) {
394 - ctx, cancel := context.WithCancel(context.Background())
395 - defer cancel()
396 - api, err := tp.makeAPI(ctx)
397 - if err != nil {
398 - t.Fatal(err)
399 - }
400 -
401 - p1, err := api.Object().Put(ctx, strings.NewReader(`{"Data":"foo"}`))
402 - if err != nil {
403 - t.Fatal(err)
404 - }
405 -
406 - p2, err := api.Object().SetData(ctx, p1, strings.NewReader("bar"))
407 - if err != nil {
408 - t.Fatal(err)
409 - }
410 -
411 - r, err := api.Object().Data(ctx, p2)
412 - if err != nil {
413 - t.Fatal(err)
414 - }
415 -
416 - data, err := ioutil.ReadAll(r)
417 -
418 - if string(data) != "bar" {
419 - t.Error("unexpected data")
420 - }
421 -}
422 -
423 -func (tp *provider) TestDiffTest(t *testing.T) {
424 - ctx, cancel := context.WithCancel(context.Background())
425 - defer cancel()
426 - api, err := tp.makeAPI(ctx)
427 - if err != nil {
428 - t.Fatal(err)
429 - }
430 -
431 - p1, err := api.Object().Put(ctx, strings.NewReader(`{"Data":"foo"}`))
432 - if err != nil {
433 - t.Fatal(err)
434 - }
435 -
436 - p2, err := api.Object().Put(ctx, strings.NewReader(`{"Data":"bar"}`))
437 - if err != nil {
438 - t.Fatal(err)
439 - }
440 -
441 - changes, err := api.Object().Diff(ctx, p1, p2)
442 - if err != nil {
443 - t.Fatal(err)
444 - }
445 -
446 - if len(changes) != 1 {
447 - t.Fatal("unexpected changes len")
448 - }
449 -
450 - if changes[0].Type != iface.DiffMod {
451 - t.Fatal("unexpected change type")
452 - }
453 -
454 - if changes[0].Before.String() != p1.String() {
455 - t.Fatal("unexpected before path")
456 - }
457 -
458 - if changes[0].After.String() != p2.String() {
459 - t.Fatal("unexpected before path")
460 - }
461 -}
core/coreapi/interface/tests/path.go deleted
-219
@@ -1,219 +0,0 @@
1 -package tests
2 -
3 -import (
4 - "context"
5 - "math"
6 - "strings"
7 - "testing"
8 -
9 - coreiface "github.com/ipfs/go-ipfs/core/coreapi/interface"
10 - "github.com/ipfs/go-ipfs/core/coreapi/interface/options"
11 -
12 - ipldcbor "gx/ipfs/QmRZxJ7oybgnnwriuRub9JXp5YdFM9wiGSyRq38QC7swpS/go-ipld-cbor"
13 -)
14 -
15 -func (tp *provider) TestPath(t *testing.T) {
16 - t.Run("TestMutablePath", tp.TestMutablePath)
17 - t.Run("TestPathRemainder", tp.TestPathRemainder)
18 - t.Run("TestEmptyPathRemainder", tp.TestEmptyPathRemainder)
19 - t.Run("TestInvalidPathRemainder", tp.TestInvalidPathRemainder)
20 - t.Run("TestPathRoot", tp.TestPathRoot)
21 - t.Run("TestPathJoin", tp.TestPathJoin)
22 -}
23 -
24 -func (tp *provider) TestMutablePath(t *testing.T) {
25 - ctx, cancel := context.WithCancel(context.Background())
26 - defer cancel()
27 - api, err := tp.makeAPI(ctx)
28 - if err != nil {
29 - t.Fatal(err)
30 - }
31 -
32 - blk, err := api.Block().Put(ctx, strings.NewReader(`foo`))
33 - if err != nil {
34 - t.Fatal(err)
35 - }
36 -
37 - if blk.Path().Mutable() {
38 - t.Error("expected /ipld path to be immutable")
39 - }
40 -
41 - // get self /ipns path ipldcbor "gx/ipfs/QmRZxJ7oybgnnwriuRub9JXp5YdFM9wiGSyRq38QC7swpS/go-ipld-cbor"
42 -
43 - if api.Key() == nil {
44 - t.Fatal(".Key not implemented")
45 - }
46 -
47 - keys, err := api.Key().List(ctx)
48 - if err != nil {
49 - t.Fatal(err)
50 - }
51 -
52 - if !keys[0].Path().Mutable() {
53 - t.Error("expected self /ipns path to be mutable")
54 - }
55 -}
56 -
57 -func (tp *provider) TestPathRemainder(t *testing.T) {
58 - ctx, cancel := context.WithCancel(context.Background())
59 - defer cancel()
60 - api, err := tp.makeAPI(ctx)
61 - if err != nil {
62 - t.Fatal(err)
63 - }
64 -
65 - if api.Dag() == nil {
66 - t.Fatal(".Dag not implemented")
67 - }
68 -
69 - nd, err := ipldcbor.FromJSON(strings.NewReader(`{"foo": {"bar": "baz"}}`), math.MaxUint64, -1)
70 - if err != nil {
71 - t.Error(err)
72 - }
73 -
74 - if err := api.Dag().Add(ctx, nd); err != nil {
75 - t.Fatal(err)
76 - }
77 -
78 - p1, err := coreiface.ParsePath(nd.String() + "/foo/bar")
79 - if err != nil {
80 - t.Error(err)
81 - }
82 -
83 - rp1, err := api.ResolvePath(ctx, p1)
84 - if err != nil {
85 - t.Fatal(err)
86 - }
87 -
88 - if rp1.Remainder() != "foo/bar" {
89 - t.Error("expected to get path remainder")
90 - }
91 -}
92 -
93 -func (tp *provider) TestEmptyPathRemainder(t *testing.T) {
94 - ctx, cancel := context.WithCancel(context.Background())
95 - defer cancel()
96 - api, err := tp.makeAPI(ctx)
97 - if err != nil {
98 - t.Fatal(err)
99 - }
100 -
101 - if api.Dag() == nil {
102 - t.Fatal(".Dag not implemented")
103 - }
104 -
105 - nd, err := ipldcbor.FromJSON(strings.NewReader(`{"foo": {"bar": "baz"}}`), math.MaxUint64, -1)
106 - if err != nil {
107 - t.Error(err)
108 - }
109 -
110 - if err := api.Dag().Add(ctx, nd); err != nil {
111 - t.Fatal(err)
112 - }
113 -
114 - p1, err := coreiface.ParsePath(nd.Cid().String())
115 - if err != nil {
116 - t.Error(err)
117 - }
118 -
119 - rp1, err := api.ResolvePath(ctx, p1)
120 - if err != nil {
121 - t.Fatal(err)
122 - }
123 -
124 - if rp1.Remainder() != "" {
125 - t.Error("expected the resolved path to not have a remainder")
126 - }
127 -}
128 -
129 -func (tp *provider) TestInvalidPathRemainder(t *testing.T) {
130 - ctx, cancel := context.WithCancel(context.Background())
131 - defer cancel()
132 - api, err := tp.makeAPI(ctx)
133 - if err != nil {
134 - t.Fatal(err)
135 - }
136 -
137 - if api.Dag() == nil {
138 - t.Fatal(".Dag not implemented")
139 - }
140 -
141 - nd, err := ipldcbor.FromJSON(strings.NewReader(`{"foo": {"bar": "baz"}}`), math.MaxUint64, -1)
142 - if err != nil {
143 - t.Error(err)
144 - }
145 -
146 - if err := api.Dag().Add(ctx, nd); err != nil {
147 - t.Fatal(err)
148 - }
149 -
150 - p1, err := coreiface.ParsePath("/ipld/" + nd.Cid().String() + "/bar/baz")
151 - if err != nil {
152 - t.Error(err)
153 - }
154 -
155 - _, err = api.ResolvePath(ctx, p1)
156 - if err == nil || !strings.Contains(err.Error(), "no such link found") {
157 - t.Fatalf("unexpected error: %s", err)
158 - }
159 -}
160 -
161 -func (tp *provider) TestPathRoot(t *testing.T) {
162 - ctx, cancel := context.WithCancel(context.Background())
163 - defer cancel()
164 - api, err := tp.makeAPI(ctx)
165 - if err != nil {
166 - t.Fatal(err)
167 - }
168 -
169 - if api.Block() == nil {
170 - t.Fatal(".Block not implemented")
171 - }
172 -
173 - blk, err := api.Block().Put(ctx, strings.NewReader(`foo`), options.Block.Format("raw"))
174 - if err != nil {
175 - t.Fatal(err)
176 - }
177 -
178 - if api.Dag() == nil {
179 - t.Fatal(".Dag not implemented")
180 - }
181 -
182 - nd, err := ipldcbor.FromJSON(strings.NewReader(`{"foo": {"/": "`+blk.Path().Cid().String()+`"}}`), math.MaxUint64, -1)
183 - if err != nil {
184 - t.Error(err)
185 - }
186 -
187 - if err := api.Dag().Add(ctx, nd); err != nil {
188 - t.Fatal(err)
189 - }
190 -
191 - p1, err := coreiface.ParsePath("/ipld/" + nd.Cid().String() + "/foo")
192 - if err != nil {
193 - t.Error(err)
194 - }
195 -
196 - rp, err := api.ResolvePath(ctx, p1)
197 - if err != nil {
198 - t.Fatal(err)
199 - }
200 -
201 - if rp.Root().String() != nd.Cid().String() {
202 - t.Error("unexpected path root")
203 - }
204 -
205 - if rp.Cid().String() != blk.Path().Cid().String() {
206 - t.Error("unexpected path cid")
207 - }
208 -}
209 -
210 -func (tp *provider) TestPathJoin(t *testing.T) {
211 - p1, err := coreiface.ParsePath("/ipfs/QmYNmQKp6SuaVrpgWRsPTgCQCnpxUYGq76YEKBXuj2N4H6/bar/baz")
212 - if err != nil {
213 - t.Error(err)
214 - }
215 -
216 - if coreiface.Join(p1, "foo").String() != "/ipfs/QmYNmQKp6SuaVrpgWRsPTgCQCnpxUYGq76YEKBXuj2N4H6/bar/baz/foo" {
217 - t.Error("unexpected path")
218 - }
219 -}
core/coreapi/interface/tests/pin.go deleted
-239
@@ -1,239 +0,0 @@
1 -package tests
2 -
3 -import (
4 - "context"
5 - "math"
6 - "strings"
7 - "testing"
8 -
9 - "github.com/ipfs/go-ipfs/core/coreapi/interface"
10 - opt "github.com/ipfs/go-ipfs/core/coreapi/interface/options"
11 -
12 - ipld "gx/ipfs/QmRL22E4paat7ky7vx9MLpR97JHHbFPrg3ytFQw6qp1y1s/go-ipld-format"
13 - ipldcbor "gx/ipfs/QmRZxJ7oybgnnwriuRub9JXp5YdFM9wiGSyRq38QC7swpS/go-ipld-cbor"
14 -)
15 -
16 -func (tp *provider) TestPin(t *testing.T) {
17 - tp.hasApi(t, func(api iface.CoreAPI) error {
18 - if api.Pin() == nil {
19 - return apiNotImplemented
20 - }
21 - return nil
22 - })
23 -
24 - t.Run("TestPinAdd", tp.TestPinAdd)
25 - t.Run("TestPinSimple", tp.TestPinSimple)
26 - t.Run("TestPinRecursive", tp.TestPinRecursive)
27 -}
28 -
29 -func (tp *provider) TestPinAdd(t *testing.T) {
30 - ctx, cancel := context.WithCancel(context.Background())
31 - defer cancel()
32 - api, err := tp.makeAPI(ctx)
33 - if err != nil {
34 - t.Error(err)
35 - }
36 -
37 - p, err := api.Unixfs().Add(ctx, strFile("foo")())
38 - if err != nil {
39 - t.Error(err)
40 - }
41 -
42 - err = api.Pin().Add(ctx, p)
43 - if err != nil {
44 - t.Error(err)
45 - }
46 -}
47 -
48 -func (tp *provider) TestPinSimple(t *testing.T) {
49 - ctx, cancel := context.WithCancel(context.Background())
50 - defer cancel()
51 - api, err := tp.makeAPI(ctx)
52 - if err != nil {
53 - t.Error(err)
54 - }
55 -
56 - p, err := api.Unixfs().Add(ctx, strFile("foo")())
57 - if err != nil {
58 - t.Error(err)
59 - }
60 -
61 - err = api.Pin().Add(ctx, p)
62 - if err != nil {
63 - t.Error(err)
64 - }
65 -
66 - list, err := api.Pin().Ls(ctx)
67 - if err != nil {
68 - t.Fatal(err)
69 - }
70 -
71 - if len(list) != 1 {
72 - t.Errorf("unexpected pin list len: %d", len(list))
73 - }
74 -
75 - if list[0].Path().Cid().String() != p.Cid().String() {
76 - t.Error("paths don't match")
77 - }
78 -
79 - if list[0].Type() != "recursive" {
80 - t.Error("unexpected pin type")
81 - }
82 -
83 - err = api.Pin().Rm(ctx, p)
84 - if err != nil {
85 - t.Fatal(err)
86 - }
87 -
88 - list, err = api.Pin().Ls(ctx)
89 - if err != nil {
90 - t.Fatal(err)
91 - }
92 -
93 - if len(list) != 0 {
94 - t.Errorf("unexpected pin list len: %d", len(list))
95 - }
96 -}
97 -
98 -func (tp *provider) TestPinRecursive(t *testing.T) {
99 - ctx, cancel := context.WithCancel(context.Background())
100 - defer cancel()
101 - api, err := tp.makeAPI(ctx)
102 - if err != nil {
103 - t.Error(err)
104 - }
105 -
106 - p0, err := api.Unixfs().Add(ctx, strFile("foo")())
107 - if err != nil {
108 - t.Error(err)
109 - }
110 -
111 - p1, err := api.Unixfs().Add(ctx, strFile("bar")())
112 - if err != nil {
113 - t.Error(err)
114 - }
115 -
116 - nd2, err := ipldcbor.FromJSON(strings.NewReader(`{"lnk": {"/": "`+p0.Cid().String()+`"}}`), math.MaxUint64, -1)
117 - if err != nil {
118 - t.Error(err)
119 - }
120 -
121 - nd3, err := ipldcbor.FromJSON(strings.NewReader(`{"lnk": {"/": "`+p1.Cid().String()+`"}}`), math.MaxUint64, -1)
122 - if err != nil {
123 - t.Error(err)
124 - }
125 -
126 - if err := api.Dag().AddMany(ctx, []ipld.Node{nd2, nd3}); err != nil {
127 - t.Fatal(err)
128 - }
129 -
130 - err = api.Pin().Add(ctx, iface.IpldPath(nd2.Cid()))
131 - if err != nil {
132 - t.Error(err)
133 - }
134 -
135 - err = api.Pin().Add(ctx, iface.IpldPath(nd3.Cid()), opt.Pin.Recursive(false))
136 - if err != nil {
137 - t.Error(err)
138 - }
139 -
140 - list, err := api.Pin().Ls(ctx)
141 - if err != nil {
142 - t.Fatal(err)
143 - }
144 -
145 - if len(list) != 3 {
146 - t.Errorf("unexpected pin list len: %d", len(list))
147 - }
148 -
149 - list, err = api.Pin().Ls(ctx, opt.Pin.Type.Direct())
150 - if err != nil {
151 - t.Fatal(err)
152 - }
153 -
154 - if len(list) != 1 {
155 - t.Errorf("unexpected pin list len: %d", len(list))
156 - }
157 -
158 - if list[0].Path().String() != iface.IpldPath(nd3.Cid()).String() {
159 - t.Errorf("unexpected path, %s != %s", list[0].Path().String(), iface.IpfsPath(nd2.Cid()).String())
160 - }
161 -
162 - list, err = api.Pin().Ls(ctx, opt.Pin.Type.Recursive())
163 - if err != nil {
164 - t.Fatal(err)
165 - }
166 -
167 - if len(list) != 1 {
168 - t.Errorf("unexpected pin list len: %d", len(list))
169 - }
170 -
171 - if list[0].Path().String() != iface.IpldPath(nd2.Cid()).String() {
172 - t.Errorf("unexpected path, %s != %s", list[0].Path().String(), iface.IpldPath(nd3.Cid()).String())
173 - }
174 -
175 - list, err = api.Pin().Ls(ctx, opt.Pin.Type.Indirect())
176 - if err != nil {
177 - t.Fatal(err)
178 - }
179 -
180 - if len(list) != 1 {
181 - t.Errorf("unexpected pin list len: %d", len(list))
182 - }
183 -
184 - if list[0].Path().Cid().String() != p0.Cid().String() {
185 - t.Error("unexpected path")
186 - }
187 -
188 - res, err := api.Pin().Verify(ctx)
189 - if err != nil {
190 - t.Fatal(err)
191 - }
192 - n := 0
193 - for r := range res {
194 - if !r.Ok() {
195 - t.Error("expected pin to be ok")
196 - }
197 - n++
198 - }
199 -
200 - if n != 1 {
201 - t.Errorf("unexpected verify result count: %d", n)
202 - }
203 -
204 - //TODO: figure out a way to test verify without touching IpfsNode
205 - /*
206 - err = api.Block().Rm(ctx, p0, opt.Block.Force(true))
207 - if err != nil {
208 - t.Fatal(err)
209 - }
210 -
211 - res, err = api.Pin().Verify(ctx)
212 - if err != nil {
213 - t.Fatal(err)
214 - }
215 - n = 0
216 - for r := range res {
217 - if r.Ok() {
218 - t.Error("expected pin to not be ok")
219 - }
220 -
221 - if len(r.BadNodes()) != 1 {
222 - t.Fatalf("unexpected badNodes len")
223 - }
224 -
225 - if r.BadNodes()[0].Path().Cid().String() != p0.Cid().String() {
226 - t.Error("unexpected badNode path")
227 - }
228 -
229 - if r.BadNodes()[0].Err().Error() != "merkledag: not found" {
230 - t.Errorf("unexpected badNode error: %s", r.BadNodes()[0].Err().Error())
231 - }
232 - n++
233 - }
234 -
235 - if n != 1 {
236 - t.Errorf("unexpected verify result count: %d", n)
237 - }
238 - */
239 -}
core/coreapi/interface/tests/pubsub.go deleted
-118
@@ -1,118 +0,0 @@
1 -package tests
2 -
3 -import (
4 - "context"
5 - "github.com/ipfs/go-ipfs/core/coreapi/interface"
6 - "github.com/ipfs/go-ipfs/core/coreapi/interface/options"
7 - "testing"
8 - "time"
9 -)
10 -
11 -func (tp *provider) TestPubSub(t *testing.T) {
12 - tp.hasApi(t, func(api iface.CoreAPI) error {
13 - if api.PubSub() == nil {
14 - return apiNotImplemented
15 - }
16 - return nil
17 - })
18 -
19 - t.Run("TestBasicPubSub", tp.TestBasicPubSub)
20 -}
21 -
22 -func (tp *provider) TestBasicPubSub(t *testing.T) {
23 - ctx, cancel := context.WithCancel(context.Background())
24 - defer cancel()
25 -
26 - apis, err := tp.MakeAPISwarm(ctx, true, 2)
27 - if err != nil {
28 - t.Fatal(err)
29 - }
30 -
31 - sub, err := apis[0].PubSub().Subscribe(ctx, "testch")
32 - if err != nil {
33 - t.Fatal(err)
34 - }
35 -
36 - go func() {
37 - tick := time.Tick(100 * time.Millisecond)
38 -
39 - for {
40 - err = apis[1].PubSub().Publish(ctx, "testch", []byte("hello world"))
41 - if err != nil {
42 - t.Fatal(err)
43 - }
44 - select {
45 - case <-tick:
46 - case <-ctx.Done():
47 - return
48 - }
49 - }
50 - }()
51 -
52 - m, err := sub.Next(ctx)
53 - if err != nil {
54 - t.Fatal(err)
55 - }
56 -
57 - if string(m.Data()) != "hello world" {
58 - t.Errorf("got invalid data: %s", string(m.Data()))
59 - }
60 -
61 - self1, err := apis[1].Key().Self(ctx)
62 - if err != nil {
63 - t.Fatal(err)
64 - }
65 -
66 - if m.From() != self1.ID() {
67 - t.Errorf("m.From didn't match")
68 - }
69 -
70 - peers, err := apis[1].PubSub().Peers(ctx, options.PubSub.Topic("testch"))
71 - if err != nil {
72 - t.Fatal(err)
73 - }
74 -
75 - if len(peers) != 1 {
76 - t.Fatalf("got incorrect number of peers: %d", len(peers))
77 - }
78 -
79 - self0, err := apis[0].Key().Self(ctx)
80 - if err != nil {
81 - t.Fatal(err)
82 - }
83 -
84 - if peers[0] != self0.ID() {
85 - t.Errorf("peer didn't match")
86 - }
87 -
88 - peers, err = apis[1].PubSub().Peers(ctx, options.PubSub.Topic("nottestch"))
89 - if err != nil {
90 - t.Fatal(err)
91 - }
92 -
93 - if len(peers) != 0 {
94 - t.Fatalf("got incorrect number of peers: %d", len(peers))
95 - }
96 -
97 - topics, err := apis[0].PubSub().Ls(ctx)
98 - if err != nil {
99 - t.Fatal(err)
100 - }
101 -
102 - if len(topics) != 1 {
103 - t.Fatalf("got incorrect number of topics: %d", len(peers))
104 - }
105 -
106 - if topics[0] != "testch" {
107 - t.Errorf("topic didn't match")
108 - }
109 -
110 - topics, err = apis[1].PubSub().Ls(ctx)
111 - if err != nil {
112 - t.Fatal(err)
113 - }
114 -
115 - if len(topics) != 0 {
116 - t.Fatalf("got incorrect number of topics: %d", len(peers))
117 - }
118 -}
core/coreapi/interface/tests/unixfs.go deleted
-1055
@@ -1,1055 +0,0 @@
1 -package tests
2 -
3 -import (
4 - "bytes"
5 - "context"
6 - "encoding/hex"
7 - "fmt"
8 - "io"
9 - "io/ioutil"
10 - "math"
11 - "math/rand"
12 - "os"
13 - "strconv"
14 - "strings"
15 - "sync"
16 - "testing"
17 -
18 - coreiface "github.com/ipfs/go-ipfs/core/coreapi/interface"
19 - "github.com/ipfs/go-ipfs/core/coreapi/interface/options"
20 -
21 - "gx/ipfs/QmR8BauakNcBa3RbE4nbQu76PDiJgoQgz8AJdhJuiU4TAw/go-cid"
22 - cbor "gx/ipfs/QmRZxJ7oybgnnwriuRub9JXp5YdFM9wiGSyRq38QC7swpS/go-ipld-cbor"
23 - mdag "gx/ipfs/QmUtsx89yiCY6F8mbpP6ecXckiSzCBH7EvkKZuZEHBcr1m/go-merkledag"
24 - "gx/ipfs/QmZArMcsVDsXdcLbUx4844CuqKXBpbxdeiryM4cnmGTNRq/go-unixfs"
25 - "gx/ipfs/QmZArMcsVDsXdcLbUx4844CuqKXBpbxdeiryM4cnmGTNRq/go-unixfs/importer/helpers"
26 - "gx/ipfs/QmaXvvAVAQ5ABqM5xtjYmV85xmN5MkWAZsX9H9Fwo4FVXp/go-ipfs-files"
27 - mh "gx/ipfs/QmerPMzPk1mJVowm8KgmoknWa4yCYvvugMPsgWmDNUvDLW/go-multihash"
28 -)
29 -
30 -func (tp *provider) TestUnixfs(t *testing.T) {
31 - tp.hasApi(t, func(api coreiface.CoreAPI) error {
32 - if api.Unixfs() == nil {
33 - return apiNotImplemented
34 - }
35 - return nil
36 - })
37 -
38 - t.Run("TestAdd", tp.TestAdd)
39 - t.Run("TestAddPinned", tp.TestAddPinned)
40 - t.Run("TestAddHashOnly", tp.TestAddHashOnly)
41 - t.Run("TestGetEmptyFile", tp.TestGetEmptyFile)
42 - t.Run("TestGetDir", tp.TestGetDir)
43 - t.Run("TestGetNonUnixfs", tp.TestGetNonUnixfs)
44 - t.Run("TestLs", tp.TestLs)
45 - t.Run("TestEntriesExpired", tp.TestEntriesExpired)
46 - t.Run("TestLsEmptyDir", tp.TestLsEmptyDir)
47 - t.Run("TestLsNonUnixfs", tp.TestLsNonUnixfs)
48 - t.Run("TestAddCloses", tp.TestAddCloses)
49 - t.Run("TestGetSeek", tp.TestGetSeek)
50 -}
51 -
52 -// `echo -n 'hello, world!' | ipfs add`
53 -var hello = "/ipfs/QmQy2Dw4Wk7rdJKjThjYXzfFJNaRKRHhHP5gHHXroJMYxk"
54 -var helloStr = "hello, world!"
55 -
56 -// `echo -n | ipfs add`
57 -var emptyFile = "/ipfs/QmbFMke1KXqnYyBBWxB74N4c5SBnJMVAiMNRcGu6x1AwQH"
58 -
59 -func strFile(data string) func() files.Node {
60 - return func() files.Node {
61 - return files.NewBytesFile([]byte(data))
62 - }
63 -}
64 -
65 -func twoLevelDir() func() files.Node {
66 - return func() files.Node {
67 - return files.NewMapDirectory(map[string]files.Node{
68 - "abc": files.NewMapDirectory(map[string]files.Node{
69 - "def": files.NewBytesFile([]byte("world")),
70 - }),
71 -
72 - "bar": files.NewBytesFile([]byte("hello2")),
73 - "foo": files.NewBytesFile([]byte("hello1")),
74 - })
75 - }
76 -}
77 -
78 -func flatDir() files.Node {
79 - return files.NewMapDirectory(map[string]files.Node{
80 - "bar": files.NewBytesFile([]byte("hello2")),
81 - "foo": files.NewBytesFile([]byte("hello1")),
82 - })
83 -}
84 -
85 -func wrapped(name string) func(f files.Node) files.Node {
86 - return func(f files.Node) files.Node {
87 - return files.NewMapDirectory(map[string]files.Node{
88 - name: f,
89 - })
90 - }
91 -}
92 -
93 -func (tp *provider) TestAdd(t *testing.T) {
94 - ctx, cancel := context.WithCancel(context.Background())
95 - defer cancel()
96 - api, err := tp.makeAPI(ctx)
97 - if err != nil {
98 - t.Error(err)
99 - }
100 -
101 - p := func(h string) coreiface.ResolvedPath {
102 - c, err := cid.Parse(h)
103 - if err != nil {
104 - t.Fatal(err)
105 - }
106 - return coreiface.IpfsPath(c)
107 - }
108 -
109 - rf, err := ioutil.TempFile(os.TempDir(), "unixfs-add-real")
110 - if err != nil {
111 - t.Fatal(err)
112 - }
113 - rfp := rf.Name()
114 -
115 - if _, err := rf.Write([]byte(helloStr)); err != nil {
116 - t.Fatal(err)
117 - }
118 -
119 - stat, err := rf.Stat()
120 - if err != nil {
121 - t.Fatal(err)
122 - }
123 -
124 - if err := rf.Close(); err != nil {
125 - t.Fatal(err)
126 - }
127 - defer os.Remove(rfp)
128 -
129 - realFile := func() files.Node {
130 - n, err := files.NewReaderPathFile(rfp, ioutil.NopCloser(strings.NewReader(helloStr)), stat)
131 - if err != nil {
132 - t.Fatal(err)
133 - }
134 - return n
135 - }
136 -
137 - cases := []struct {
138 - name string
139 - data func() files.Node
140 - expect func(files.Node) files.Node
141 -
142 - apiOpts []options.ApiOption
143 -
144 - path string
145 - err string
146 -
147 - wrap string
148 -
149 - events []coreiface.AddEvent
150 -
151 - opts []options.UnixfsAddOption
152 - }{
153 - // Simple cases
154 - {
155 - name: "simpleAdd",
156 - data: strFile(helloStr),
157 - path: hello,
158 - opts: []options.UnixfsAddOption{},
159 - },
160 - {
161 - name: "addEmpty",
162 - data: strFile(""),
163 - path: emptyFile,
164 - },
165 - // CIDv1 version / rawLeaves
166 - {
167 - name: "addCidV1",
168 - data: strFile(helloStr),
169 - path: "/ipfs/zb2rhdhmJjJZs9qkhQCpCQ7VREFkqWw3h1r8utjVvQugwHPFd",
170 - opts: []options.UnixfsAddOption{options.Unixfs.CidVersion(1)},
171 - },
172 - {
173 - name: "addCidV1NoLeaves",
174 - data: strFile(helloStr),
175 - path: "/ipfs/zdj7WY4GbN8NDbTW1dfCShAQNVovams2xhq9hVCx5vXcjvT8g",
176 - opts: []options.UnixfsAddOption{options.Unixfs.CidVersion(1), options.Unixfs.RawLeaves(false)},
177 - },
178 - // Non sha256 hash vs CID
179 - {
180 - name: "addCidSha3",
181 - data: strFile(helloStr),
182 - path: "/ipfs/zb2wwnYtXBxpndNABjtYxWAPt3cwWNRnc11iT63fvkYV78iRb",
183 - opts: []options.UnixfsAddOption{options.Unixfs.Hash(mh.SHA3_256)},
184 - },
185 - {
186 - name: "addCidSha3Cid0",
187 - data: strFile(helloStr),
188 - err: "CIDv0 only supports sha2-256",
189 - opts: []options.UnixfsAddOption{options.Unixfs.CidVersion(0), options.Unixfs.Hash(mh.SHA3_256)},
190 - },
191 - // Inline
192 - {
193 - name: "addInline",
194 - data: strFile(helloStr),
195 - path: "/ipfs/zaYomJdLndMku8P9LHngHB5w2CQ7NenLbv",
196 - opts: []options.UnixfsAddOption{options.Unixfs.Inline(true)},
197 - },
198 - {
199 - name: "addInlineLimit",
200 - data: strFile(helloStr),
201 - path: "/ipfs/zaYomJdLndMku8P9LHngHB5w2CQ7NenLbv",
202 - opts: []options.UnixfsAddOption{options.Unixfs.InlineLimit(32), options.Unixfs.Inline(true)},
203 - },
204 - {
205 - name: "addInlineZero",
206 - data: strFile(""),
207 - path: "/ipfs/z2yYDV",
208 - opts: []options.UnixfsAddOption{options.Unixfs.InlineLimit(0), options.Unixfs.Inline(true), options.Unixfs.RawLeaves(true)},
209 - },
210 - { //TODO: after coreapi add is used in `ipfs add`, consider making this default for inline
211 - name: "addInlineRaw",
212 - data: strFile(helloStr),
213 - path: "/ipfs/zj7Gr8AcBreqGEfrnR5kPFe",
214 - opts: []options.UnixfsAddOption{options.Unixfs.InlineLimit(32), options.Unixfs.Inline(true), options.Unixfs.RawLeaves(true)},
215 - },
216 - // Chunker / Layout
217 - {
218 - name: "addChunks",
219 - data: strFile(strings.Repeat("aoeuidhtns", 200)),
220 - path: "/ipfs/QmRo11d4QJrST47aaiGVJYwPhoNA4ihRpJ5WaxBWjWDwbX",
221 - opts: []options.UnixfsAddOption{options.Unixfs.Chunker("size-4")},
222 - },
223 - {
224 - name: "addChunksTrickle",
225 - data: strFile(strings.Repeat("aoeuidhtns", 200)),
226 - path: "/ipfs/QmNNhDGttafX3M1wKWixGre6PrLFGjnoPEDXjBYpTv93HP",
227 - opts: []options.UnixfsAddOption{options.Unixfs.Chunker("size-4"), options.Unixfs.Layout(options.TrickleLayout)},
228 - },
229 - // Local
230 - {
231 - name: "addLocal", // better cases in sharness
232 - data: strFile(helloStr),
233 - path: hello,
234 - apiOpts: []options.ApiOption{options.Api.Offline(true)},
235 - },
236 - {
237 - name: "hashOnly", // test (non)fetchability
238 - data: strFile(helloStr),
239 - path: hello,
240 - opts: []options.UnixfsAddOption{options.Unixfs.HashOnly(true)},
241 - },
242 - // multi file
243 - {
244 - name: "simpleDir",
245 - data: flatDir,
246 - wrap: "t",
247 - path: "/ipfs/QmRKGpFfR32FVXdvJiHfo4WJ5TDYBsM1P9raAp1p6APWSp",
248 - },
249 - {
250 - name: "twoLevelDir",
251 - data: twoLevelDir(),
252 - wrap: "t",
253 - path: "/ipfs/QmVG2ZYCkV1S4TK8URA3a4RupBF17A8yAr4FqsRDXVJASr",
254 - },
255 - // wrapped
256 - {
257 - name: "addWrapped",
258 - path: "/ipfs/QmVE9rNpj5doj7XHzp5zMUxD7BJgXEqx4pe3xZ3JBReWHE",
259 - data: func() files.Node {
260 - return files.NewBytesFile([]byte(helloStr))
261 - },
262 - wrap: "foo",
263 - expect: wrapped("foo"),
264 - opts: []options.UnixfsAddOption{options.Unixfs.Wrap(true)},
265 - },
266 - {
267 - name: "addNotWrappedDirFile",
268 - path: hello,
269 - data: func() files.Node {
270 - return files.NewBytesFile([]byte(helloStr))
271 - },
272 - wrap: "foo",
273 - },
274 - {
275 - name: "stdinWrapped",
276 - path: "/ipfs/QmU3r81oZycjHS9oaSHw37ootMFuFUw1DvMLKXPsezdtqU",
277 - data: func() files.Node {
278 - return files.NewBytesFile([]byte(helloStr))
279 - },
280 - expect: func(files.Node) files.Node {
281 - return files.NewMapDirectory(map[string]files.Node{
282 - "QmQy2Dw4Wk7rdJKjThjYXzfFJNaRKRHhHP5gHHXroJMYxk": files.NewBytesFile([]byte(helloStr)),
283 - })
284 - },
285 - opts: []options.UnixfsAddOption{options.Unixfs.Wrap(true)},
286 - },
287 - {
288 - name: "stdinNamed",
289 - path: "/ipfs/QmQ6cGBmb3ZbdrQW1MRm1RJnYnaxCqfssz7CrTa9NEhQyS",
290 - data: func() files.Node {
291 - rf, err := files.NewReaderPathFile(os.Stdin.Name(), ioutil.NopCloser(strings.NewReader(helloStr)), nil)
292 - if err != nil {
293 - panic(err)
294 - }
295 -
296 - return rf
297 - },
298 - expect: func(files.Node) files.Node {
299 - return files.NewMapDirectory(map[string]files.Node{
300 - "test": files.NewBytesFile([]byte(helloStr)),
301 - })
302 - },
303 - opts: []options.UnixfsAddOption{options.Unixfs.Wrap(true), options.Unixfs.StdinName("test")},
304 - },
305 - {
306 - name: "twoLevelDirWrapped",
307 - data: twoLevelDir(),
308 - wrap: "t",
309 - expect: wrapped("t"),
310 - path: "/ipfs/QmPwsL3T5sWhDmmAWZHAzyjKtMVDS9a11aHNRqb3xoVnmg",
311 - opts: []options.UnixfsAddOption{options.Unixfs.Wrap(true)},
312 - },
313 - {
314 - name: "twoLevelInlineHash",
315 - data: twoLevelDir(),
316 - wrap: "t",
317 - expect: wrapped("t"),
318 - path: "/ipfs/zBunoruKoyCHKkALNSWxDvj4L7yuQnMgQ4hUa9j1Z64tVcDEcu6Zdetyu7eeFCxMPfxb7YJvHeFHoFoHMkBUQf6vfdhmi",
319 - opts: []options.UnixfsAddOption{options.Unixfs.Wrap(true), options.Unixfs.Inline(true), options.Unixfs.RawLeaves(true), options.Unixfs.Hash(mh.SHA3)},
320 - },
321 - // hidden
322 - {
323 - name: "hiddenFiles",
324 - data: func() files.Node {
325 - return files.NewMapDirectory(map[string]files.Node{
326 - ".bar": files.NewBytesFile([]byte("hello2")),
327 - "bar": files.NewBytesFile([]byte("hello2")),
328 - "foo": files.NewBytesFile([]byte("hello1")),
329 - })
330 - },
331 - wrap: "t",
332 - path: "/ipfs/QmehGvpf2hY196MzDFmjL8Wy27S4jbgGDUAhBJyvXAwr3g",
333 - opts: []options.UnixfsAddOption{options.Unixfs.Hidden(true)},
334 - },
335 - {
336 - name: "hiddenFileAlwaysAdded",
337 - data: func() files.Node {
338 - return files.NewBytesFile([]byte(helloStr))
339 - },
340 - wrap: ".foo",
341 - path: hello,
342 - },
343 - {
344 - name: "hiddenFilesNotAdded",
345 - data: func() files.Node {
346 - return files.NewMapDirectory(map[string]files.Node{
347 - ".bar": files.NewBytesFile([]byte("hello2")),
348 - "bar": files.NewBytesFile([]byte("hello2")),
349 - "foo": files.NewBytesFile([]byte("hello1")),
350 - })
351 - },
352 - expect: func(files.Node) files.Node {
353 - return flatDir()
354 - },
355 - wrap: "t",
356 - path: "/ipfs/QmRKGpFfR32FVXdvJiHfo4WJ5TDYBsM1P9raAp1p6APWSp",
357 - opts: []options.UnixfsAddOption{options.Unixfs.Hidden(false)},
358 - },
359 - // NoCopy
360 - {
361 - name: "simpleNoCopy",
362 - data: realFile,
363 - path: "/ipfs/zb2rhdhmJjJZs9qkhQCpCQ7VREFkqWw3h1r8utjVvQugwHPFd",
364 - opts: []options.UnixfsAddOption{options.Unixfs.Nocopy(true)},
365 - },
366 - {
367 - name: "noCopyNoRaw",
368 - data: realFile,
369 - path: "/ipfs/zb2rhdhmJjJZs9qkhQCpCQ7VREFkqWw3h1r8utjVvQugwHPFd",
370 - opts: []options.UnixfsAddOption{options.Unixfs.Nocopy(true), options.Unixfs.RawLeaves(false)},
371 - err: "nocopy option requires '--raw-leaves' to be enabled as well",
372 - },
373 - {
374 - name: "noCopyNoPath",
375 - data: strFile(helloStr),
376 - path: "/ipfs/zb2rhdhmJjJZs9qkhQCpCQ7VREFkqWw3h1r8utjVvQugwHPFd",
377 - opts: []options.UnixfsAddOption{options.Unixfs.Nocopy(true)},
378 - err: helpers.ErrMissingFsRef.Error(),
379 - },
380 - // Events / Progress
381 - {
382 - name: "simpleAddEvent",
383 - data: strFile(helloStr),
384 - path: "/ipfs/zb2rhdhmJjJZs9qkhQCpCQ7VREFkqWw3h1r8utjVvQugwHPFd",
385 - events: []coreiface.AddEvent{
386 - {Name: "zb2rhdhmJjJZs9qkhQCpCQ7VREFkqWw3h1r8utjVvQugwHPFd", Path: p("zb2rhdhmJjJZs9qkhQCpCQ7VREFkqWw3h1r8utjVvQugwHPFd"), Size: strconv.Itoa(len(helloStr))},
387 - },
388 - opts: []options.UnixfsAddOption{options.Unixfs.RawLeaves(true)},
389 - },
390 - {
391 - name: "silentAddEvent",
392 - data: twoLevelDir(),
393 - path: "/ipfs/QmVG2ZYCkV1S4TK8URA3a4RupBF17A8yAr4FqsRDXVJASr",
394 - events: []coreiface.AddEvent{
395 - {Name: "t/abc", Path: p("QmU7nuGs2djqK99UNsNgEPGh6GV4662p6WtsgccBNGTDxt"), Size: "62"},
396 - {Name: "t", Path: p("QmVG2ZYCkV1S4TK8URA3a4RupBF17A8yAr4FqsRDXVJASr"), Size: "229"},
397 - },
398 - wrap: "t",
399 - opts: []options.UnixfsAddOption{options.Unixfs.Silent(true)},
400 - },
401 - {
402 - name: "dirAddEvents",
403 - data: twoLevelDir(),
404 - path: "/ipfs/QmVG2ZYCkV1S4TK8URA3a4RupBF17A8yAr4FqsRDXVJASr",
405 - events: []coreiface.AddEvent{
406 - {Name: "t/abc/def", Path: p("QmNyJpQkU1cEkBwMDhDNFstr42q55mqG5GE5Mgwug4xyGk"), Size: "13"},
407 - {Name: "t/bar", Path: p("QmS21GuXiRMvJKHos4ZkEmQDmRBqRaF5tQS2CQCu2ne9sY"), Size: "14"},
408 - {Name: "t/foo", Path: p("QmfAjGiVpTN56TXi6SBQtstit5BEw3sijKj1Qkxn6EXKzJ"), Size: "14"},
409 - {Name: "t/abc", Path: p("QmU7nuGs2djqK99UNsNgEPGh6GV4662p6WtsgccBNGTDxt"), Size: "62"},
410 - {Name: "t", Path: p("QmVG2ZYCkV1S4TK8URA3a4RupBF17A8yAr4FqsRDXVJASr"), Size: "229"},
411 - },
412 - wrap: "t",
413 - },
414 - {
415 - name: "progress1M",
416 - data: func() files.Node {
417 - return files.NewReaderFile(bytes.NewReader(bytes.Repeat([]byte{0}, 1000000)))
418 - },
419 - path: "/ipfs/QmXXNNbwe4zzpdMg62ZXvnX1oU7MwSrQ3vAEtuwFKCm1oD",
420 - events: []coreiface.AddEvent{
421 - {Name: "", Bytes: 262144},
422 - {Name: "", Bytes: 524288},
423 - {Name: "", Bytes: 786432},
424 - {Name: "", Bytes: 1000000},
425 - {Name: "QmXXNNbwe4zzpdMg62ZXvnX1oU7MwSrQ3vAEtuwFKCm1oD", Path: p("QmXXNNbwe4zzpdMg62ZXvnX1oU7MwSrQ3vAEtuwFKCm1oD"), Size: "1000256"},
426 - },
427 - wrap: "",
428 - opts: []options.UnixfsAddOption{options.Unixfs.Progress(true)},
429 - },
430 - }
431 -
432 - for _, testCase := range cases {
433 - t.Run(testCase.name, func(t *testing.T) {
434 - ctx, cancel := context.WithCancel(ctx)
435 - defer cancel()
436 -
437 - // recursive logic
438 -
439 - data := testCase.data()
440 - if testCase.wrap != "" {
441 - data = files.NewMapDirectory(map[string]files.Node{
442 - testCase.wrap: data,
443 - })
444 - }
445 -
446 - // handle events if relevant to test case
447 -
448 - opts := testCase.opts
449 - eventOut := make(chan interface{})
450 - var evtWg sync.WaitGroup
451 - if len(testCase.events) > 0 {
452 - opts = append(opts, options.Unixfs.Events(eventOut))
453 - evtWg.Add(1)
454 -
455 - go func() {
456 - defer evtWg.Done()
457 - expected := testCase.events
458 -
459 - for evt := range eventOut {
460 - event, ok := evt.(*coreiface.AddEvent)
461 - if !ok {
462 - t.Fatal("unexpected event type")
463 - }
464 -
465 - if len(expected) < 1 {
466 - t.Fatal("got more events than expected")
467 - }
468 -
469 - if expected[0].Size != event.Size {
470 - t.Errorf("Event.Size didn't match, %s != %s", expected[0].Size, event.Size)
471 - }
472 -
473 - if expected[0].Name != event.Name {
474 - t.Errorf("Event.Name didn't match, %s != %s", expected[0].Name, event.Name)
475 - }
476 -
477 - if expected[0].Path != nil && event.Path != nil {
478 - if expected[0].Path.Cid().String() != event.Path.Cid().String() {
479 - t.Errorf("Event.Hash didn't match, %s != %s", expected[0].Path, event.Path)
480 - }
481 - } else if event.Path != expected[0].Path {
482 - t.Errorf("Event.Hash didn't match, %s != %s", expected[0].Path, event.Path)
483 - }
484 - if expected[0].Bytes != event.Bytes {
485 - t.Errorf("Event.Bytes didn't match, %d != %d", expected[0].Bytes, event.Bytes)
486 - }
487 -
488 - expected = expected[1:]
489 - }
490 -
491 - if len(expected) > 0 {
492 - t.Fatalf("%d event(s) didn't arrive", len(expected))
493 - }
494 - }()
495 - }
496 -
497 - tapi, err := api.WithOptions(testCase.apiOpts...)
498 - if err != nil {
499 - t.Fatal(err)
500 - }
501 -
502 - // Add!
503 -
504 - p, err := tapi.Unixfs().Add(ctx, data, opts...)
505 - close(eventOut)
506 - evtWg.Wait()
507 - if testCase.err != "" {
508 - if err == nil {
509 - t.Fatalf("expected an error: %s", testCase.err)
510 - }
511 - if err.Error() != testCase.err {
512 - t.Fatalf("expected an error: '%s' != '%s'", err.Error(), testCase.err)
513 - }
514 - return
515 - }
516 - if err != nil {
517 - t.Fatal(err)
518 - }
519 -
520 - if p.String() != testCase.path {
521 - t.Errorf("expected path %s, got: %s", testCase.path, p)
522 - }
523 -
524 - // compare file structure with Unixfs().Get
525 -
526 - var cmpFile func(origName string, orig files.Node, gotName string, got files.Node)
527 - cmpFile = func(origName string, orig files.Node, gotName string, got files.Node) {
528 - _, origDir := orig.(files.Directory)
529 - _, gotDir := got.(files.Directory)
530 -
531 - if origDir != gotDir {
532 - t.Fatal("file type mismatch")
533 - }
534 -
535 - if origName != gotName {
536 - t.Errorf("file name mismatch, orig='%s', got='%s'", origName, gotName)
537 - }
538 -
539 - if !gotDir {
540 - defer orig.Close()
541 - defer got.Close()
542 -
543 - do, err := ioutil.ReadAll(orig.(files.File))
544 - if err != nil {
545 - t.Fatal(err)
546 - }
547 -
548 - dg, err := ioutil.ReadAll(got.(files.File))
549 - if err != nil {
550 - t.Fatal(err)
551 - }
552 -
553 - if !bytes.Equal(do, dg) {
554 - t.Fatal("data not equal")
555 - }
556 -
557 - return
558 - }
559 -
560 - origIt := orig.(files.Directory).Entries()
561 - gotIt := got.(files.Directory).Entries()
562 -
563 - for {
564 - if origIt.Next() {
565 - if !gotIt.Next() {
566 - t.Fatal("gotIt out of entries before origIt")
567 - }
568 - } else {
569 - if gotIt.Next() {
570 - t.Fatal("origIt out of entries before gotIt")
571 - }
572 - break
573 - }
574 -
575 - cmpFile(origIt.Name(), origIt.Node(), gotIt.Name(), gotIt.Node())
576 - }
577 - if origIt.Err() != nil {
578 - t.Fatal(origIt.Err())
579 - }
580 - if gotIt.Err() != nil {
581 - t.Fatal(gotIt.Err())
582 - }
583 - }
584 -
585 - f, err := tapi.Unixfs().Get(ctx, p)
586 - if err != nil {
587 - t.Fatal(err)
588 - }
589 -
590 - orig := testCase.data()
591 - if testCase.expect != nil {
592 - orig = testCase.expect(orig)
593 - }
594 -
595 - cmpFile("", orig, "", f)
596 - })
597 - }
598 -}
599 -
600 -func (tp *provider) TestAddPinned(t *testing.T) {
601 - ctx, cancel := context.WithCancel(context.Background())
602 - defer cancel()
603 - api, err := tp.makeAPI(ctx)
604 - if err != nil {
605 - t.Error(err)
606 - }
607 -
608 - _, err = api.Unixfs().Add(ctx, strFile(helloStr)(), options.Unixfs.Pin(true))
609 - if err != nil {
610 - t.Error(err)
611 - }
612 -
613 - pins, err := api.Pin().Ls(ctx)
614 - if len(pins) != 1 {
615 - t.Fatalf("expected 1 pin, got %d", len(pins))
616 - }
617 -
618 - if pins[0].Path().String() != "/ipld/QmQy2Dw4Wk7rdJKjThjYXzfFJNaRKRHhHP5gHHXroJMYxk" {
619 - t.Fatalf("got unexpected pin: %s", pins[0].Path().String())
620 - }
621 -}
622 -
623 -func (tp *provider) TestAddHashOnly(t *testing.T) {
624 - ctx, cancel := context.WithCancel(context.Background())
625 - defer cancel()
626 - api, err := tp.makeAPI(ctx)
627 - if err != nil {
628 - t.Error(err)
629 - }
630 -
631 - p, err := api.Unixfs().Add(ctx, strFile(helloStr)(), options.Unixfs.HashOnly(true))
632 - if err != nil {
633 - t.Error(err)
634 - }
635 -
636 - if p.String() != hello {
637 - t.Errorf("unxepected path: %s", p.String())
638 - }
639 -
640 - _, err = api.Block().Get(ctx, p)
641 - if err == nil {
642 - t.Fatal("expected an error")
643 - }
644 - if !strings.Contains(err.Error(), "blockservice: key not found") {
645 - t.Errorf("unxepected error: %s", err.Error())
646 - }
647 -}
648 -
649 -func (tp *provider) TestGetEmptyFile(t *testing.T) {
650 - ctx, cancel := context.WithCancel(context.Background())
651 - defer cancel()
652 - api, err := tp.makeAPI(ctx)
653 - if err != nil {
654 - t.Fatal(err)
655 - }
656 -
657 - _, err = api.Unixfs().Add(ctx, files.NewBytesFile([]byte{}))
658 - if err != nil {
659 - t.Fatal(err)
660 - }
661 -
662 - emptyFilePath, err := coreiface.ParsePath(emptyFile)
663 - if err != nil {
664 - t.Fatal(err)
665 - }
666 -
667 - r, err := api.Unixfs().Get(ctx, emptyFilePath)
668 - if err != nil {
669 - t.Fatal(err)
670 - }
671 -
672 - buf := make([]byte, 1) // non-zero so that Read() actually tries to read
673 - n, err := io.ReadFull(r.(files.File), buf)
674 - if err != nil && err != io.EOF {
675 - t.Error(err)
676 - }
677 - if !bytes.HasPrefix(buf, []byte{0x00}) {
678 - t.Fatalf("expected empty data, got [%s] [read=%d]", buf, n)
679 - }
680 -}
681 -
682 -func (tp *provider) TestGetDir(t *testing.T) {
683 - ctx, cancel := context.WithCancel(context.Background())
684 - defer cancel()
685 - api, err := tp.makeAPI(ctx)
686 - if err != nil {
687 - t.Error(err)
688 - }
689 - edir := unixfs.EmptyDirNode()
690 - err = api.Dag().Add(ctx, edir)
691 - if err != nil {
692 - t.Error(err)
693 - }
694 - p := coreiface.IpfsPath(edir.Cid())
695 -
696 - emptyDir, err := api.Object().New(ctx, options.Object.Type("unixfs-dir"))
697 - if err != nil {
698 - t.Error(err)
699 - }
700 -
701 - if p.String() != coreiface.IpfsPath(emptyDir.Cid()).String() {
702 - t.Fatalf("expected path %s, got: %s", emptyDir.Cid(), p.String())
703 - }
704 -
705 - r, err := api.Unixfs().Get(ctx, coreiface.IpfsPath(emptyDir.Cid()))
706 - if err != nil {
707 - t.Error(err)
708 - }
709 -
710 - if _, ok := r.(files.Directory); !ok {
711 - t.Fatalf("expected a directory")
712 - }
713 -}
714 -
715 -func (tp *provider) TestGetNonUnixfs(t *testing.T) {
716 - ctx, cancel := context.WithCancel(context.Background())
717 - defer cancel()
718 - api, err := tp.makeAPI(ctx)
719 - if err != nil {
720 - t.Error(err)
721 - }
722 -
723 - nd := new(mdag.ProtoNode)
724 - err = api.Dag().Add(ctx, nd)
725 - if err != nil {
726 - t.Error(err)
727 - }
728 -
729 - _, err = api.Unixfs().Get(ctx, coreiface.IpfsPath(nd.Cid()))
730 - if !strings.Contains(err.Error(), "proto: required field") {
731 - t.Fatalf("expected protobuf error, got: %s", err)
732 - }
733 -}
734 -
735 -func (tp *provider) TestLs(t *testing.T) {
736 - ctx, cancel := context.WithCancel(context.Background())
737 - defer cancel()
738 - api, err := tp.makeAPI(ctx)
739 - if err != nil {
740 - t.Error(err)
741 - }
742 -
743 - r := strings.NewReader("content-of-file")
744 - p, err := api.Unixfs().Add(ctx, files.NewMapDirectory(map[string]files.Node{
745 - "0": files.NewMapDirectory(map[string]files.Node{
746 - "name-of-file": files.NewReaderFile(r),
747 - }),
748 - }))
749 - if err != nil {
750 - t.Error(err)
751 - }
752 -
753 - links, err := api.Unixfs().Ls(ctx, p)
754 - if err != nil {
755 - t.Error(err)
756 - }
757 -
758 - linkRes := <-links
759 - if linkRes.Err != nil {
760 - t.Fatal(linkRes.Err)
761 - }
762 - link := linkRes.Link
763 - if linkRes.Size != 15 {
764 - t.Fatalf("expected size = 15, got %d", link.Size)
765 - }
766 - if link.Name != "name-of-file" {
767 - t.Fatalf("expected name = name-of-file, got %s", link.Name)
768 - }
769 - if link.Cid.String() != "QmX3qQVKxDGz3URVC3861Z3CKtQKGBn6ffXRBBWGMFz9Lr" {
770 - t.Fatalf("expected cid = QmX3qQVKxDGz3URVC3861Z3CKtQKGBn6ffXRBBWGMFz9Lr, got %s", link.Cid)
771 - }
772 - if l, ok := <-links; ok {
773 - t.Errorf("didn't expect a second link")
774 - if l.Err != nil {
775 - t.Error(l.Err)
776 - }
777 - }
778 -}
779 -
780 -func (tp *provider) TestEntriesExpired(t *testing.T) {
781 - ctx, cancel := context.WithCancel(context.Background())
782 - defer cancel()
783 - api, err := tp.makeAPI(ctx)
784 - if err != nil {
785 - t.Error(err)
786 - }
787 -
788 - r := strings.NewReader("content-of-file")
789 - p, err := api.Unixfs().Add(ctx, files.NewMapDirectory(map[string]files.Node{
790 - "0": files.NewMapDirectory(map[string]files.Node{
791 - "name-of-file": files.NewReaderFile(r),
792 - }),
793 - }))
794 - if err != nil {
795 - t.Error(err)
796 - }
797 -
798 - ctx, cancel = context.WithCancel(ctx)
799 -
800 - nd, err := api.Unixfs().Get(ctx, p)
801 - if err != nil {
802 - t.Error(err)
803 - }
804 - cancel()
805 -
806 - it := files.ToDir(nd).Entries()
807 - if it == nil {
808 - t.Fatal("it was nil")
809 - }
810 -
811 - if it.Next() {
812 - t.Fatal("Next succeeded")
813 - }
814 -
815 - if it.Err() != context.Canceled {
816 - t.Fatalf("unexpected error %s", it.Err())
817 - }
818 -
819 - if it.Next() {
820 - t.Fatal("Next succeeded")
821 - }
822 -}
823 -
824 -func (tp *provider) TestLsEmptyDir(t *testing.T) {
825 - ctx, cancel := context.WithCancel(context.Background())
826 - defer cancel()
827 - api, err := tp.makeAPI(ctx)
828 - if err != nil {
829 - t.Error(err)
830 - }
831 -
832 - _, err = api.Unixfs().Add(ctx, files.NewMapDirectory(map[string]files.Node{"0": files.NewSliceDirectory([]files.DirEntry{})}))
833 - if err != nil {
834 - t.Error(err)
835 - }
836 -
837 - emptyDir, err := api.Object().New(ctx, options.Object.Type("unixfs-dir"))
838 - if err != nil {
839 - t.Error(err)
840 - }
841 -
842 - links, err := api.Unixfs().Ls(ctx, coreiface.IpfsPath(emptyDir.Cid()))
843 - if err != nil {
844 - t.Error(err)
845 - }
846 -
847 - if len(links) != 0 {
848 - t.Fatalf("expected 0 links, got %d", len(links))
849 - }
850 -}
851 -
852 -// TODO(lgierth) this should test properly, with len(links) > 0
853 -func (tp *provider) TestLsNonUnixfs(t *testing.T) {
854 - ctx, cancel := context.WithCancel(context.Background())
855 - defer cancel()
856 - api, err := tp.makeAPI(ctx)
857 - if err != nil {
858 - t.Error(err)
859 - }
860 -
861 - nd, err := cbor.WrapObject(map[string]interface{}{"foo": "bar"}, math.MaxUint64, -1)
862 - if err != nil {
863 - t.Fatal(err)
864 - }
865 -
866 - err = api.Dag().Add(ctx, nd)
867 - if err != nil {
868 - t.Error(err)
869 - }
870 -
871 - links, err := api.Unixfs().Ls(ctx, coreiface.IpfsPath(nd.Cid()))
872 - if err != nil {
873 - t.Error(err)
874 - }
875 -
876 - if len(links) != 0 {
877 - t.Fatalf("expected 0 links, got %d", len(links))
878 - }
879 -}
880 -
881 -type closeTestF struct {
882 - files.File
883 - closed bool
884 -
885 - t *testing.T
886 -}
887 -
888 -type closeTestD struct {
889 - files.Directory
890 - closed bool
891 -
892 - t *testing.T
893 -}
894 -
895 -func (f *closeTestD) Close() error {
896 - if f.closed {
897 - f.t.Fatal("already closed")
898 - }
899 - f.closed = true
900 - return nil
901 -}
902 -
903 -func (f *closeTestF) Close() error {
904 - if f.closed {
905 - f.t.Fatal("already closed")
906 - }
907 - f.closed = true
908 - return nil
909 -}
910 -
911 -func (tp *provider) TestAddCloses(t *testing.T) {
912 - ctx, cancel := context.WithCancel(context.Background())
913 - defer cancel()
914 - api, err := tp.makeAPI(ctx)
915 - if err != nil {
916 - t.Error(err)
917 - }
918 -
919 - n4 := &closeTestF{files.NewBytesFile([]byte("foo")), false, t}
920 - d3 := &closeTestD{files.NewMapDirectory(map[string]files.Node{
921 - "sub": n4,
922 - }), false, t}
923 - n2 := &closeTestF{files.NewBytesFile([]byte("bar")), false, t}
924 - n1 := &closeTestF{files.NewBytesFile([]byte("baz")), false, t}
925 - d0 := &closeTestD{files.NewMapDirectory(map[string]files.Node{
926 - "a": d3,
927 - "b": n1,
928 - "c": n2,
929 - }), false, t}
930 -
931 - _, err = api.Unixfs().Add(ctx, d0)
932 - if err != nil {
933 - t.Error(err)
934 - }
935 -
936 - d0.Close() // Adder doesn't close top-level file
937 -
938 - for i, n := range []*closeTestF{n1, n2, n4} {
939 - if !n.closed {
940 - t.Errorf("file %d not closed!", i)
941 - }
942 - }
943 -
944 - for i, n := range []*closeTestD{d0, d3} {
945 - if !n.closed {
946 - t.Errorf("dir %d not closed!", i)
947 - }
948 - }
949 -}
950 -
951 -func (tp *provider) TestGetSeek(t *testing.T) {
952 - ctx, cancel := context.WithCancel(context.Background())
953 - defer cancel()
954 - api, err := tp.makeAPI(ctx)
955 - if err != nil {
956 - t.Error(err)
957 - }
958 -
959 - dataSize := int64(100000)
960 - tf := files.NewReaderFile(io.LimitReader(rand.New(rand.NewSource(1403768328)), dataSize))
961 -
962 - p, err := api.Unixfs().Add(ctx, tf, options.Unixfs.Chunker("size-100"))
963 - if err != nil {
964 - t.Fatal(err)
965 - }
966 -
967 - r, err := api.Unixfs().Get(ctx, p)
968 - if err != nil {
969 - t.Fatal(err)
970 - }
971 -
972 - f := files.ToFile(r)
973 - if f == nil {
974 - t.Fatal("not a file")
975 - }
976 -
977 - orig := make([]byte, dataSize)
978 - if _, err := io.ReadFull(f, orig); err != nil {
979 - t.Fatal(err)
980 - }
981 - f.Close()
982 -
983 - origR := bytes.NewReader(orig)
984 -
985 - r, err = api.Unixfs().Get(ctx, p)
986 - if err != nil {
987 - t.Fatal(err)
988 - }
989 -
990 - f = files.ToFile(r)
991 - if f == nil {
992 - t.Fatal("not a file")
993 - }
994 -
995 - test := func(offset int64, whence int, read int, expect int64, shouldEof bool) {
996 - t.Run(fmt.Sprintf("seek%d+%d-r%d-%d", whence, offset, read, expect), func(t *testing.T) {
997 - n, err := f.Seek(offset, whence)
998 - if err != nil {
999 - t.Fatal(err)
1000 - }
1001 - origN, err := origR.Seek(offset, whence)
1002 - if err != nil {
1003 - t.Fatal(err)
1004 - }
1005 -
1006 - if n != origN {
1007 - t.Fatalf("offsets didn't match, expected %d, got %d", origN, n)
1008 - }
1009 -
1010 - buf := make([]byte, read)
1011 - origBuf := make([]byte, read)
1012 - origRead, err := origR.Read(origBuf)
1013 - if err != nil {
1014 - t.Fatalf("orig: %s", err)
1015 - }
1016 - r, err := io.ReadFull(f, buf)
1017 - switch {
1018 - case shouldEof && err != nil && err != io.ErrUnexpectedEOF:
1019 - fallthrough
1020 - case !shouldEof && err != nil:
1021 - t.Fatalf("f: %s", err)
1022 - case shouldEof:
1023 - _, err := f.Read([]byte{0})
1024 - if err != io.EOF {
1025 - t.Fatal("expected EOF")
1026 - }
1027 - _, err = origR.Read([]byte{0})
1028 - if err != io.EOF {
1029 - t.Fatal("expected EOF (orig)")
1030 - }
1031 - }
1032 -
1033 - if int64(r) != expect {
1034 - t.Fatal("read wrong amount of data")
1035 - }
1036 - if r != origRead {
1037 - t.Fatal("read different amount of data than bytes.Reader")
1038 - }
1039 - if !bytes.Equal(buf, origBuf) {
1040 - fmt.Fprintf(os.Stderr, "original:\n%s\n", hex.Dump(origBuf))
1041 - fmt.Fprintf(os.Stderr, "got:\n%s\n", hex.Dump(buf))
1042 - t.Fatal("data didn't match")
1043 - }
1044 - })
1045 - }
1046 -
1047 - test(3, io.SeekCurrent, 10, 10, false)
1048 - test(3, io.SeekCurrent, 10, 10, false)
1049 - test(500, io.SeekCurrent, 10, 10, false)
1050 - test(350, io.SeekStart, 100, 100, false)
1051 - test(-123, io.SeekCurrent, 100, 100, false)
1052 - test(0, io.SeekStart, int(dataSize), dataSize, false)
1053 - test(dataSize-50, io.SeekStart, 100, 50, true)
1054 - test(-5, io.SeekEnd, 100, 5, true)
1055 -}
core/coreapi/interface/unixfs.go deleted
-55
@@ -1,55 +0,0 @@
1 -package iface
2 -
3 -import (
4 - "context"
5 - "github.com/ipfs/go-ipfs/core/coreapi/interface/options"
6 -
7 - ipld "gx/ipfs/QmRL22E4paat7ky7vx9MLpR97JHHbFPrg3ytFQw6qp1y1s/go-ipld-format"
8 - "gx/ipfs/QmZArMcsVDsXdcLbUx4844CuqKXBpbxdeiryM4cnmGTNRq/go-unixfs"
9 - "gx/ipfs/QmaXvvAVAQ5ABqM5xtjYmV85xmN5MkWAZsX9H9Fwo4FVXp/go-ipfs-files"
10 -)
11 -
12 -type AddEvent struct {
13 - Name string
14 - Path ResolvedPath `json:",omitempty"`
15 - Bytes int64 `json:",omitempty"`
16 - Size string `json:",omitempty"`
17 -}
18 -
19 -type FileType int32
20 -
21 -const (
22 - TRaw = FileType(unixfs.TRaw)
23 - TFile = FileType(unixfs.TFile)
24 - TDirectory = FileType(unixfs.TDirectory)
25 - TMetadata = FileType(unixfs.TMetadata)
26 - TSymlink = FileType(unixfs.TSymlink)
27 - THAMTShard = FileType(unixfs.THAMTShard)
28 -)
29 -
30 -type LsLink struct {
31 - Link *ipld.Link
32 - Size uint64
33 - Type FileType
34 -
35 - Err error
36 -}
37 -
38 -// UnixfsAPI is the basic interface to immutable files in IPFS
39 -// NOTE: This API is heavily WIP, things are guaranteed to break frequently
40 -type UnixfsAPI interface {
41 - // Add imports the data from the reader into merkledag file
42 - //
43 - // TODO: a long useful comment on how to use this for many different scenarios
44 - Add(context.Context, files.Node, ...options.UnixfsAddOption) (ResolvedPath, error)
45 -
46 - // Get returns a read-only handle to a file tree referenced by a path
47 - //
48 - // Note that some implementations of this API may apply the specified context
49 - // to operations performed on the returned file
50 - Get(context.Context, Path) (files.Node, error)
51 -
52 - // Ls returns the list of links in a directory. Links aren't guaranteed to be
53 - // returned in order
54 - Ls(context.Context, Path, ...options.UnixfsLsOption) (<-chan LsLink, error)
55 -}
core/coreapi/interface/util.go deleted
-20
@@ -1,20 +0,0 @@
1 -package iface
2 -
3 -import (
4 - "context"
5 - "io"
6 -)
7 -
8 -type Reader interface {
9 - ReadSeekCloser
10 - Size() uint64
11 - CtxReadFull(context.Context, []byte) (int, error)
12 -}
13 -
14 -// A ReadSeekCloser implements interfaces to read, copy, seek and close.
15 -type ReadSeekCloser interface {
16 - io.Reader
17 - io.Seeker
18 - io.Closer
19 - io.WriterTo
20 -}