node.go 7.48 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
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)
	}
}

56 57 58 59 60 61 62 63 64 65 66
// SetPrefix sets the prefix if it is non nil, if prefix is nil then
// it resets it the default value
func (n *ProtoNode) SetPrefix(prefix *cid.Prefix) {
	if prefix == nil {
		n.Prefix = v0CidPrefix
	} else {
		n.Prefix = *prefix
		n.Prefix.Codec = cid.DagProtobuf
		n.encoded = nil
		n.cached = nil
	}
67 68
}

Jeromy's avatar
Jeromy committed
69
type LinkSlice []*node.Link
70 71 72 73 74

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 }

75 76
func NodeWithData(d []byte) *ProtoNode {
	return &ProtoNode{data: d}
77 78
}

79
// AddNodeLink adds a link to another node.
80
func (n *ProtoNode) AddNodeLink(name string, that node.Node) error {
81
	n.encoded = nil
82

Jeromy's avatar
Jeromy committed
83
	lnk, err := node.MakeLink(that)
84 85 86 87
	if err != nil {
		return err
	}

Jeromy's avatar
Jeromy committed
88 89
	lnk.Name = name

90 91
	n.AddRawLink(name, lnk)

92 93 94
	return nil
}

95
// AddNodeLinkClean adds a link to another node. without keeping a reference to
96
// the child node
Jeromy's avatar
Jeromy committed
97
func (n *ProtoNode) AddNodeLinkClean(name string, that node.Node) error {
98
	n.encoded = nil
Jeromy's avatar
Jeromy committed
99
	lnk, err := node.MakeLink(that)
100 101 102
	if err != nil {
		return err
	}
103 104 105 106 107 108
	n.AddRawLink(name, lnk)

	return nil
}

// AddRawLink adds a copy of a link to this node
Jeromy's avatar
Jeromy committed
109
func (n *ProtoNode) AddRawLink(name string, l *node.Link) error {
110
	n.encoded = nil
Jeromy's avatar
Jeromy committed
111
	n.links = append(n.links, &node.Link{
112 113
		Name: name,
		Size: l.Size,
114
		Cid:  l.Cid,
115
	})
116 117 118 119 120

	return nil
}

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

126
	for _, l := range n.links {
Jeromy's avatar
Jeromy committed
127 128 129 130
		if l.Name != name {
			good = append(good, l)
		} else {
			found = true
131 132
		}
	}
133
	n.links = good
Jeromy's avatar
Jeromy committed
134 135 136 137 138 139

	if !found {
		return ErrNotFound
	}

	return nil
140 141
}

142
// Return a copy of the link with given name
Jeromy's avatar
Jeromy committed
143
func (n *ProtoNode) GetNodeLink(name string) (*node.Link, error) {
144
	for _, l := range n.links {
145
		if l.Name == name {
Jeromy's avatar
Jeromy committed
146
			return &node.Link{
147 148
				Name: l.Name,
				Size: l.Size,
149
				Cid:  l.Cid,
150 151 152
			}, nil
		}
	}
153
	return nil, ErrLinkNotFound
154 155
}

156 157 158 159 160 161 162 163 164 165 166 167 168 169
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
170
func (n *ProtoNode) GetLinkedNode(ctx context.Context, ds DAGService, name string) (node.Node, error) {
171 172 173 174 175 176 177 178
	lnk, err := n.GetNodeLink(name)
	if err != nil {
		return nil, err
	}

	return lnk.GetNode(ctx, ds)
}

179
// Copy returns a copy of the node.
180
// NOTE: Does not make copies of Node objects in the links.
181
func (n *ProtoNode) Copy() node.Node {
182
	nnode := new(ProtoNode)
183 184 185
	if len(n.data) > 0 {
		nnode.data = make([]byte, len(n.data))
		copy(nnode.data, n.data)
Jeromy's avatar
Jeromy committed
186
	}
187

188
	if len(n.links) > 0 {
Jeromy's avatar
Jeromy committed
189
		nnode.links = make([]*node.Link, len(n.links))
190
		copy(nnode.links, n.links)
Jeromy's avatar
Jeromy committed
191
	}
192 193 194

	nnode.Prefix = n.Prefix

195 196 197
	return nnode
}

198
func (n *ProtoNode) RawData() []byte {
Jeromy's avatar
Jeromy committed
199 200 201 202
	out, _ := n.EncodeProtobuf(false)
	return out
}

203
func (n *ProtoNode) Data() []byte {
204 205 206
	return n.data
}

207
func (n *ProtoNode) SetData(d []byte) {
208 209 210 211 212
	n.encoded = nil
	n.cached = nil
	n.data = d
}

213 214
// 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.
215
func (n *ProtoNode) UpdateNodeLink(name string, that *ProtoNode) (*ProtoNode, error) {
216
	newnode := n.Copy().(*ProtoNode)
217 218 219 220 221 222
	err := newnode.RemoveNodeLink(name)
	err = nil // ignore error
	err = newnode.AddNodeLink(name, that)
	return newnode, err
}

223 224
// Size returns the total size of the data addressed by node,
// including the total sizes of references.
225
func (n *ProtoNode) Size() (uint64, error) {
226
	b, err := n.EncodeProtobuf(false)
227 228 229 230 231
	if err != nil {
		return 0, err
	}

	s := uint64(len(b))
232
	for _, l := range n.links {
233 234 235 236 237 238
		s += l.Size
	}
	return s, nil
}

// Stat returns statistics on the node.
Jeromy's avatar
Jeromy committed
239
func (n *ProtoNode) Stat() (*node.NodeStat, error) {
240
	enc, err := n.EncodeProtobuf(false)
241
	if err != nil {
242
		return nil, err
243 244 245 246
	}

	cumSize, err := n.Size()
	if err != nil {
247
		return nil, err
248 249
	}

Jeromy's avatar
Jeromy committed
250
	return &node.NodeStat{
Jeromy's avatar
Jeromy committed
251
		Hash:           n.Cid().String(),
252
		NumLinks:       len(n.links),
253
		BlockSize:      len(enc),
254 255
		LinksSize:      len(enc) - len(n.data), // includes framing.
		DataSize:       len(n.data),
256 257 258 259
		CumulativeSize: int(cumSize),
	}, nil
}

260
func (n *ProtoNode) Loggable() map[string]interface{} {
Jeromy's avatar
Jeromy committed
261 262 263 264 265
	return map[string]interface{}{
		"node": n.String(),
	}
}

Jeromy's avatar
Jeromy committed
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
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
}

282 283 284 285 286 287 288 289 290
func (n *ProtoNode) MarshalJSON() ([]byte, error) {
	out := map[string]interface{}{
		"data":  n.data,
		"links": n.links,
	}

	return json.Marshal(out)
}

291
func (n *ProtoNode) Cid() *cid.Cid {
292 293 294 295 296
	if n.encoded != nil && n.cached != nil {
		return n.cached
	}

	if n.Prefix.Codec == 0 {
297
		n.SetPrefix(nil)
298 299 300 301 302
	}

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

307 308
	n.cached = c
	return c
Jeromy's avatar
Jeromy committed
309 310
}

311
func (n *ProtoNode) String() string {
Jeromy's avatar
Jeromy committed
312 313 314
	return n.Cid().String()
}

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

Jeromy's avatar
Jeromy committed
324
	return n.cached.Hash()
325
}
326

Jeromy's avatar
Jeromy committed
327
func (n *ProtoNode) Links() []*node.Link {
328 329 330
	return n.links
}

Jeromy's avatar
Jeromy committed
331
func (n *ProtoNode) SetLinks(links []*node.Link) {
332 333 334
	n.links = links
}

335 336 337 338 339
func (n *ProtoNode) Resolve(path []string) (interface{}, []string, error) {
	return n.ResolveLink(path)
}

func (n *ProtoNode) ResolveLink(path []string) (*node.Link, []string, error) {
340 341 342 343 344 345 346 347 348 349 350 351
	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
}

352 353 354 355 356 357 358
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
	}

359 360 361 362 363 364
	out := make([]string, 0, len(n.links))
	for _, lnk := range n.links {
		out = append(out, lnk.Name)
	}
	return out
}