hamt.go 13.1 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 28 29 30 31 32 33
package hamt

import (
	"context"
	"fmt"
	"math"
	"math/big"
	"os"

	dag "github.com/ipfs/go-ipfs/merkledag"
	format "github.com/ipfs/go-ipfs/unixfs"
	upb "github.com/ipfs/go-ipfs/unixfs/pb"

34 35
	cid "gx/ipfs/QmNp85zy9RLrQ5oQD4hPyS39ezrrXpcaa7R4Y9kxdWQLLQ/go-cid"
	node "gx/ipfs/QmPN7cwmpcc4DWXb4KTB9dNAJgjuPY69h3npsMfhRrQL9c/go-ipld-format"
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
	proto "gx/ipfs/QmZ4Qi3GaRbjcx28Sme5eMH7RQjGkt8wHxt2a65oLaeFEV/gogo-protobuf/proto"
	"gx/ipfs/QmfJHywXQu98UeZtGJBQrPAR6AtmDjjbe3qjTo9piXHPnx/murmur3"
)

const (
	HashMurmur3 uint64 = 0x22
)

type HamtShard struct {
	nd *dag.ProtoNode

	bitfield *big.Int

	children []child

	tableSize    int
	tableSizeLg2 int

54
	prefix   *cid.Prefix
55 56 57 58 59 60 61 62 63 64
	hashFunc uint64

	prefixPadStr string
	maxpadlen    int

	dserv dag.DAGService
}

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

69 70 71 72 73 74
func NewHamtShard(dserv dag.DAGService, size int) (*HamtShard, error) {
	ds, err := makeHamtShard(dserv, size)
	if err != nil {
		return nil, err
	}

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

81 82 83 84 85
func makeHamtShard(ds dag.DAGService, size int) (*HamtShard, error) {
	lg2s := int(math.Log2(float64(size)))
	if 1<<uint(lg2s) != size {
		return nil, fmt.Errorf("hamt size should be a power of two")
	}
86 87
	maxpadding := fmt.Sprintf("%X", size-1)
	return &HamtShard{
88
		tableSizeLg2: lg2s,
89 90 91 92
		prefixPadStr: fmt.Sprintf("%%0%dX", len(maxpadding)),
		maxpadlen:    len(maxpadding),
		tableSize:    size,
		dserv:        ds,
93
	}, nil
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
}

func NewHamtFromDag(dserv dag.DAGService, nd node.Node) (*HamtShard, error) {
	pbnd, ok := nd.(*dag.ProtoNode)
	if !ok {
		return nil, dag.ErrLinkNotFound
	}

	pbd, err := format.FromBytes(pbnd.Data())
	if err != nil {
		return nil, err
	}

	if pbd.GetType() != upb.Data_HAMTShard {
		return nil, fmt.Errorf("node was not a dir shard")
	}

	if pbd.GetHashType() != HashMurmur3 {
		return nil, fmt.Errorf("only murmur3 supported as hash function")
	}

115 116 117 118 119
	ds, err := makeHamtShard(dserv, int(pbd.GetFanout()))
	if err != nil {
		return nil, err
	}

120 121 122 123
	ds.nd = pbnd.Copy().(*dag.ProtoNode)
	ds.children = make([]child, len(pbnd.Links()))
	ds.bitfield = new(big.Int).SetBytes(pbd.GetData())
	ds.hashFunc = pbd.GetHashType()
124
	ds.prefix = &ds.nd.Prefix
125 126 127 128

	return ds, nil
}

Kevin Atkinson's avatar
Kevin Atkinson committed
129
// SetPrefix sets the CID Prefix
130 131 132 133
func (ds *HamtShard) SetPrefix(prefix *cid.Prefix) {
	ds.prefix = prefix
}

Kevin Atkinson's avatar
Kevin Atkinson committed
134
// Prefix gets the CID Prefix, may be nil if unset
135 136 137 138
func (ds *HamtShard) Prefix() *cid.Prefix {
	return ds.prefix
}

139 140 141
// Node serializes the HAMT structure into a merkledag node with unixfs formatting
func (ds *HamtShard) Node() (node.Node, error) {
	out := new(dag.ProtoNode)
142
	out.SetPrefix(ds.prefix)
143 144 145 146 147 148 149 150 151 152

	// TODO: optimized 'for each set bit'
	for i := 0; i < ds.tableSize; i++ {
		if ds.bitfield.Bit(i) == 0 {
			continue
		}

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

158
			err = out.AddRawLink(ds.linkNamePrefix(i)+ch.Label(), clnk)
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
			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
			}
		}
	}

	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)

	_, err = ds.dserv.Add(out)
	if err != nil {
		return nil, err
	}

	return out, nil
}

type shardValue struct {
	key string
197
	val *node.Link
198 199
}

Jeromy's avatar
Jeromy committed
200
// Link returns a link to this node
201
func (sv *shardValue) Link() (*node.Link, error) {
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
	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)
}

// Label for HamtShards is the empty string, this is used to differentiate them from
// value entries
func (ds *HamtShard) Label() string {
	return ""
}

// Set sets 'name' = nd in the HAMT
func (ds *HamtShard) Set(ctx context.Context, name string, nd node.Node) error {
	hv := &hashBits{b: hash([]byte(name))}
224 225 226 227 228 229 230 231 232 233 234 235
	_, err := ds.dserv.Add(nd)
	if err != nil {
		return err
	}

	lnk, err := node.MakeLink(nd)
	if err != nil {
		return err
	}
	lnk.Name = ds.linkNamePrefix(0) + name

	return ds.modifyValue(ctx, hv, name, lnk)
236 237 238 239 240 241 242 243
}

// Remove deletes the named entry if it exists, this operation is idempotent.
func (ds *HamtShard) Remove(ctx context.Context, name string) error {
	hv := &hashBits{b: hash([]byte(name))}
	return ds.modifyValue(ctx, hv, name, nil)
}

Jeromy's avatar
Jeromy committed
244 245
// Find searches for a child node by 'name' within this hamt
func (ds *HamtShard) Find(ctx context.Context, name string) (*node.Link, error) {
246 247
	hv := &hashBits{b: hash([]byte(name))}

248
	var out *node.Link
249 250 251 252
	err := ds.getValue(ctx, hv, name, func(sv *shardValue) error {
		out = sv.val
		return nil
	})
253 254 255
	if err != nil {
		return nil, err
	}
256

Jeromy's avatar
Jeromy committed
257
	return out, nil
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
}

// 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.
func (ds *HamtShard) getChild(ctx context.Context, i int) (child, error) {
	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
func (ds *HamtShard) loadChild(ctx context.Context, i int) (child, error) {
	lnk := ds.nd.Links()[i]
	if len(lnk.Name) < ds.maxpadlen {
		return nil, fmt.Errorf("invalid link name '%s'", lnk.Name)
	}

	nd, err := lnk.GetNode(ctx, ds.dserv)
	if err != nil {
		return nil, err
	}

	var c child
	if len(lnk.Name) == ds.maxpadlen {
		pbnd, ok := nd.(*dag.ProtoNode)
		if !ok {
			return nil, dag.ErrNotProtobuf
		}

		pbd, err := format.FromBytes(pbnd.Data())
		if err != nil {
			return nil, err
		}

		if pbd.GetType() != format.THAMTShard {
			return nil, fmt.Errorf("HAMT entries must have non-zero length name")
		}

		cds, err := NewHamtFromDag(ds.dserv, nd)
		if err != nil {
			return nil, err
		}

		c = cds
	} else {
316
		lnk2 := *lnk
317 318
		c = &shardValue{
			key: lnk.Name[ds.maxpadlen:],
319
			val: &lnk2,
320 321 322 323 324 325 326 327 328 329 330
		}
	}

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

func (ds *HamtShard) setChild(i int, c child) {
	ds.children[i] = c
}

Jeromy's avatar
Jeromy committed
331
// Link returns a merklelink to this shard node
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
func (ds *HamtShard) Link() (*node.Link, error) {
	nd, err := ds.Node()
	if err != nil {
		return nil, err
	}

	_, err = ds.dserv.Add(nd)
	if err != nil {
		return nil, err
	}

	return node.MakeLink(nd)
}

func (ds *HamtShard) insertChild(idx int, key string, lnk *node.Link) error {
	if lnk == nil {
348 349 350 351 352
		return os.ErrNotExist
	}

	i := ds.indexForBitPos(idx)
	ds.bitfield.SetBit(ds.bitfield, idx, 1)
353 354

	lnk.Name = ds.linkNamePrefix(idx) + key
355 356
	sv := &shardValue{
		key: key,
357
		val: lnk,
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
	}

	ds.children = append(ds.children[:i], append([]child{sv}, ds.children[i:]...)...)
	ds.nd.SetLinks(append(ds.nd.Links()[:i], append([]*node.Link{nil}, ds.nd.Links()[i:]...)...))
	return nil
}

func (ds *HamtShard) rmChild(i int) error {
	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
}

func (ds *HamtShard) getValue(ctx context.Context, hv *hashBits, key string, cb func(*shardValue) error) error {
	idx := hv.Next(ds.tableSizeLg2)
	if ds.bitfield.Bit(int(idx)) == 1 {
		cindex := ds.indexForBitPos(idx)

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

		switch child := child.(type) {
		case *HamtShard:
			return child.getValue(ctx, hv, key, cb)
		case *shardValue:
			if child.key == key {
				return cb(child)
			}
		}
	}

	return os.ErrNotExist
}

Jeromy's avatar
Jeromy committed
402
func (ds *HamtShard) EnumLinks(ctx context.Context) ([]*node.Link, error) {
403
	var links []*node.Link
Jeromy's avatar
Jeromy committed
404
	err := ds.ForEachLink(ctx, func(l *node.Link) error {
405 406 407 408 409 410
		links = append(links, l)
		return nil
	})
	return links, err
}

Jeromy's avatar
Jeromy committed
411 412
func (ds *HamtShard) ForEachLink(ctx context.Context, f func(*node.Link) error) error {
	return ds.walkTrie(ctx, func(sv *shardValue) error {
413
		lnk := sv.val
414 415
		lnk.Name = sv.key

416
		return f(lnk)
417 418 419
	})
}

Jeromy's avatar
Jeromy committed
420
func (ds *HamtShard) walkTrie(ctx context.Context, cb func(*shardValue) error) error {
421 422 423 424 425 426 427 428
	for i := 0; i < ds.tableSize; i++ {
		if ds.bitfield.Bit(i) == 0 {
			continue
		}

		idx := ds.indexForBitPos(i)
		// NOTE: an optimized version could simply iterate over each
		//       element in the 'children' array.
Jeromy's avatar
Jeromy committed
429
		c, err := ds.getChild(ctx, idx)
430 431 432 433 434 435 436 437 438 439 440 441
		if err != nil {
			return err
		}

		switch c := c.(type) {
		case *shardValue:
			err := cb(c)
			if err != nil {
				return err
			}

		case *HamtShard:
Jeromy's avatar
Jeromy committed
442
			err := c.walkTrie(ctx, cb)
443 444 445 446 447 448 449 450 451 452
			if err != nil {
				return err
			}
		default:
			return fmt.Errorf("unexpected child type: %#v", c)
		}
	}
	return nil
}

453
func (ds *HamtShard) modifyValue(ctx context.Context, hv *hashBits, key string, val *node.Link) error {
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
	idx := hv.Next(ds.tableSizeLg2)

	if ds.bitfield.Bit(idx) != 1 {
		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) {
	case *HamtShard:
		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.
				ds.bitfield.SetBit(ds.bitfield, idx, 0)
				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:
		switch {
		case val == nil: // passing a nil value signifies a 'delete'
			ds.bitfield.SetBit(ds.bitfield, idx, 0)
			return ds.rmChild(cindex)

		case child.key == key: // value modification
			child.val = val
			return nil

		default: // replace value with another shard, one level deeper
505 506 507 508
			ns, err := NewHamtShard(ds.dserv, ds.tableSize)
			if err != nil {
				return err
			}
509
			ns.prefix = ds.prefix
510 511 512 513 514
			chhv := &hashBits{
				b:        hash([]byte(child.key)),
				consumed: hv.consumed,
			}

515
			err = ns.modifyValue(ctx, hv, key, val)
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
			if err != nil {
				return err
			}

			err = ns.modifyValue(ctx, chhv, child.key, child.val)
			if err != nil {
				return err
			}

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

Jeromy's avatar
Jeromy committed
533 534 535
// 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.
536 537 538 539
func (ds *HamtShard) indexForBitPos(bp int) int {
	// TODO: an optimization could reuse the same 'mask' here and change the size
	//       as needed. This isnt yet done as the bitset package doesnt make it easy
	//       to do.
Jeromy's avatar
Jeromy committed
540 541

	// make a bitmask (all bits set) 'bp' bits long
542 543 544 545 546 547 548 549 550 551
	mask := new(big.Int).Sub(new(big.Int).Exp(big.NewInt(2), big.NewInt(int64(bp)), nil), big.NewInt(1))
	mask.And(mask, ds.bitfield)

	return popCount(mask)
}

// linkNamePrefix takes in the bitfield index of an entry and returns its hex prefix
func (ds *HamtShard) linkNamePrefix(idx int) string {
	return fmt.Sprintf(ds.prefixPadStr, idx)
}