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	nCPU := runtime.NumCPU()
172
173	// CASE A: if nLeafs==0 (root==0)
174	if bytes.Equal(t.root, t.emptyHash) {
175		// if len(kvs) is not a power of 2, cut at the bigger power
176		// of two under len(kvs), build the tree with that, and add
177		// later the excedents
178		kvsP2, kvsNonP2 := cutPowerOfTwo(kvs)
179		invalids, err := t.buildTreeBottomUp(nCPU, kvsP2)
180		if err != nil {
181			return nil, err
182		}
183		for i := 0; i < len(kvsNonP2); i++ {
184			err = t.add(0, kvsNonP2[i].k, kvsNonP2[i].v)
185			if err != nil {
186				invalids = append(invalids, kvsNonP2[i].pos)
187			}
188		}
189		return invalids, nil
190	}
191
192	// CASE B: if nLeafs<nBuckets
193	nLeafs, err := t.GetNLeafs()
194	if err != nil {
195		return nil, err
196	}
197	if nLeafs < minLeafsThreshold { // CASE B
198		invalids, excedents, err := t.caseB(0, kvs)
199		if err != nil {
200			return nil, err
201		}
202		// add the excedents
203		for i := 0; i < len(excedents); i++ {
204			err = t.add(0, excedents[i].k, excedents[i].v)
205			if err != nil {
206				invalids = append(invalids, excedents[i].pos)
207			}
208		}
209		return invalids, nil
210	}
211
212	// CASE C: if nLeafs>=minLeafsThreshold && (nLeafs/nBuckets) < minLeafsThreshold
213	// available parallelization, will need to be a power of 2 (2**n)
214	var excedents []kv
215	l := int(math.Log2(float64(nCPU)))
216	if nLeafs >= minLeafsThreshold && (nLeafs/nCPU) < minLeafsThreshold {
217		// TODO move to own function
218		// 1. go down until level L (L=log2(nBuckets))
219		keysAtL, err := t.getKeysAtLevel(l + 1)
220		if err != nil {
221			return nil, err
222		}
223
224		buckets := splitInBuckets(kvs, nCPU)
225
226		// 2. use keys at level L as roots of the subtrees under each one
227		var subRoots [][]byte
228		// TODO parallelize
229		for i := 0; i < len(keysAtL); i++ {
230			bucketTree := Tree{tx: t.tx, db: t.db, maxLevels: t.maxLevels,
231				hashFunction: t.hashFunction, root: keysAtL[i]}
232
233			// 3. and do CASE B for each
234			_, bucketExcedents, err := bucketTree.caseB(l, buckets[i])
235			if err != nil {
236				return nil, err
237			}
238			excedents = append(excedents, bucketExcedents...)
239			subRoots = append(subRoots, bucketTree.root)
240		}
241		// 4. go upFromKeys from the new roots of the subtrees
242		newRoot, err := t.upFromKeys(subRoots)
243		if err != nil {
244			return nil, err
245		}
246		t.root = newRoot
247
248		var invalids []int
249		for i := 0; i < len(excedents); i++ {
250			// Add until the level L
251			err = t.add(0, excedents[i].k, excedents[i].v)
252			if err != nil {
253				invalids = append(invalids, excedents[i].pos) // TODO WIP
254			}
255		}
256
257		return invalids, nil
258	}
259
260	// TODO store t.root into DB
261	// TODO update NLeafs from DB
262
263	return nil, fmt.Errorf("UNIMPLEMENTED")
264}
265
266func (t *Tree) caseB(l int, kvs []kv) ([]int, []kv, error) {
267	// get already existing keys
268	aKs, aVs, err := t.getLeafs(t.root)
269	if err != nil {
270		return nil, nil, err
271	}
272	aKvs, err := t.keysValuesToKvs(aKs, aVs)
273	if err != nil {
274		return nil, nil, err
275	}
276	// add already existing key-values to the inputted key-values
277	kvs = append(kvs, aKvs...)
278
279	// proceed with CASE A
280	sortKvs(kvs)
281
282	// cutPowerOfTwo, the excedent add it as normal Tree.Add
283	kvsP2, kvsNonP2 := cutPowerOfTwo(kvs)
284	invalids, err := t.buildTreeBottomUpSingleThread(kvsP2)
285	if err != nil {
286		return nil, nil, err
287	}
288	// return the excedents which will be added at the full tree at the end
289	return invalids, kvsNonP2, nil
290}
291
292func splitInBuckets(kvs []kv, nBuckets int) [][]kv {
293	buckets := make([][]kv, nBuckets)
294	// 1. classify the keyvalues into buckets
295	for i := 0; i < len(kvs); i++ {
296		pair := kvs[i]
297
298		bucketnum := keyToBucket(pair.k, nBuckets)
299		buckets[bucketnum] = append(buckets[bucketnum], pair)
300	}
301	return buckets
302}
303
304// TODO rename in a more 'real' name (calculate bucket from/for key)
305func keyToBucket(k []byte, nBuckets int) int {
306	nLevels := int(math.Log2(float64(nBuckets)))
307	b := make([]int, nBuckets)
308	for i := 0; i < nBuckets; i++ {
309		b[i] = i
310	}
311	r := b
312	mid := len(r) / 2 //nolint:gomnd
313	for i := 0; i < nLevels; i++ {
314		if int(k[i/8]&(1<<(i%8))) != 0 {
315			r = r[mid:]
316			mid = len(r) / 2 //nolint:gomnd
317		} else {
318			r = r[:mid]
319			mid = len(r) / 2 //nolint:gomnd
320		}
321	}
322	return r[0]
323}
324
325type kv struct {
326	pos     int // original position in the array
327	keyPath []byte
328	k       []byte
329	v       []byte
330}
331
332// compareBytes compares byte slices where the bytes are compared from left to
333// right and each byte is compared by bit from right to left
334func compareBytes(a, b []byte) bool {
335	// WIP
336	for i := 0; i < len(a); i++ {
337		for j := 0; j < 8; j++ {
338			aBit := a[i] & (1 << j)
339			bBit := b[i] & (1 << j)
340			if aBit > bBit {
341				return false
342			} else if aBit < bBit {
343				return true
344			}
345		}
346	}
347	return false
348}
349
350// sortKvs sorts the kv by path
351func sortKvs(kvs []kv) {
352	sort.Slice(kvs, func(i, j int) bool {
353		return compareBytes(kvs[i].keyPath, kvs[j].keyPath)
354	})
355}
356
357func (t *Tree) keysValuesToKvs(ks, vs [][]byte) ([]kv, error) {
358	if len(ks) != len(vs) {
359		return nil, fmt.Errorf("len(keys)!=len(values) (%d!=%d)",
360			len(ks), len(vs))
361	}
362	kvs := make([]kv, len(ks))
363	for i := 0; i < len(ks); i++ {
364		keyPath := make([]byte, t.hashFunction.Len())
365		copy(keyPath[:], ks[i])
366		kvs[i].pos = i
367		kvs[i].keyPath = ks[i]
368		kvs[i].k = ks[i]
369		kvs[i].v = vs[i]
370	}
371
372	return kvs, nil
373}
374
375/*
376func (t *Tree) kvsToKeysValues(kvs []kv) ([][]byte, [][]byte) {
377	ks := make([][]byte, len(kvs))
378	vs := make([][]byte, len(kvs))
379	for i := 0; i < len(kvs); i++ {
380		ks[i] = kvs[i].k
381		vs[i] = kvs[i].v
382	}
383	return ks, vs
384}
385*/
386
387// buildTreeBottomUp splits the key-values into n Buckets (where n is the number
388// of CPUs), in parallel builds a subtree for each bucket, once all the subtrees
389// are built, uses the subtrees roots as keys for a new tree, which as result
390// will have the complete Tree build from bottom to up, where until the
391// log2(nCPU) level it has been computed in parallel.
392func (t *Tree) buildTreeBottomUp(nCPU int, kvs []kv) ([]int, error) {
393	buckets := splitInBuckets(kvs, nCPU)
394	subRoots := make([][]byte, nCPU)
395	invalidsInBucket := make([][]int, nCPU)
396	txs := make([]db.Tx, nCPU)
397
398	var wg sync.WaitGroup
399	wg.Add(nCPU)
400	for i := 0; i < nCPU; i++ {
401		go func(cpu int) {
402			sortKvs(buckets[cpu])
403
404			var err error
405			txs[cpu], err = t.db.NewTx()
406			if err != nil {
407				panic(err) // TODO
408			}
409			bucketTree := Tree{tx: txs[cpu], db: t.db, maxLevels: t.maxLevels,
410				hashFunction: t.hashFunction, root: t.emptyHash}
411
412			currInvalids, err := bucketTree.buildTreeBottomUpSingleThread(buckets[cpu])
413			if err != nil {
414				panic(err) // TODO
415			}
416			invalidsInBucket[cpu] = currInvalids
417			subRoots[cpu] = bucketTree.root
418			wg.Done()
419		}(i)
420	}
421	wg.Wait()
422
423	newRoot, err := t.upFromKeys(subRoots)
424	if err != nil {
425		return nil, err
426	}
427	t.root = newRoot
428
429	var invalids []int
430	for i := 0; i < len(invalidsInBucket); i++ {
431		invalids = append(invalids, invalidsInBucket[i]...)
432	}
433	return invalids, err
434}
435
436// buildTreeBottomUpSingleThread builds the tree with the given []kv from bottom
437// to the root. keys & values must be sorted by path, and the array ks must be
438// length multiple of 2
439func (t *Tree) buildTreeBottomUpSingleThread(kvs []kv) ([]int, error) {
440	// TODO check that log2(len(leafs)) < t.maxLevels, if not, maxLevels
441	// would be reached and should return error
442
443	var invalids []int
444	// build the leafs
445	leafKeys := make([][]byte, len(kvs))
446	for i := 0; i < len(kvs); i++ {
447		// TODO handle the case where Key&Value == 0
448		leafKey, leafValue, err := newLeafValue(t.hashFunction, kvs[i].k, kvs[i].v)
449		if err != nil {
450			// return nil, err
451			invalids = append(invalids, kvs[i].pos)
452		}
453		// store leafKey & leafValue to db
454		if err := t.tx.Put(leafKey, leafValue); err != nil {
455			// return nil, err
456			invalids = append(invalids, kvs[i].pos)
457		}
458		leafKeys[i] = leafKey
459	}
460	r, err := t.upFromKeys(leafKeys)
461	if err != nil {
462		return invalids, err
463	}
464	t.root = r
465	return invalids, nil
466}
467
468// keys & values must be sorted by path, and the array ks must be length
469// multiple of 2
470func (t *Tree) upFromKeys(ks [][]byte) ([]byte, error) {
471	if len(ks) == 1 {
472		return ks[0], nil
473	}
474
475	var rKs [][]byte
476	for i := 0; i < len(ks); i += 2 {
477		// TODO handle the case where Key&Value == 0
478		k, v, err := newIntermediate(t.hashFunction, ks[i], ks[i+1])
479		if err != nil {
480			return nil, err
481		}
482		// store k-v to db
483		if err = t.tx.Put(k, v); err != nil {
484			return nil, err
485		}
486		rKs = append(rKs, k)
487	}
488	return t.upFromKeys(rKs)
489}
490
491func (t *Tree) getLeafs(root []byte) ([][]byte, [][]byte, error) {
492	var ks, vs [][]byte
493	err := t.iter(root, func(k, v []byte) {
494		if v[0] != PrefixValueLeaf {
495			return
496		}
497		leafK, leafV := readLeafValue(v)
498		ks = append(ks, leafK)
499		vs = append(vs, leafV)
500	})
501	return ks, vs, err
502}
503
504func (t *Tree) getKeysAtLevel(l int) ([][]byte, error) {
505	var keys [][]byte
506	err := t.iterWithStop(t.root, 0, func(currLvl int, k, v []byte) bool {
507		if currLvl == l {
508			keys = append(keys, k)
509		}
510		if currLvl >= l {
511			return true // to stop the iter from going down
512		}
513		return false
514	})
515
516	return keys, err
517}
518
519// cutPowerOfTwo returns []kv of length that is a power of 2, and a second []kv
520// with the extra elements that don't fit in a power of 2 length
521func cutPowerOfTwo(kvs []kv) ([]kv, []kv) {
522	x := len(kvs)
523	if (x & (x - 1)) != 0 {
524		p2 := highestPowerOfTwo(x)
525		return kvs[:p2], kvs[p2:]
526	}
527	return kvs, nil
528}
529
530func highestPowerOfTwo(n int) int {
531	res := 0
532	for i := n; i >= 1; i-- {
533		if (i & (i - 1)) == 0 {
534			res = i
535			break
536		}
537	}
538	return res
539}
540
541// func computeSimpleAddCost(nLeafs int) int {
542//         // nLvls 2^nLvls
543//         nLvls := int(math.Log2(float64(nLeafs)))
544//         return nLvls * int(math.Pow(2, float64(nLvls)))
545// }
546//
547// func computeBottomUpAddCost(nLeafs int) int {
548//         // 2^nLvls * 2 - 1
549//         nLvls := int(math.Log2(float64(nLeafs)))
550//         return (int(math.Pow(2, float64(nLvls))) * 2) - 1
551// }