node.go 5.9 KB
Newer Older
1 2 3 4 5
package merkledag

import (
	"fmt"

6
	"context"
Jeromy's avatar
Jeromy committed
7

8
	cid "gx/ipfs/QmXUuRadqDq5BuFWzVU6VuKaSjTcNm1gNCtLvvP1TJCW4z/go-cid"
9 10
	mh "gx/ipfs/QmYDds3421prZgqKbLpEK7T9Aa2eVdQ7o3YarX1LVLdP2J/go-multihash"
	key "gx/ipfs/QmYEoKZXHoAToWfhGF3vryhMn3WWhE1o2MasQ8uzY5iDi9/go-key"
11 12
)

13 14
var ErrLinkNotFound = fmt.Errorf("no link by that name")

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

	// cache encoded/marshaled value
	encoded []byte

Jeromy's avatar
Jeromy committed
24
	cached *cid.Cid
25 26 27 28
}

// NodeStat is a statistics object for a Node. Mostly sizes.
type NodeStat struct {
29
	Hash           string
30
	NumLinks       int // number of links in link table
31
	BlockSize      int // size of the raw, encoded data
32 33
	LinksSize      int // size of the links segment
	DataSize       int // size of the data segment
34
	CumulativeSize int // cumulative size of object and its references
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
}

func (ns NodeStat) String() string {
	f := "NodeStat{NumLinks: %d, BlockSize: %d, LinksSize: %d, DataSize: %d, CumulativeSize: %d}"
	return fmt.Sprintf(f, ns.NumLinks, ns.BlockSize, ns.LinksSize, ns.DataSize, ns.CumulativeSize)
}

// Link represents an IPFS Merkle DAG Link between Nodes.
type Link struct {
	// utf string name. should be unique per object
	Name string // utf8

	// cumulative size of target object
	Size uint64

	// multihash of the target object
	Hash mh.Multihash
}

type LinkSlice []*Link

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 }

// MakeLink creates a link to the given node
func MakeLink(n *Node) (*Link, error) {
	s, err := n.Size()
	if err != nil {
		return nil, err
	}

Jeromy's avatar
Jeromy committed
67 68
	h := n.Multihash()

69 70 71 72 73 74 75
	return &Link{
		Size: s,
		Hash: h,
	}, nil
}

// GetNode returns the MDAG Node that this link points to
Jeromy's avatar
Jeromy committed
76
func (l *Link) GetNode(ctx context.Context, serv DAGService) (*Node, error) {
Jeromy's avatar
Jeromy committed
77
	return serv.Get(ctx, legacyCidFromLink(l))
78 79
}

80 81 82 83
func NodeWithData(d []byte) *Node {
	return &Node{data: d}
}

84 85
// AddNodeLink adds a link to another node.
func (n *Node) AddNodeLink(name string, that *Node) error {
86
	n.encoded = nil
87

88
	lnk, err := MakeLink(that)
89 90

	lnk.Name = name
91 92 93 94
	if err != nil {
		return err
	}

95 96
	n.AddRawLink(name, lnk)

97 98 99
	return nil
}

100
// AddNodeLinkClean adds a link to another node. without keeping a reference to
101 102
// the child node
func (n *Node) AddNodeLinkClean(name string, that *Node) error {
103
	n.encoded = nil
104 105 106 107
	lnk, err := MakeLink(that)
	if err != nil {
		return err
	}
108 109 110 111 112 113 114 115 116 117 118 119 120
	n.AddRawLink(name, lnk)

	return nil
}

// AddRawLink adds a copy of a link to this node
func (n *Node) AddRawLink(name string, l *Link) error {
	n.encoded = nil
	n.Links = append(n.Links, &Link{
		Name: name,
		Size: l.Size,
		Hash: l.Hash,
	})
121 122 123 124 125 126

	return nil
}

// Remove a link on this node by the given name
func (n *Node) RemoveNodeLink(name string) error {
127
	n.encoded = nil
Jeromy's avatar
Jeromy committed
128 129 130 131 132 133 134 135
	good := make([]*Link, 0, len(n.Links))
	var found bool

	for _, l := range n.Links {
		if l.Name != name {
			good = append(good, l)
		} else {
			found = true
136 137
		}
	}
Jeromy's avatar
Jeromy committed
138 139 140 141 142 143 144
	n.Links = good

	if !found {
		return ErrNotFound
	}

	return nil
145 146
}

147 148 149 150 151 152 153 154 155 156 157
// Return a copy of the link with given name
func (n *Node) GetNodeLink(name string) (*Link, error) {
	for _, l := range n.Links {
		if l.Name == name {
			return &Link{
				Name: l.Name,
				Size: l.Size,
				Hash: l.Hash,
			}, nil
		}
	}
158
	return nil, ErrLinkNotFound
159 160
}

161 162 163 164 165 166 167 168 169
func (n *Node) GetLinkedNode(ctx context.Context, ds DAGService, name string) (*Node, error) {
	lnk, err := n.GetNodeLink(name)
	if err != nil {
		return nil, err
	}

	return lnk.GetNode(ctx, ds)
}

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

Jeromy's avatar
Jeromy committed
179 180 181 182
	if len(n.Links) > 0 {
		nnode.Links = make([]*Link, len(n.Links))
		copy(nnode.Links, n.Links)
	}
183 184 185
	return nnode
}

Jeromy's avatar
Jeromy committed
186 187 188 189 190
func (n *Node) RawData() []byte {
	out, _ := n.EncodeProtobuf(false)
	return out
}

191 192 193 194 195 196 197 198 199 200
func (n *Node) Data() []byte {
	return n.data
}

func (n *Node) SetData(d []byte) {
	n.encoded = nil
	n.cached = nil
	n.data = d
}

201 202 203 204 205 206 207 208 209 210
// 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.
func (n *Node) UpdateNodeLink(name string, that *Node) (*Node, error) {
	newnode := n.Copy()
	err := newnode.RemoveNodeLink(name)
	err = nil // ignore error
	err = newnode.AddNodeLink(name, that)
	return newnode, err
}

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

	s := uint64(len(b))
	for _, l := range n.Links {
		s += l.Size
	}
	return s, nil
}

// Stat returns statistics on the node.
227
func (n *Node) Stat() (*NodeStat, error) {
228
	enc, err := n.EncodeProtobuf(false)
229
	if err != nil {
230
		return nil, err
231 232 233 234
	}

	cumSize, err := n.Size()
	if err != nil {
235
		return nil, err
236 237
	}

238
	return &NodeStat{
Jeromy's avatar
Jeromy committed
239
		Hash:           n.Key().B58String(),
240 241
		NumLinks:       len(n.Links),
		BlockSize:      len(enc),
242 243
		LinksSize:      len(enc) - len(n.data), // includes framing.
		DataSize:       len(n.data),
244 245 246 247
		CumulativeSize: int(cumSize),
	}, nil
}

Jeromy's avatar
Jeromy committed
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
func (n *Node) Key() key.Key {
	return key.Key(n.Multihash())
}

func (n *Node) Loggable() map[string]interface{} {
	return map[string]interface{}{
		"node": n.String(),
	}
}

func (n *Node) Cid() *cid.Cid {
	h := n.Multihash()

	return cid.NewCidV0(h)
}

func (n *Node) String() string {
	return n.Cid().String()
}

268
// Multihash hashes the encoded data of this node.
Jeromy's avatar
Jeromy committed
269
func (n *Node) Multihash() mh.Multihash {
270
	// NOTE: EncodeProtobuf generates the hash and puts it in n.cached.
271
	_, err := n.EncodeProtobuf(false)
272
	if err != nil {
Jeromy's avatar
Jeromy committed
273 274
		// Note: no possibility exists for an error to be returned through here
		panic(err)
275 276
	}

Jeromy's avatar
Jeromy committed
277
	return n.cached.Hash()
278
}