hamt.go 13.9 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
package hamt

import (
	"context"
	"fmt"
	"os"
27
	"sync"
28

Jeromy's avatar
Jeromy committed
29 30 31
	bitfield "github.com/Stebalien/go-bitfield"
	cid "github.com/ipfs/go-cid"
	ipld "github.com/ipfs/go-ipld-format"
Kevin Atkinson's avatar
Kevin Atkinson committed
32 33
	dag "github.com/ipfs/go-merkledag"
	format "github.com/ipfs/go-unixfs"
Jeromy's avatar
Jeromy committed
34
	"github.com/spaolacci/murmur3"
35 36 37
)

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

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

Steven Allen's avatar
Steven Allen committed
46
	bitfield bitfield.Bitfield
47 48 49 50 51 52

	children []child

	tableSize    int
	tableSizeLg2 int

53
	builder  cid.Builder
54 55 56 57 58
	hashFunc uint64

	prefixPadStr string
	maxpadlen    int

59
	dserv ipld.DAGService
60 61 62 63
}

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

Hector Sanjuan's avatar
Hector Sanjuan committed
68 69 70
// 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)
71 72 73 74
	if err != nil {
		return nil, err
	}

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

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

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

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

Overbool's avatar
Overbool committed
108
	if fsn.Type() != format.THAMTShard {
109 110 111
		return nil, fmt.Errorf("node was not a dir shard")
	}

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

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

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

	return ds, nil
}

130 131 132
// SetCidBuilder sets the CID Builder
func (ds *Shard) SetCidBuilder(builder cid.Builder) {
	ds.builder = builder
133 134
}

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

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

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

		ch := ds.children[cindex]
		if ch != nil {
154
			clnk, err := ch.Link()
155 156 157 158
			if err != nil {
				return nil, err
			}

159
			err = out.AddRawLink(ds.linkNamePrefix(i)+ch.Label(), clnk)
160 161 162 163 164 165 166 167 168 169 170 171 172
			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
173
		cindex++
174 175
	}

Overbool's avatar
Overbool committed
176
	data, err := format.HAMTShardData(ds.bitfield.Bytes(), uint64(ds.tableSize), HashMurmur3)
177 178 179 180 181 182
	if err != nil {
		return nil, err
	}

	out.SetData(data)

183
	err = ds.dserv.Add(context.TODO(), out)
184 185 186 187 188 189 190 191 192
	if err != nil {
		return nil, err
	}

	return out, nil
}

type shardValue struct {
	key string
193
	val *ipld.Link
194 195
}

Jeromy's avatar
Jeromy committed
196
// Link returns a link to this node
197
func (sv *shardValue) Link() (*ipld.Link, error) {
198 199 200 201 202 203 204
	return sv.val, nil
}

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

205 206 207 208 209 210 211 212
func (ds *Shard) makeShardValue(lnk *ipld.Link) *shardValue {
	lnk2 := *lnk
	return &shardValue{
		key: lnk.Name[ds.maxpadlen:],
		val: &lnk2,
	}
}

213 214 215 216 217 218
func hash(val []byte) []byte {
	h := murmur3.New64()
	h.Write(val)
	return h.Sum(nil)
}

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

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

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

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

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

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

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

Jeromy's avatar
Jeromy committed
261
	return out, nil
262 263
}

264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
type linkType int

const (
	invalidLink linkType = iota
	shardLink
	shardValueLink
)

func (ds *Shard) childLinkType(lnk *ipld.Link) (linkType, error) {
	if len(lnk.Name) < ds.maxpadlen {
		return invalidLink, fmt.Errorf("invalid link name '%s'", lnk.Name)
	}
	if len(lnk.Name) == ds.maxpadlen {
		return shardLink, nil
	}
	return shardValueLink, nil
}

282 283 284
// 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
285
func (ds *Shard) getChild(ctx context.Context, i int) (child, error) {
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
	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
304
func (ds *Shard) loadChild(ctx context.Context, i int) (child, error) {
305
	lnk := ds.nd.Links()[i]
306 307 308
	lnkLinkType, err := ds.childLinkType(lnk)
	if err != nil {
		return nil, err
309 310 311
	}

	var c child
312
	if lnkLinkType == shardLink {
313 314 315 316
		nd, err := lnk.GetNode(ctx, ds.dserv)
		if err != nil {
			return nil, err
		}
317 318 319 320 321 322 323
		cds, err := NewHamtFromDag(ds.dserv, nd)
		if err != nil {
			return nil, err
		}

		c = cds
	} else {
324
		c = ds.makeShardValue(lnk)
325 326 327 328 329 330
	}

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

Hector Sanjuan's avatar
Hector Sanjuan committed
331
func (ds *Shard) setChild(i int, c child) {
332 333 334
	ds.children[i] = c
}

Jeromy's avatar
Jeromy committed
335
// Link returns a merklelink to this shard node
Hector Sanjuan's avatar
Hector Sanjuan committed
336
func (ds *Shard) Link() (*ipld.Link, error) {
337 338 339 340 341
	nd, err := ds.Node()
	if err != nil {
		return nil, err
	}

342
	err = ds.dserv.Add(context.TODO(), nd)
343 344 345 346
	if err != nil {
		return nil, err
	}

347
	return ipld.MakeLink(nd)
348 349
}

Hector Sanjuan's avatar
Hector Sanjuan committed
350
func (ds *Shard) insertChild(idx int, key string, lnk *ipld.Link) error {
351
	if lnk == nil {
352 353 354 355
		return os.ErrNotExist
	}

	i := ds.indexForBitPos(idx)
Steven Allen's avatar
Steven Allen committed
356
	ds.bitfield.SetBit(idx)
357 358

	lnk.Name = ds.linkNamePrefix(idx) + key
359 360
	sv := &shardValue{
		key: key,
361
		val: lnk,
362 363 364
	}

	ds.children = append(ds.children[:i], append([]child{sv}, ds.children[i:]...)...)
365
	ds.nd.SetLinks(append(ds.nd.Links()[:i], append([]*ipld.Link{nil}, ds.nd.Links()[i:]...)...))
366 367 368
	return nil
}

Hector Sanjuan's avatar
Hector Sanjuan committed
369
func (ds *Shard) rmChild(i int) error {
370 371 372 373 374 375 376 377 378 379 380 381 382
	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
383
func (ds *Shard) getValue(ctx context.Context, hv *hashBits, key string, cb func(*shardValue) error) error {
384
	idx := hv.Next(ds.tableSizeLg2)
Steven Allen's avatar
Steven Allen committed
385
	if ds.bitfield.Bit(int(idx)) {
386 387 388 389 390 391 392 393
		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
394
		case *Shard:
395 396 397 398 399 400 401 402 403 404 405
			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
406 407
// EnumLinks collects all links in the Shard.
func (ds *Shard) EnumLinks(ctx context.Context) ([]*ipld.Link, error) {
408
	var links []*ipld.Link
409 410
	var setlk sync.Mutex

411 412 413
	getLinks := makeAsyncTrieGetLinks(ds.dserv, func(sv *shardValue) error {
		lnk := sv.val
		lnk.Name = sv.key
414
		setlk.Lock()
415
		links = append(links, lnk)
416
		setlk.Unlock()
417 418
		return nil
	})
419

420 421 422
	cset := cid.NewSet()

	err := dag.EnumerateChildrenAsync(ctx, getLinks, ds.nd.Cid(), cset.Visit)
423 424 425
	return links, err
}

Hector Sanjuan's avatar
Hector Sanjuan committed
426 427
// 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
428
	return ds.walkTrie(ctx, func(sv *shardValue) error {
429
		lnk := sv.val
430 431
		lnk.Name = sv.key

432
		return f(lnk)
433 434 435
	})
}

436 437 438 439
// makeAsyncTrieGetLinks builds a getLinks function that can be used with EnumerateChildrenAsync
// to iterate a HAMT shard. It takes an IPLD Dag Service to fetch nodes, and a call back that will get called
// on all links to leaf nodes in a HAMT tree, so they can be collected for an EnumLinks operation
func makeAsyncTrieGetLinks(dagService ipld.DAGService, onShardValue func(*shardValue) error) dag.GetLinks {
440

441 442
	return func(ctx context.Context, currentCid cid.Cid) ([]*ipld.Link, error) {
		node, err := dagService.Get(ctx, currentCid)
443 444 445
		if err != nil {
			return nil, err
		}
446
		directoryShard, err := NewHamtFromDag(dagService, node)
447 448 449 450
		if err != nil {
			return nil, err
		}

451
		childShards := make([]*ipld.Link, 0, len(directoryShard.children))
452
		links := directoryShard.nd.Links()
453
		for idx := range directoryShard.children {
454
			lnk := links[idx]
455
			lnkLinkType, err := directoryShard.childLinkType(lnk)
456

457 458
			if err != nil {
				return nil, err
459
			}
460
			if lnkLinkType == shardLink {
461 462
				childShards = append(childShards, lnk)
			} else {
463
				sv := directoryShard.makeShardValue(lnk)
464 465 466 467
				err := onShardValue(sv)
				if err != nil {
					return nil, err
				}
468 469 470 471 472 473
			}
		}
		return childShards, nil
	}
}

Hector Sanjuan's avatar
Hector Sanjuan committed
474
func (ds *Shard) walkTrie(ctx context.Context, cb func(*shardValue) error) error {
Steven Allen's avatar
Steven Allen committed
475
	for idx := range ds.children {
Jeromy's avatar
Jeromy committed
476
		c, err := ds.getChild(ctx, idx)
477 478 479 480 481 482
		if err != nil {
			return err
		}

		switch c := c.(type) {
		case *shardValue:
Steven Allen's avatar
Steven Allen committed
483
			if err := cb(c); err != nil {
484 485 486
				return err
			}

Hector Sanjuan's avatar
Hector Sanjuan committed
487
		case *Shard:
Steven Allen's avatar
Steven Allen committed
488
			if err := c.walkTrie(ctx, cb); err != nil {
489 490 491 492 493 494 495 496 497
				return err
			}
		default:
			return fmt.Errorf("unexpected child type: %#v", c)
		}
	}
	return nil
}

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

Steven Allen's avatar
Steven Allen committed
501
	if !ds.bitfield.Bit(idx) {
502 503 504 505 506 507 508 509 510 511 512
		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
513
	case *Shard:
514 515 516 517 518 519 520 521 522 523 524 525
		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
526
				ds.bitfield.UnsetBit(idx)
527 528 529 530 531 532 533 534 535 536 537 538 539
				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
540 541 542
		if child.key == key {
			// value modification
			if val == nil {
Steven Allen's avatar
Steven Allen committed
543
				ds.bitfield.UnsetBit(idx)
Jeromy's avatar
Jeromy committed
544 545
				return ds.rmChild(cindex)
			}
546 547 548

			child.val = val
			return nil
Jeromy's avatar
Jeromy committed
549
		}
550

Jeromy's avatar
Jeromy committed
551 552 553
		if val == nil {
			return os.ErrNotExist
		}
554

Jeromy's avatar
Jeromy committed
555
		// replace value with another shard, one level deeper
Hector Sanjuan's avatar
Hector Sanjuan committed
556
		ns, err := NewShard(ds.dserv, ds.tableSize)
Jeromy's avatar
Jeromy committed
557 558 559
		if err != nil {
			return err
		}
560
		ns.builder = ds.builder
Jeromy's avatar
Jeromy committed
561 562 563 564
		chhv := &hashBits{
			b:        hash([]byte(child.key)),
			consumed: hv.consumed,
		}
565

Jeromy's avatar
Jeromy committed
566 567 568 569
		err = ns.modifyValue(ctx, hv, key, val)
		if err != nil {
			return err
		}
570

Jeromy's avatar
Jeromy committed
571 572 573
		err = ns.modifyValue(ctx, chhv, child.key, child.val)
		if err != nil {
			return err
574
		}
Jeromy's avatar
Jeromy committed
575 576 577

		ds.setChild(cindex, ns)
		return nil
578 579 580 581 582
	default:
		return fmt.Errorf("unexpected type for child: %#v", child)
	}
}

Jeromy's avatar
Jeromy committed
583 584 585
// 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
586
func (ds *Shard) indexForBitPos(bp int) int {
Steven Allen's avatar
Steven Allen committed
587
	return ds.bitfield.OnesBefore(bp)
588 589 590
}

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