node.go 7.29 KB
Newer Older
1 2 3
package merkledag

import (
4
	"context"
5
	"encoding/json"
Jeromy's avatar
Jeromy committed
6
	"fmt"
Jeromy's avatar
Jeromy committed
7

8 9 10
	mh "gx/ipfs/QmVGtdTZdTFaLsaj2RwdVG8jcjNNcp1DE914DKZ2kHmXHw/go-multihash"
	cid "gx/ipfs/QmYhQaCYEcaPPjxJX7YcPcVKkQfRy6sJ7B3XmGFk82XYdQ/go-cid"
	node "gx/ipfs/Qmb3Hm9QDFmfYuET4pu7Kyg8JV78jFa1nvZx5vnCZsK4ck/go-ipld-format"
11 12
)

Jeromy's avatar
Jeromy committed
13
var ErrNotProtobuf = fmt.Errorf("expected protobuf dag node")
14 15
var ErrLinkNotFound = fmt.Errorf("no link by that name")

16 17
// Node represents a node in the IPFS Merkle DAG.
// nodes have opaque data and a set of navigable links.
18
type ProtoNode struct {
Jeromy's avatar
Jeromy committed
19
	links []*node.Link
20
	data  []byte
21 22 23 24

	// cache encoded/marshaled value
	encoded []byte

Jeromy's avatar
Jeromy committed
25
	cached *cid.Cid
26

27 28 29 30
	// Prefix specifies cid version and hashing function
	Prefix cid.Prefix
}

31
var v0CidPrefix = cid.Prefix{
32 33 34 35
	Codec:    cid.DagProtobuf,
	MhLength: -1,
	MhType:   mh.SHA2_256,
	Version:  0,
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
var v1CidPrefix = cid.Prefix{
	Codec:    cid.DagProtobuf,
	MhLength: -1,
	MhType:   mh.SHA2_256,
	Version:  1,
}

func PrefixForCidVersion(version int) (cid.Prefix, error) {
	switch version {
	case 0:
		return v0CidPrefix, nil
	case 1:
		return v1CidPrefix, nil
	default:
		return cid.Prefix{}, fmt.Errorf("unknown CID version: %d", version)
	}
}

func (n *ProtoNode) SetPrefix(prefix cid.Prefix) {
	n.Prefix = prefix
	n.encoded = nil
	n.cached = nil
}

Jeromy's avatar
Jeromy committed
62
type LinkSlice []*node.Link
63 64 65 66 67

func (ls LinkSlice) Len() int           { return len(ls) }
func (ls LinkSlice) Swap(a, b int)      { ls[a], ls[b] = ls[b], ls[a] }
func (ls LinkSlice) Less(a, b int) bool { return ls[a].Name < ls[b].Name }

68 69
func NodeWithData(d []byte) *ProtoNode {
	return &ProtoNode{data: d}
70 71
}

72
// AddNodeLink adds a link to another node.
73
func (n *ProtoNode) AddNodeLink(name string, that node.Node) error {
74
	n.encoded = nil
75

Jeromy's avatar
Jeromy committed
76
	lnk, err := node.MakeLink(that)
77 78 79 80
	if err != nil {
		return err
	}

Jeromy's avatar
Jeromy committed
81 82
	lnk.Name = name

83 84
	n.AddRawLink(name, lnk)

85 86 87
	return nil
}

88
// AddNodeLinkClean adds a link to another node. without keeping a reference to
89
// the child node
Jeromy's avatar
Jeromy committed
90
func (n *ProtoNode) AddNodeLinkClean(name string, that node.Node) error {
91
	n.encoded = nil
Jeromy's avatar
Jeromy committed
92
	lnk, err := node.MakeLink(that)
93 94 95
	if err != nil {
		return err
	}
96 97 98 99 100 101
	n.AddRawLink(name, lnk)

	return nil
}

// AddRawLink adds a copy of a link to this node
Jeromy's avatar
Jeromy committed
102
func (n *ProtoNode) AddRawLink(name string, l *node.Link) error {
103
	n.encoded = nil
Jeromy's avatar
Jeromy committed
104
	n.links = append(n.links, &node.Link{
105 106
		Name: name,
		Size: l.Size,
107
		Cid:  l.Cid,
108
	})
109 110 111 112 113

	return nil
}

// Remove a link on this node by the given name
114
func (n *ProtoNode) RemoveNodeLink(name string) error {
115
	n.encoded = nil
Jeromy's avatar
Jeromy committed
116
	good := make([]*node.Link, 0, len(n.links))
Jeromy's avatar
Jeromy committed
117 118
	var found bool

119
	for _, l := range n.links {
Jeromy's avatar
Jeromy committed
120 121 122 123
		if l.Name != name {
			good = append(good, l)
		} else {
			found = true
124 125
		}
	}
126
	n.links = good
Jeromy's avatar
Jeromy committed
127 128 129 130 131 132

	if !found {
		return ErrNotFound
	}

	return nil
133 134
}

135
// Return a copy of the link with given name
Jeromy's avatar
Jeromy committed
136
func (n *ProtoNode) GetNodeLink(name string) (*node.Link, error) {
137
	for _, l := range n.links {
138
		if l.Name == name {
Jeromy's avatar
Jeromy committed
139
			return &node.Link{
140 141
				Name: l.Name,
				Size: l.Size,
142
				Cid:  l.Cid,
143 144 145
			}, nil
		}
	}
146
	return nil, ErrLinkNotFound
147 148
}

149 150 151 152 153 154 155 156 157 158 159 160 161 162
func (n *ProtoNode) GetLinkedProtoNode(ctx context.Context, ds DAGService, name string) (*ProtoNode, error) {
	nd, err := n.GetLinkedNode(ctx, ds, name)
	if err != nil {
		return nil, err
	}

	pbnd, ok := nd.(*ProtoNode)
	if !ok {
		return nil, ErrNotProtobuf
	}

	return pbnd, nil
}

Jeromy's avatar
Jeromy committed
163
func (n *ProtoNode) GetLinkedNode(ctx context.Context, ds DAGService, name string) (node.Node, error) {
164 165 166 167 168 169 170 171
	lnk, err := n.GetNodeLink(name)
	if err != nil {
		return nil, err
	}

	return lnk.GetNode(ctx, ds)
}

172
// Copy returns a copy of the node.
173
// NOTE: Does not make copies of Node objects in the links.
174
func (n *ProtoNode) Copy() node.Node {
175
	nnode := new(ProtoNode)
176 177 178
	if len(n.data) > 0 {
		nnode.data = make([]byte, len(n.data))
		copy(nnode.data, n.data)
Jeromy's avatar
Jeromy committed
179
	}
180

181
	if len(n.links) > 0 {
Jeromy's avatar
Jeromy committed
182
		nnode.links = make([]*node.Link, len(n.links))
183
		copy(nnode.links, n.links)
Jeromy's avatar
Jeromy committed
184
	}
185 186 187

	nnode.Prefix = n.Prefix

188 189 190
	return nnode
}

191
func (n *ProtoNode) RawData() []byte {
Jeromy's avatar
Jeromy committed
192 193 194 195
	out, _ := n.EncodeProtobuf(false)
	return out
}

196
func (n *ProtoNode) Data() []byte {
197 198 199
	return n.data
}

200
func (n *ProtoNode) SetData(d []byte) {
201 202 203 204 205
	n.encoded = nil
	n.cached = nil
	n.data = d
}

206 207
// UpdateNodeLink return a copy of the node with the link name set to point to
// that. If a link of the same name existed, it is removed.
208
func (n *ProtoNode) UpdateNodeLink(name string, that *ProtoNode) (*ProtoNode, error) {
209
	newnode := n.Copy().(*ProtoNode)
210 211 212 213 214 215
	err := newnode.RemoveNodeLink(name)
	err = nil // ignore error
	err = newnode.AddNodeLink(name, that)
	return newnode, err
}

216 217
// Size returns the total size of the data addressed by node,
// including the total sizes of references.
218
func (n *ProtoNode) Size() (uint64, error) {
219
	b, err := n.EncodeProtobuf(false)
220 221 222 223 224
	if err != nil {
		return 0, err
	}

	s := uint64(len(b))
225
	for _, l := range n.links {
226 227 228 229 230 231
		s += l.Size
	}
	return s, nil
}

// Stat returns statistics on the node.
Jeromy's avatar
Jeromy committed
232
func (n *ProtoNode) Stat() (*node.NodeStat, error) {
233
	enc, err := n.EncodeProtobuf(false)
234
	if err != nil {
235
		return nil, err
236 237 238 239
	}

	cumSize, err := n.Size()
	if err != nil {
240
		return nil, err
241 242
	}

Jeromy's avatar
Jeromy committed
243
	return &node.NodeStat{
Jeromy's avatar
Jeromy committed
244
		Hash:           n.Cid().String(),
245
		NumLinks:       len(n.links),
246
		BlockSize:      len(enc),
247 248
		LinksSize:      len(enc) - len(n.data), // includes framing.
		DataSize:       len(n.data),
249 250 251 252
		CumulativeSize: int(cumSize),
	}, nil
}

253
func (n *ProtoNode) Loggable() map[string]interface{} {
Jeromy's avatar
Jeromy committed
254 255 256 257 258
	return map[string]interface{}{
		"node": n.String(),
	}
}

Jeromy's avatar
Jeromy committed
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
func (n *ProtoNode) UnmarshalJSON(b []byte) error {
	s := struct {
		Data  []byte       `json:"data"`
		Links []*node.Link `json:"links"`
	}{}

	err := json.Unmarshal(b, &s)
	if err != nil {
		return err
	}

	n.data = s.Data
	n.links = s.Links
	return nil
}

275 276 277 278 279 280 281 282 283
func (n *ProtoNode) MarshalJSON() ([]byte, error) {
	out := map[string]interface{}{
		"data":  n.data,
		"links": n.links,
	}

	return json.Marshal(out)
}

284
func (n *ProtoNode) Cid() *cid.Cid {
285 286 287 288 289
	if n.encoded != nil && n.cached != nil {
		return n.cached
	}

	if n.Prefix.Codec == 0 {
290
		n.Prefix = v0CidPrefix
291 292 293 294 295
	}

	c, err := n.Prefix.Sum(n.RawData())
	if err != nil {
		// programmer error
296
		err = fmt.Errorf("invalid CID of length %d: %x: %v", len(n.RawData()), n.RawData(), err)
297 298
		panic(err)
	}
Jeromy's avatar
Jeromy committed
299

300 301
	n.cached = c
	return c
Jeromy's avatar
Jeromy committed
302 303
}

304
func (n *ProtoNode) String() string {
Jeromy's avatar
Jeromy committed
305 306 307
	return n.Cid().String()
}

308
// Multihash hashes the encoded data of this node.
309
func (n *ProtoNode) Multihash() mh.Multihash {
310
	// NOTE: EncodeProtobuf generates the hash and puts it in n.cached.
311
	_, err := n.EncodeProtobuf(false)
312
	if err != nil {
Jeromy's avatar
Jeromy committed
313 314
		// Note: no possibility exists for an error to be returned through here
		panic(err)
315 316
	}

Jeromy's avatar
Jeromy committed
317
	return n.cached.Hash()
318
}
319

Jeromy's avatar
Jeromy committed
320
func (n *ProtoNode) Links() []*node.Link {
321 322 323
	return n.links
}

Jeromy's avatar
Jeromy committed
324
func (n *ProtoNode) SetLinks(links []*node.Link) {
325 326 327
	n.links = links
}

328 329 330 331 332
func (n *ProtoNode) Resolve(path []string) (interface{}, []string, error) {
	return n.ResolveLink(path)
}

func (n *ProtoNode) ResolveLink(path []string) (*node.Link, []string, error) {
333 334 335 336 337 338 339 340 341 342 343 344
	if len(path) == 0 {
		return nil, nil, fmt.Errorf("end of path, no more links to resolve")
	}

	lnk, err := n.GetNodeLink(path[0])
	if err != nil {
		return nil, nil, err
	}

	return lnk, path[1:], nil
}

345 346 347 348 349 350 351
func (n *ProtoNode) Tree(p string, depth int) []string {
	// ProtoNodes are only ever one path deep, anything below that results in
	// nothing
	if p != "" {
		return nil
	}

352 353 354 355 356 357
	out := make([]string, 0, len(n.links))
	for _, lnk := range n.links {
		out = append(out, lnk.Name)
	}
	return out
}