You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

608 lines
15 KiB

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