hamt.go 12.2 KB
Newer Older
Jeromy's avatar
Jeromy committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
// Package hamt implements a Hash Array Mapped Trie over ipfs merkledag nodes.
// It is implemented mostly as described in the wikipedia article on HAMTs,
// however the table size is variable (usually 256 in our usages) as opposed to
// 32 as suggested in the article.  The hash function used is currently
// Murmur3, but this value is configurable (the datastructure reports which
// hash function its using).
//
// The one algorithmic change we implement that is not mentioned in the
// wikipedia article is the collapsing of empty shards.
// Given the following tree: ( '[' = shards, '{' = values )
// [ 'A' ] -> [ 'B' ] -> { "ABC" }
//    |       L-> { "ABD" }
//    L-> { "ASDF" }
// If we simply removed "ABC", we would end up with a tree where shard 'B' only
// has a single child.  This causes two issues, the first, is that now we have
// an extra lookup required to get to "ABD".  The second issue is that now we
// have a tree that contains only "ABD", but is not the same tree that we would
// get by simply inserting "ABD" into a new tree.  To address this, we always
// check for empty shard nodes upon deletion and prune them to maintain a
// consistent tree, independent of insertion order.
21 22 23 24 25 26 27
package hamt

import (
	"context"
	"fmt"
	"os"

Jeromy's avatar
Jeromy committed
28 29 30
	dag "github.com/ipfs/go-merkledag"
	format "github.com/ipfs/go-unixfs"
	upb "github.com/ipfs/go-unixfs/pb"
31

Jeromy's avatar
Jeromy committed
32 33 34 35 36
	bitfield "github.com/Stebalien/go-bitfield"
	proto "github.com/gogo/protobuf/proto"
	cid "github.com/ipfs/go-cid"
	ipld "github.com/ipfs/go-ipld-format"
	"github.com/spaolacci/murmur3"
37 38 39
)

const (
Hector Sanjuan's avatar
Hector Sanjuan committed
40
	// HashMurmur3 is the multiformats identifier for Murmur3
41 42 43
	HashMurmur3 uint64 = 0x22
)

Hector Sanjuan's avatar
Hector Sanjuan committed
44 45
// A Shard represents the HAMT. It should be initialized with NewShard().
type Shard struct {
46 47
	nd *dag.ProtoNode

Steven Allen's avatar
Steven Allen committed
48
	bitfield bitfield.Bitfield
49 50 51 52 53 54

	children []child

	tableSize    int
	tableSizeLg2 int

55
	builder  cid.Builder
56 57 58 59 60
	hashFunc uint64

	prefixPadStr string
	maxpadlen    int

61
	dserv ipld.DAGService
62 63 64 65
}

// child can either be another shard, or a leaf node value
type child interface {
66
	Link() (*ipld.Link, error)
67 68 69
	Label() string
}

Hector Sanjuan's avatar
Hector Sanjuan committed
70 71 72
// NewShard creates a new, empty HAMT shard with the given size.
func NewShard(dserv ipld.DAGService, size int) (*Shard, error) {
	ds, err := makeShard(dserv, size)
73 74 75 76
	if err != nil {
		return nil, err
	}

77 78
	ds.nd = new(dag.ProtoNode)
	ds.hashFunc = HashMurmur3
79
	return ds, nil
80 81
}

Hector Sanjuan's avatar
Hector Sanjuan committed
82
func makeShard(ds ipld.DAGService, size int) (*Shard, error) {
Steven Allen's avatar
Steven Allen committed
83 84 85
	lg2s, err := logtwo(size)
	if err != nil {
		return nil, err
86
	}
87
	maxpadding := fmt.Sprintf("%X", size-1)
Hector Sanjuan's avatar
Hector Sanjuan committed
88
	return &Shard{
89
		tableSizeLg2: lg2s,
90 91
		prefixPadStr: fmt.Sprintf("%%0%dX", len(maxpadding)),
		maxpadlen:    len(maxpadding),
Steven Allen's avatar
Steven Allen committed
92
		bitfield:     bitfield.NewBitfield(size),
93 94
		tableSize:    size,
		dserv:        ds,
95
	}, nil
96 97
}

Steven Allen's avatar
Steven Allen committed
98
// NewHamtFromDag creates new a HAMT shard from the given DAG.
Hector Sanjuan's avatar
Hector Sanjuan committed
99
func NewHamtFromDag(dserv ipld.DAGService, nd ipld.Node) (*Shard, error) {
100 101
	pbnd, ok := nd.(*dag.ProtoNode)
	if !ok {
102
		return nil, dag.ErrNotProtobuf
103 104
	}

Overbool's avatar
Overbool committed
105
	fsn, err := format.FSNodeFromBytes(pbnd.Data())
106 107 108 109
	if err != nil {
		return nil, err
	}

Overbool's avatar
Overbool committed
110 111

	if fsn.Type() != upb.Data_HAMTShard {
112 113 114
		return nil, fmt.Errorf("node was not a dir shard")
	}

Overbool's avatar
Overbool committed
115
	if fsn.HashType() != HashMurmur3 {
116 117 118
		return nil, fmt.Errorf("only murmur3 supported as hash function")
	}

Overbool's avatar
Overbool committed
119
	ds, err := makeShard(dserv, int(fsn.Fanout()))
120 121 122 123
	if err != nil {
		return nil, err
	}

124 125
	ds.nd = pbnd.Copy().(*dag.ProtoNode)
	ds.children = make([]child, len(pbnd.Links()))
Overbool's avatar
Overbool committed
126 127
	ds.bitfield.SetBytes(fsn.Data())
	ds.hashFunc = fsn.HashType()
128
	ds.builder = ds.nd.CidBuilder()
129 130 131 132

	return ds, nil
}

133 134 135
// SetCidBuilder sets the CID Builder
func (ds *Shard) SetCidBuilder(builder cid.Builder) {
	ds.builder = builder
136 137
}

138 139 140
// CidBuilder gets the CID Builder, may be nil if unset
func (ds *Shard) CidBuilder() cid.Builder {
	return ds.builder
141 142
}

143
// Node serializes the HAMT structure into a merkledag node with unixfs formatting
Hector Sanjuan's avatar
Hector Sanjuan committed
144
func (ds *Shard) Node() (ipld.Node, error) {
145
	out := new(dag.ProtoNode)
146
	out.SetCidBuilder(ds.builder)
147

Steven Allen's avatar
Steven Allen committed
148
	cindex := 0
149 150
	// TODO: optimized 'for each set bit'
	for i := 0; i < ds.tableSize; i++ {
Steven Allen's avatar
Steven Allen committed
151
		if !ds.bitfield.Bit(i) {
152 153 154 155 156
			continue
		}

		ch := ds.children[cindex]
		if ch != nil {
157
			clnk, err := ch.Link()
158 159 160 161
			if err != nil {
				return nil, err
			}

162
			err = out.AddRawLink(ds.linkNamePrefix(i)+ch.Label(), clnk)
163 164 165 166 167 168 169 170 171 172 173 174 175
			if err != nil {
				return nil, err
			}
		} else {
			// child unloaded, just copy in link with updated name
			lnk := ds.nd.Links()[cindex]
			label := lnk.Name[ds.maxpadlen:]

			err := out.AddRawLink(ds.linkNamePrefix(i)+label, lnk)
			if err != nil {
				return nil, err
			}
		}
Steven Allen's avatar
Steven Allen committed
176
		cindex++
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
	}

	typ := upb.Data_HAMTShard
	data, err := proto.Marshal(&upb.Data{
		Type:     &typ,
		Fanout:   proto.Uint64(uint64(ds.tableSize)),
		HashType: proto.Uint64(HashMurmur3),
		Data:     ds.bitfield.Bytes(),
	})
	if err != nil {
		return nil, err
	}

	out.SetData(data)

192
	err = ds.dserv.Add(context.TODO(), out)
193 194 195 196 197 198 199 200 201
	if err != nil {
		return nil, err
	}

	return out, nil
}

type shardValue struct {
	key string
202
	val *ipld.Link
203 204
}

Jeromy's avatar
Jeromy committed
205
// Link returns a link to this node
206
func (sv *shardValue) Link() (*ipld.Link, error) {
207 208 209 210 211 212 213 214 215 216 217 218 219
	return sv.val, nil
}

func (sv *shardValue) Label() string {
	return sv.key
}

func hash(val []byte) []byte {
	h := murmur3.New64()
	h.Write(val)
	return h.Sum(nil)
}

Hector Sanjuan's avatar
Hector Sanjuan committed
220
// Label for Shards is the empty string, this is used to differentiate them from
221
// value entries
Hector Sanjuan's avatar
Hector Sanjuan committed
222
func (ds *Shard) Label() string {
223 224 225 226
	return ""
}

// Set sets 'name' = nd in the HAMT
Hector Sanjuan's avatar
Hector Sanjuan committed
227
func (ds *Shard) Set(ctx context.Context, name string, nd ipld.Node) error {
228
	hv := &hashBits{b: hash([]byte(name))}
229
	err := ds.dserv.Add(ctx, nd)
230 231 232 233
	if err != nil {
		return err
	}

234
	lnk, err := ipld.MakeLink(nd)
235 236 237 238 239 240
	if err != nil {
		return err
	}
	lnk.Name = ds.linkNamePrefix(0) + name

	return ds.modifyValue(ctx, hv, name, lnk)
241 242 243
}

// Remove deletes the named entry if it exists, this operation is idempotent.
Hector Sanjuan's avatar
Hector Sanjuan committed
244
func (ds *Shard) Remove(ctx context.Context, name string) error {
245 246 247 248
	hv := &hashBits{b: hash([]byte(name))}
	return ds.modifyValue(ctx, hv, name, nil)
}

Jeromy's avatar
Jeromy committed
249
// Find searches for a child node by 'name' within this hamt
Hector Sanjuan's avatar
Hector Sanjuan committed
250
func (ds *Shard) Find(ctx context.Context, name string) (*ipld.Link, error) {
251 252
	hv := &hashBits{b: hash([]byte(name))}

253
	var out *ipld.Link
254 255 256 257
	err := ds.getValue(ctx, hv, name, func(sv *shardValue) error {
		out = sv.val
		return nil
	})
258 259 260
	if err != nil {
		return nil, err
	}
261

Jeromy's avatar
Jeromy committed
262
	return out, nil
263 264 265 266 267
}

// getChild returns the i'th child of this shard. If it is cached in the
// children array, it will return it from there. Otherwise, it loads the child
// node from disk.
Hector Sanjuan's avatar
Hector Sanjuan committed
268
func (ds *Shard) getChild(ctx context.Context, i int) (child, error) {
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
	if i >= len(ds.children) || i < 0 {
		return nil, fmt.Errorf("invalid index passed to getChild (likely corrupt bitfield)")
	}

	if len(ds.children) != len(ds.nd.Links()) {
		return nil, fmt.Errorf("inconsistent lengths between children array and Links array")
	}

	c := ds.children[i]
	if c != nil {
		return c, nil
	}

	return ds.loadChild(ctx, i)
}

// loadChild reads the i'th child node of this shard from disk and returns it
// as a 'child' interface
Hector Sanjuan's avatar
Hector Sanjuan committed
287
func (ds *Shard) loadChild(ctx context.Context, i int) (child, error) {
288 289 290 291 292 293 294
	lnk := ds.nd.Links()[i]
	if len(lnk.Name) < ds.maxpadlen {
		return nil, fmt.Errorf("invalid link name '%s'", lnk.Name)
	}

	var c child
	if len(lnk.Name) == ds.maxpadlen {
295 296 297 298
		nd, err := lnk.GetNode(ctx, ds.dserv)
		if err != nil {
			return nil, err
		}
299 300 301 302 303 304 305
		cds, err := NewHamtFromDag(ds.dserv, nd)
		if err != nil {
			return nil, err
		}

		c = cds
	} else {
306
		lnk2 := *lnk
307 308
		c = &shardValue{
			key: lnk.Name[ds.maxpadlen:],
309
			val: &lnk2,
310 311 312 313 314 315 316
		}
	}

	ds.children[i] = c
	return c, nil
}

Hector Sanjuan's avatar
Hector Sanjuan committed
317
func (ds *Shard) setChild(i int, c child) {
318 319 320
	ds.children[i] = c
}

Jeromy's avatar
Jeromy committed
321
// Link returns a merklelink to this shard node
Hector Sanjuan's avatar
Hector Sanjuan committed
322
func (ds *Shard) Link() (*ipld.Link, error) {
323 324 325 326 327
	nd, err := ds.Node()
	if err != nil {
		return nil, err
	}

328
	err = ds.dserv.Add(context.TODO(), nd)
329 330 331 332
	if err != nil {
		return nil, err
	}

333
	return ipld.MakeLink(nd)
334 335
}

Hector Sanjuan's avatar
Hector Sanjuan committed
336
func (ds *Shard) insertChild(idx int, key string, lnk *ipld.Link) error {
337
	if lnk == nil {
338 339 340 341
		return os.ErrNotExist
	}

	i := ds.indexForBitPos(idx)
Steven Allen's avatar
Steven Allen committed
342
	ds.bitfield.SetBit(idx)
343 344

	lnk.Name = ds.linkNamePrefix(idx) + key
345 346
	sv := &shardValue{
		key: key,
347
		val: lnk,
348 349 350
	}

	ds.children = append(ds.children[:i], append([]child{sv}, ds.children[i:]...)...)
351
	ds.nd.SetLinks(append(ds.nd.Links()[:i], append([]*ipld.Link{nil}, ds.nd.Links()[i:]...)...))
352 353 354
	return nil
}

Hector Sanjuan's avatar
Hector Sanjuan committed
355
func (ds *Shard) rmChild(i int) error {
356 357 358 359 360 361 362 363 364 365 366 367 368
	if i < 0 || i >= len(ds.children) || i >= len(ds.nd.Links()) {
		return fmt.Errorf("hamt: attempted to remove child with out of range index")
	}

	copy(ds.children[i:], ds.children[i+1:])
	ds.children = ds.children[:len(ds.children)-1]

	copy(ds.nd.Links()[i:], ds.nd.Links()[i+1:])
	ds.nd.SetLinks(ds.nd.Links()[:len(ds.nd.Links())-1])

	return nil
}

Hector Sanjuan's avatar
Hector Sanjuan committed
369
func (ds *Shard) getValue(ctx context.Context, hv *hashBits, key string, cb func(*shardValue) error) error {
370
	idx := hv.Next(ds.tableSizeLg2)
Steven Allen's avatar
Steven Allen committed
371
	if ds.bitfield.Bit(int(idx)) {
372 373 374 375 376 377 378 379
		cindex := ds.indexForBitPos(idx)

		child, err := ds.getChild(ctx, cindex)
		if err != nil {
			return err
		}

		switch child := child.(type) {
Hector Sanjuan's avatar
Hector Sanjuan committed
380
		case *Shard:
381 382 383 384 385 386 387 388 389 390 391
			return child.getValue(ctx, hv, key, cb)
		case *shardValue:
			if child.key == key {
				return cb(child)
			}
		}
	}

	return os.ErrNotExist
}

Hector Sanjuan's avatar
Hector Sanjuan committed
392 393
// EnumLinks collects all links in the Shard.
func (ds *Shard) EnumLinks(ctx context.Context) ([]*ipld.Link, error) {
394 395
	var links []*ipld.Link
	err := ds.ForEachLink(ctx, func(l *ipld.Link) error {
396 397 398 399 400 401
		links = append(links, l)
		return nil
	})
	return links, err
}

Hector Sanjuan's avatar
Hector Sanjuan committed
402 403
// ForEachLink walks the Shard and calls the given function.
func (ds *Shard) ForEachLink(ctx context.Context, f func(*ipld.Link) error) error {
Jeromy's avatar
Jeromy committed
404
	return ds.walkTrie(ctx, func(sv *shardValue) error {
405
		lnk := sv.val
406 407
		lnk.Name = sv.key

408
		return f(lnk)
409 410 411
	})
}

Hector Sanjuan's avatar
Hector Sanjuan committed
412
func (ds *Shard) walkTrie(ctx context.Context, cb func(*shardValue) error) error {
Steven Allen's avatar
Steven Allen committed
413
	for idx := range ds.children {
Jeromy's avatar
Jeromy committed
414
		c, err := ds.getChild(ctx, idx)
415 416 417 418 419 420
		if err != nil {
			return err
		}

		switch c := c.(type) {
		case *shardValue:
Steven Allen's avatar
Steven Allen committed
421
			if err := cb(c); err != nil {
422 423 424
				return err
			}

Hector Sanjuan's avatar
Hector Sanjuan committed
425
		case *Shard:
Steven Allen's avatar
Steven Allen committed
426
			if err := c.walkTrie(ctx, cb); err != nil {
427 428 429 430 431 432 433 434 435
				return err
			}
		default:
			return fmt.Errorf("unexpected child type: %#v", c)
		}
	}
	return nil
}

Hector Sanjuan's avatar
Hector Sanjuan committed
436
func (ds *Shard) modifyValue(ctx context.Context, hv *hashBits, key string, val *ipld.Link) error {
437 438
	idx := hv.Next(ds.tableSizeLg2)

Steven Allen's avatar
Steven Allen committed
439
	if !ds.bitfield.Bit(idx) {
440 441 442 443 444 445 446 447 448 449 450
		return ds.insertChild(idx, key, val)
	}

	cindex := ds.indexForBitPos(idx)

	child, err := ds.getChild(ctx, cindex)
	if err != nil {
		return err
	}

	switch child := child.(type) {
Hector Sanjuan's avatar
Hector Sanjuan committed
451
	case *Shard:
452 453 454 455 456 457 458 459 460 461 462 463
		err := child.modifyValue(ctx, hv, key, val)
		if err != nil {
			return err
		}

		if val == nil {
			switch len(child.children) {
			case 0:
				// empty sub-shard, prune it
				// Note: this shouldnt normally ever happen
				//       in the event of another implementation creates flawed
				//       structures, this will help to normalize them.
Steven Allen's avatar
Steven Allen committed
464
				ds.bitfield.UnsetBit(idx)
465 466 467 468 469 470 471 472 473 474 475 476 477
				return ds.rmChild(cindex)
			case 1:
				nchild, ok := child.children[0].(*shardValue)
				if ok {
					// sub-shard with a single value element, collapse it
					ds.setChild(cindex, nchild)
				}
				return nil
			}
		}

		return nil
	case *shardValue:
Jeromy's avatar
Jeromy committed
478 479 480
		if child.key == key {
			// value modification
			if val == nil {
Steven Allen's avatar
Steven Allen committed
481
				ds.bitfield.UnsetBit(idx)
Jeromy's avatar
Jeromy committed
482 483
				return ds.rmChild(cindex)
			}
484 485 486

			child.val = val
			return nil
Jeromy's avatar
Jeromy committed
487
		}
488

Jeromy's avatar
Jeromy committed
489 490 491
		if val == nil {
			return os.ErrNotExist
		}
492

Jeromy's avatar
Jeromy committed
493
		// replace value with another shard, one level deeper
Hector Sanjuan's avatar
Hector Sanjuan committed
494
		ns, err := NewShard(ds.dserv, ds.tableSize)
Jeromy's avatar
Jeromy committed
495 496 497
		if err != nil {
			return err
		}
498
		ns.builder = ds.builder
Jeromy's avatar
Jeromy committed
499 500 501 502
		chhv := &hashBits{
			b:        hash([]byte(child.key)),
			consumed: hv.consumed,
		}
503

Jeromy's avatar
Jeromy committed
504 505 506 507
		err = ns.modifyValue(ctx, hv, key, val)
		if err != nil {
			return err
		}
508

Jeromy's avatar
Jeromy committed
509 510 511
		err = ns.modifyValue(ctx, chhv, child.key, child.val)
		if err != nil {
			return err
512
		}
Jeromy's avatar
Jeromy committed
513 514 515

		ds.setChild(cindex, ns)
		return nil
516 517 518 519 520
	default:
		return fmt.Errorf("unexpected type for child: %#v", child)
	}
}

Jeromy's avatar
Jeromy committed
521 522 523
// indexForBitPos returns the index within the collapsed array corresponding to
// the given bit in the bitset.  The collapsed array contains only one entry
// per bit set in the bitfield, and this function is used to map the indices.
Hector Sanjuan's avatar
Hector Sanjuan committed
524
func (ds *Shard) indexForBitPos(bp int) int {
Steven Allen's avatar
Steven Allen committed
525
	return ds.bitfield.OnesBefore(bp)
526 527 528
}

// linkNamePrefix takes in the bitfield index of an entry and returns its hex prefix
Hector Sanjuan's avatar
Hector Sanjuan committed
529
func (ds *Shard) linkNamePrefix(idx int) string {
530 531
	return fmt.Sprintf(ds.prefixPadStr, idx)
}