forked from berty/go-orbit-db
/
address.go
78 lines (60 loc) · 1.53 KB
/
address.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package address
import (
"fmt"
"path"
"strings"
cid "github.com/ipfs/go-cid"
"github.com/pkg/errors"
)
// Address A store address
type Address interface {
// GetRoot Returns the root CID for the store
GetRoot() cid.Cid
// GetPath Returns the path for the store
GetPath() string
// String Returns the whole address for the store as a string
String() string
}
type address struct {
root cid.Cid
path string
}
func (a *address) String() string {
return path.Join("/orbitdb", a.root.String(), a.path)
}
func (a *address) GetRoot() cid.Cid {
return a.root
}
func (a *address) GetPath() string {
return a.path
}
// IsValid Checks if a given name is a valid address
func IsValid(name string) error {
name = strings.TrimPrefix(name, "/orbitdb/")
parts := strings.Split(name, "/")
var accessControllerHash cid.Cid
accessControllerHash, err := cid.Decode(parts[0])
if err != nil {
return fmt.Errorf("address is invalid: %w", err)
}
if accessControllerHash.String() == "" {
return fmt.Errorf("address is invalid")
}
return nil
}
// Parse Returns an Address instance if the given path is valid
func Parse(path string) (Address, error) {
if err := IsValid(path); err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("not a valid OrbitDB address: %s", path))
}
path = strings.TrimPrefix(path, "/orbitdb/")
parts := strings.Split(path, "/")
c, err := cid.Decode(parts[0])
if err != nil {
return nil, fmt.Errorf("unable to parse CID: %w", err)
}
return &address{
root: c,
path: strings.Join(parts[1:], "/"),
}, nil
}