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