arnaucube
arnaucube/arboPublic Self-hosted repository
arbo/addbatch.go
addbatch.goRaw
  1package arbo
  2
  3import (
  4	"bytes"
  5	"fmt"
  6	"math"
  7	"runtime"
  8	"sort"
  9	"sync"
 10
 11	"github.com/iden3/go-merkletree/db"
 12)
 13
 14/*
 15
 16AddBatch design
 17===============
 18
 19
 20CASE A: Empty Tree --> if tree is empty (root==0)
 21=================================================
 22- Build the full tree from bottom to top (from all the leaf to the root)
 23
 24
 25CASE B: ALMOST CASE A, Almost empty Tree --> if Tree has numLeafs < minLeafsThreshold
 26==============================================================================
 27- Get the Leafs (key & value) (iterate the tree from the current root getting
 28the leafs)
 29- Create a new empty Tree
 30- Do CASE A for the new Tree, giving the already existing key&values (leafs)
 31from the original Tree + the new key&values to be added from the AddBatch call
 32
 33
 34       R                 R
 35      / \               /  \
 36     A   *             /    \
 37        / \           /      \
 38       B   C         *        *
 39                    / |      / \
 40                   /  |     /   \
 41                  /   |    /     \
 42           L:    A    B   G       D
 43                         / \
 44                        /   \
 45                       /     \
 46                      C      *
 47                            / \
 48                           /   \
 49                          /     \
 50                         ...     ... (nLeafs < minLeafsThreshold)
 51
 52
 53CASE C: ALMOST CASE B --> if Tree has few Leafs (but numLeafs>=minLeafsThreshold)
 54==============================================================================
 55- Use A, B, G, F as Roots of subtrees
 56- Do CASE B for each subtree
 57- Then go from L to the Root
 58
 59              R
 60             /  \
 61            /    \
 62           /      \
 63          *        *
 64         / |      / \
 65        /  |     /   \
 66       /   |    /     \
 67L:    A    B   G       D
 68              / \
 69             /   \
 70            /     \
 71           C      *
 72                 / \
 73                /   \
 74               /     \
 75              ...    ... (nLeafs >= minLeafsThreshold)
 76
 77
 78
 79CASE D: Already populated Tree
 80==============================
 81- Use A, B, C, D as subtree
 82- Sort the Keys in Buckets that share the initial part of the path
 83- For each subtree add there the new leafs
 84
 85              R
 86             /  \
 87            /    \
 88           /      \
 89          *        *
 90         / |      / \
 91        /  |     /   \
 92       /   |    /     \
 93L:    A    B   C       D
 94     /\   /\  / \     / \
 95    ...  ... ... ... ... ...
 96
 97
 98CASE E: Already populated Tree Unbalanced
 99=========================================
100- Need to fill M1 and M2, and then will be able to use CASE D
101	- Search for M1 & M2 in the inputed Keys
102	- Add M1 & M2 to the Tree
103	- From here can use CASE D
104
105              R
106             /  \
107            /    \
108           /      \
109          *        *
110           |        \
111           |         \
112           |          \
113L:    M1   *   M2      *        (where M1 and M2 are empty)
114          / |         /
115         /  |        /
116        /   |       /
117       A    *      *
118           / \     | \
119          /   \    |  \
120         /     \   |   \
121        B      *   *   C
122              / \  |\
123           ... ... | \
124                   |  \
125                   D  E
126
127
128
129Algorithm decision
130==================
131- if nLeafs==0 (root==0): CASE A
132- if nLeafs<minLeafsThreshold: CASE B
133- if nLeafs>=minLeafsThreshold && (nLeafs/nBuckets) < minLeafsThreshold: CASE C
134- else: CASE D & CASE E
135
136
137- Multiple tree.Add calls: O(n log n)
138	- Used in: cases A, B, C
139- Tree from bottom to top: O(log n)
140	- Used in: cases D, E
141
142*/
143
144const (
145	minLeafsThreshold = 100 // nolint:gomnd // TMP WIP this will be autocalculated
146)
147
148// AddBatchOpt is the WIP implementation of the AddBatch method in a more
149// optimized approach.
150func (t *Tree) AddBatchOpt(keys, values [][]byte) ([]int, error) {
151	t.updateAccessTime()
152	t.Lock()
153	defer t.Unlock()
154
155	// TODO if len(keys) is not a power of 2, add padding of empty
156	// keys&values. Maybe when len(keyvalues) is not a power of 2, cut at
157	// the biggest power of 2 under the len(keys), add those 2**n key-values
158	// using the AddBatch approach, and then add the remaining key-values
159	// using tree.Add.
160
161	kvs, err := t.keysValuesToKvs(keys, values)
162	if err != nil {
163		return nil, err
164	}
165
166	t.tx, err = t.db.NewTx() // TODO add t.tx.Commit()
167	if err != nil {
168		return nil, err
169	}
170
171	// TODO if nCPU is not a power of two, cut at the highest power of two
172	// under nCPU
173	nCPU := runtime.NumCPU()
174	l := int(math.Log2(float64(nCPU)))
175
176	// CASE A: if nLeafs==0 (root==0)
177	if bytes.Equal(t.root, t.emptyHash) {
178		// if len(kvs) is not a power of 2, cut at the bigger power
179		// of two under len(kvs), build the tree with that, and add
180		// later the excedents
181		kvsP2, kvsNonP2 := cutPowerOfTwo(kvs)
182		invalids, err := t.buildTreeBottomUp(nCPU, kvsP2)
183		if err != nil {
184			return nil, err
185		}
186		for i := 0; i < len(kvsNonP2); i++ {
187			err = t.add(0, kvsNonP2[i].k, kvsNonP2[i].v)
188			if err != nil {
189				invalids = append(invalids, kvsNonP2[i].pos)
190			}
191		}
192		return invalids, nil
193	}
194
195	// CASE B: if nLeafs<nBuckets
196	nLeafs, err := t.GetNLeafs()
197	if err != nil {
198		return nil, err
199	}
200	if nLeafs < minLeafsThreshold { // CASE B
201		invalids, excedents, err := t.caseB(0, kvs)
202		if err != nil {
203			return nil, err
204		}
205		// add the excedents
206		for i := 0; i < len(excedents); i++ {
207			err = t.add(0, excedents[i].k, excedents[i].v)
208			if err != nil {
209				invalids = append(invalids, excedents[i].pos)
210			}
211		}
212		return invalids, nil
213	}
214
215	// CASE C: if nLeafs>=minLeafsThreshold && (nLeafs/nBuckets) < minLeafsThreshold
216	// available parallelization, will need to be a power of 2 (2**n)
217	var excedents []kv
218	if nLeafs >= minLeafsThreshold && (nLeafs/nCPU) < minLeafsThreshold {
219		// TODO move to own function
220		// 1. go down until level L (L=log2(nBuckets))
221		keysAtL, err := t.getKeysAtLevel(l + 1)
222		if err != nil {
223			return nil, err
224		}
225
226		buckets := splitInBuckets(kvs, nCPU)
227
228		// 2. use keys at level L as roots of the subtrees under each one
229		var subRoots [][]byte
230		// TODO parallelize
231		for i := 0; i < len(keysAtL); i++ {
232			bucketTree := Tree{tx: t.tx, db: t.db, maxLevels: t.maxLevels,
233				hashFunction: t.hashFunction, root: keysAtL[i]}
234
235			// 3. and do CASE B for each
236			_, bucketExcedents, err := bucketTree.caseB(l, buckets[i])
237			if err != nil {
238				return nil, err
239			}
240			excedents = append(excedents, bucketExcedents...)
241			subRoots = append(subRoots, bucketTree.root)
242		}
243		// 4. go upFromKeys from the new roots of the subtrees
244		newRoot, err := t.upFromKeys(subRoots)
245		if err != nil {
246			return nil, err
247		}
248		t.root = newRoot
249
250		var invalids []int
251		for i := 0; i < len(excedents); i++ {
252			// Add until the level L
253			err = t.add(0, excedents[i].k, excedents[i].v)
254			if err != nil {
255				invalids = append(invalids, excedents[i].pos) // TODO WIP
256			}
257		}
258
259		return invalids, nil
260	}
261
262	// CASE D
263	if true { // TODO enter in CASE D if len(keysAtL)=nCPU, if not, CASE E
264		return t.caseD(nCPU, l, kvs)
265	}
266
267	// TODO store t.root into DB
268	// TODO update NLeafs from DB
269
270	return nil, fmt.Errorf("UNIMPLEMENTED")
271}
272
273func (t *Tree) caseB(l int, kvs []kv) ([]int, []kv, error) {
274	// get already existing keys
275	aKs, aVs, err := t.getLeafs(t.root)
276	if err != nil {
277		return nil, nil, err
278	}
279	aKvs, err := t.keysValuesToKvs(aKs, aVs)
280	if err != nil {
281		return nil, nil, err
282	}
283	// add already existing key-values to the inputted key-values
284	kvs = append(kvs, aKvs...)
285
286	// proceed with CASE A
287	sortKvs(kvs)
288
289	// cutPowerOfTwo, the excedent add it as normal Tree.Add
290	kvsP2, kvsNonP2 := cutPowerOfTwo(kvs)
291	invalids, err := t.buildTreeBottomUpSingleThread(kvsP2)
292	if err != nil {
293		return nil, nil, err
294	}
295	// return the excedents which will be added at the full tree at the end
296	return invalids, kvsNonP2, nil
297}
298
299func (t *Tree) caseD(nCPU, l int, kvs []kv) ([]int, error) {
300	fmt.Println("CASE D", nCPU)
301	keysAtL, err := t.getKeysAtLevel(l + 1)
302	if err != nil {
303		return nil, err
304	}
305	buckets := splitInBuckets(kvs, nCPU)
306
307	var subRoots [][]byte
308	var invalids []int
309	for i := 0; i < len(keysAtL); i++ {
310		bucketTree := Tree{tx: t.tx, db: t.db, maxLevels: t.maxLevels, // maxLevels-l
311			hashFunction: t.hashFunction, root: keysAtL[i]}
312
313		for j := 0; j < len(buckets[i]); j++ {
314			if err = bucketTree.add(l, buckets[i][j].k, buckets[i][j].v); err != nil {
315				fmt.Println("failed", buckets[i][j].k[:4])
316
317				panic(err)
318				// invalids = append(invalids, buckets[i][j].pos)
319			}
320		}
321		subRoots = append(subRoots, bucketTree.root)
322	}
323	newRoot, err := t.upFromKeys(subRoots)
324	if err != nil {
325		return nil, err
326	}
327	t.root = newRoot
328
329	return invalids, nil
330}
331
332func splitInBuckets(kvs []kv, nBuckets int) [][]kv {
333	buckets := make([][]kv, nBuckets)
334	// 1. classify the keyvalues into buckets
335	for i := 0; i < len(kvs); i++ {
336		pair := kvs[i]
337
338		// bucketnum := keyToBucket(pair.k, nBuckets)
339		bucketnum := keyToBucket(pair.keyPath, nBuckets)
340		buckets[bucketnum] = append(buckets[bucketnum], pair)
341	}
342	return buckets
343}
344
345// TODO rename in a more 'real' name (calculate bucket from/for key)
346func keyToBucket(k []byte, nBuckets int) int {
347	nLevels := int(math.Log2(float64(nBuckets)))
348	b := make([]int, nBuckets)
349	for i := 0; i < nBuckets; i++ {
350		b[i] = i
351	}
352	r := b
353	mid := len(r) / 2 //nolint:gomnd
354	for i := 0; i < nLevels; i++ {
355		if int(k[i/8]&(1<<(i%8))) != 0 {
356			r = r[mid:]
357			mid = len(r) / 2 //nolint:gomnd
358		} else {
359			r = r[:mid]
360			mid = len(r) / 2 //nolint:gomnd
361		}
362	}
363	return r[0]
364}
365
366type kv struct {
367	pos     int // original position in the array
368	keyPath []byte
369	k       []byte
370	v       []byte
371}
372
373// compareBytes compares byte slices where the bytes are compared from left to
374// right and each byte is compared by bit from right to left
375func compareBytes(a, b []byte) bool {
376	// WIP
377	for i := 0; i < len(a); i++ {
378		for j := 0; j < 8; j++ {
379			aBit := a[i] & (1 << j)
380			bBit := b[i] & (1 << j)
381			if aBit > bBit {
382				return false
383			} else if aBit < bBit {
384				return true
385			}
386		}
387	}
388	return false
389}
390
391// sortKvs sorts the kv by path
392func sortKvs(kvs []kv) {
393	sort.Slice(kvs, func(i, j int) bool {
394		return compareBytes(kvs[i].keyPath, kvs[j].keyPath)
395	})
396}
397
398func (t *Tree) keysValuesToKvs(ks, vs [][]byte) ([]kv, error) {
399	if len(ks) != len(vs) {
400		return nil, fmt.Errorf("len(keys)!=len(values) (%d!=%d)",
401			len(ks), len(vs))
402	}
403	kvs := make([]kv, len(ks))
404	for i := 0; i < len(ks); i++ {
405		keyPath := make([]byte, t.hashFunction.Len())
406		copy(keyPath[:], ks[i])
407		kvs[i].pos = i
408		kvs[i].keyPath = ks[i]
409		kvs[i].k = ks[i]
410		kvs[i].v = vs[i]
411	}
412
413	return kvs, nil
414}
415
416/*
417func (t *Tree) kvsToKeysValues(kvs []kv) ([][]byte, [][]byte) {
418	ks := make([][]byte, len(kvs))
419	vs := make([][]byte, len(kvs))
420	for i := 0; i < len(kvs); i++ {
421		ks[i] = kvs[i].k
422		vs[i] = kvs[i].v
423	}
424	return ks, vs
425}
426*/
427
428// buildTreeBottomUp splits the key-values into n Buckets (where n is the number
429// of CPUs), in parallel builds a subtree for each bucket, once all the subtrees
430// are built, uses the subtrees roots as keys for a new tree, which as result
431// will have the complete Tree build from bottom to up, where until the
432// log2(nCPU) level it has been computed in parallel.
433func (t *Tree) buildTreeBottomUp(nCPU int, kvs []kv) ([]int, error) {
434	buckets := splitInBuckets(kvs, nCPU)
435	subRoots := make([][]byte, nCPU)
436	invalidsInBucket := make([][]int, nCPU)
437	txs := make([]db.Tx, nCPU)
438
439	var wg sync.WaitGroup
440	wg.Add(nCPU)
441	for i := 0; i < nCPU; i++ {
442		go func(cpu int) {
443			sortKvs(buckets[cpu])
444
445			var err error
446			txs[cpu], err = t.db.NewTx()
447			if err != nil {
448				panic(err) // TODO
449			}
450			bucketTree := Tree{tx: txs[cpu], db: t.db, maxLevels: t.maxLevels,
451				hashFunction: t.hashFunction, root: t.emptyHash}
452
453			currInvalids, err := bucketTree.buildTreeBottomUpSingleThread(buckets[cpu])
454			if err != nil {
455				panic(err) // TODO
456			}
457			invalidsInBucket[cpu] = currInvalids
458			subRoots[cpu] = bucketTree.root
459			wg.Done()
460		}(i)
461	}
462	wg.Wait()
463
464	newRoot, err := t.upFromKeys(subRoots)
465	if err != nil {
466		return nil, err
467	}
468	t.root = newRoot
469
470	var invalids []int
471	for i := 0; i < len(invalidsInBucket); i++ {
472		invalids = append(invalids, invalidsInBucket[i]...)
473	}
474	return invalids, err
475}
476
477// buildTreeBottomUpSingleThread builds the tree with the given []kv from bottom
478// to the root. keys & values must be sorted by path, and the array ks must be
479// length multiple of 2
480func (t *Tree) buildTreeBottomUpSingleThread(kvs []kv) ([]int, error) {
481	// TODO check that log2(len(leafs)) < t.maxLevels, if not, maxLevels
482	// would be reached and should return error
483
484	var invalids []int
485	// build the leafs
486	leafKeys := make([][]byte, len(kvs))
487	for i := 0; i < len(kvs); i++ {
488		// TODO handle the case where Key&Value == 0
489		leafKey, leafValue, err := newLeafValue(t.hashFunction, kvs[i].k, kvs[i].v)
490		if err != nil {
491			// return nil, err
492			invalids = append(invalids, kvs[i].pos)
493		}
494		// store leafKey & leafValue to db
495		if err := t.tx.Put(leafKey, leafValue); err != nil {
496			// return nil, err
497			invalids = append(invalids, kvs[i].pos)
498		}
499		leafKeys[i] = leafKey
500	}
501	r, err := t.upFromKeys(leafKeys)
502	if err != nil {
503		return invalids, err
504	}
505	t.root = r
506	return invalids, nil
507}
508
509// keys & values must be sorted by path, and the array ks must be length
510// multiple of 2
511func (t *Tree) upFromKeys(ks [][]byte) ([]byte, error) {
512	if len(ks) == 1 {
513		return ks[0], nil
514	}
515
516	var rKs [][]byte
517	for i := 0; i < len(ks); i += 2 {
518		// TODO handle the case where Key&Value == 0
519		k, v, err := newIntermediate(t.hashFunction, ks[i], ks[i+1])
520		if err != nil {
521			return nil, err
522		}
523		// store k-v to db
524		if err = t.tx.Put(k, v); err != nil {
525			return nil, err
526		}
527		rKs = append(rKs, k)
528	}
529	return t.upFromKeys(rKs)
530}
531
532func (t *Tree) getLeafs(root []byte) ([][]byte, [][]byte, error) {
533	var ks, vs [][]byte
534	err := t.iter(root, func(k, v []byte) {
535		if v[0] != PrefixValueLeaf {
536			return
537		}
538		leafK, leafV := readLeafValue(v)
539		ks = append(ks, leafK)
540		vs = append(vs, leafV)
541	})
542	return ks, vs, err
543}
544
545func (t *Tree) getKeysAtLevel(l int) ([][]byte, error) {
546	var keys [][]byte
547	err := t.iterWithStop(t.root, 0, func(currLvl int, k, v []byte) bool {
548		if currLvl == l {
549			keys = append(keys, k)
550		}
551		if currLvl >= l {
552			return true // to stop the iter from going down
553		}
554		return false
555	})
556
557	return keys, err
558}
559
560// cutPowerOfTwo returns []kv of length that is a power of 2, and a second []kv
561// with the extra elements that don't fit in a power of 2 length
562func cutPowerOfTwo(kvs []kv) ([]kv, []kv) {
563	x := len(kvs)
564	if (x & (x - 1)) != 0 {
565		p2 := highestPowerOfTwo(x)
566		return kvs[:p2], kvs[p2:]
567	}
568	return kvs, nil
569}
570
571func highestPowerOfTwo(n int) int {
572	res := 0
573	for i := n; i >= 1; i-- {
574		if (i & (i - 1)) == 0 {
575			res = i
576			break
577		}
578	}
579	return res
580}
581
582// func computeSimpleAddCost(nLeafs int) int {
583//         // nLvls 2^nLvls
584//         nLvls := int(math.Log2(float64(nLeafs)))
585//         return nLvls * int(math.Pow(2, float64(nLvls)))
586// }
587//
588// func computeBottomUpAddCost(nLeafs int) int {
589//         // 2^nLvls * 2 - 1
590//         nLvls := int(math.Log2(float64(nLeafs)))
591//         return (int(math.Pow(2, float64(nLvls))) * 2) - 1
592// }