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.

592 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. fmt.Println("CASE D", nCPU)
  254. keysAtL, err := t.getKeysAtLevel(l + 1)
  255. if err != nil {
  256. return nil, err
  257. }
  258. buckets := splitInBuckets(kvs, nCPU)
  259. var subRoots [][]byte
  260. var invalids []int
  261. for i := 0; i < len(keysAtL); i++ {
  262. bucketTree := Tree{tx: t.tx, db: t.db, maxLevels: t.maxLevels, // maxLevels-l
  263. hashFunction: t.hashFunction, root: keysAtL[i]}
  264. for j := 0; j < len(buckets[i]); j++ {
  265. if err = bucketTree.add(l, buckets[i][j].k, buckets[i][j].v); err != nil {
  266. fmt.Println("failed", buckets[i][j].k[:4])
  267. panic(err)
  268. // invalids = append(invalids, buckets[i][j].pos)
  269. }
  270. }
  271. subRoots = append(subRoots, bucketTree.root)
  272. }
  273. newRoot, err := t.upFromKeys(subRoots)
  274. if err != nil {
  275. return nil, err
  276. }
  277. t.root = newRoot
  278. return invalids, nil
  279. }
  280. func splitInBuckets(kvs []kv, nBuckets int) [][]kv {
  281. buckets := make([][]kv, nBuckets)
  282. // 1. classify the keyvalues into buckets
  283. for i := 0; i < len(kvs); i++ {
  284. pair := kvs[i]
  285. // bucketnum := keyToBucket(pair.k, nBuckets)
  286. bucketnum := keyToBucket(pair.keyPath, nBuckets)
  287. buckets[bucketnum] = append(buckets[bucketnum], pair)
  288. }
  289. return buckets
  290. }
  291. // TODO rename in a more 'real' name (calculate bucket from/for key)
  292. func keyToBucket(k []byte, nBuckets int) int {
  293. nLevels := int(math.Log2(float64(nBuckets)))
  294. b := make([]int, nBuckets)
  295. for i := 0; i < nBuckets; i++ {
  296. b[i] = i
  297. }
  298. r := b
  299. mid := len(r) / 2 //nolint:gomnd
  300. for i := 0; i < nLevels; i++ {
  301. if int(k[i/8]&(1<<(i%8))) != 0 {
  302. r = r[mid:]
  303. mid = len(r) / 2 //nolint:gomnd
  304. } else {
  305. r = r[:mid]
  306. mid = len(r) / 2 //nolint:gomnd
  307. }
  308. }
  309. return r[0]
  310. }
  311. type kv struct {
  312. pos int // original position in the array
  313. keyPath []byte
  314. k []byte
  315. v []byte
  316. }
  317. // compareBytes compares byte slices where the bytes are compared from left to
  318. // right and each byte is compared by bit from right to left
  319. func compareBytes(a, b []byte) bool {
  320. // WIP
  321. for i := 0; i < len(a); i++ {
  322. for j := 0; j < 8; j++ {
  323. aBit := a[i] & (1 << j)
  324. bBit := b[i] & (1 << j)
  325. if aBit > bBit {
  326. return false
  327. } else if aBit < bBit {
  328. return true
  329. }
  330. }
  331. }
  332. return false
  333. }
  334. // sortKvs sorts the kv by path
  335. func sortKvs(kvs []kv) {
  336. sort.Slice(kvs, func(i, j int) bool {
  337. return compareBytes(kvs[i].keyPath, kvs[j].keyPath)
  338. })
  339. }
  340. func (t *Tree) keysValuesToKvs(ks, vs [][]byte) ([]kv, error) {
  341. if len(ks) != len(vs) {
  342. return nil, fmt.Errorf("len(keys)!=len(values) (%d!=%d)",
  343. len(ks), len(vs))
  344. }
  345. kvs := make([]kv, len(ks))
  346. for i := 0; i < len(ks); i++ {
  347. keyPath := make([]byte, t.hashFunction.Len())
  348. copy(keyPath[:], ks[i])
  349. kvs[i].pos = i
  350. kvs[i].keyPath = ks[i]
  351. kvs[i].k = ks[i]
  352. kvs[i].v = vs[i]
  353. }
  354. return kvs, nil
  355. }
  356. /*
  357. func (t *Tree) kvsToKeysValues(kvs []kv) ([][]byte, [][]byte) {
  358. ks := make([][]byte, len(kvs))
  359. vs := make([][]byte, len(kvs))
  360. for i := 0; i < len(kvs); i++ {
  361. ks[i] = kvs[i].k
  362. vs[i] = kvs[i].v
  363. }
  364. return ks, vs
  365. }
  366. */
  367. // buildTreeBottomUp splits the key-values into n Buckets (where n is the number
  368. // of CPUs), in parallel builds a subtree for each bucket, once all the subtrees
  369. // are built, uses the subtrees roots as keys for a new tree, which as result
  370. // will have the complete Tree build from bottom to up, where until the
  371. // log2(nCPU) level it has been computed in parallel.
  372. func (t *Tree) buildTreeBottomUp(nCPU int, kvs []kv) ([]int, error) {
  373. buckets := splitInBuckets(kvs, nCPU)
  374. subRoots := make([][]byte, nCPU)
  375. invalidsInBucket := make([][]int, nCPU)
  376. txs := make([]db.Tx, nCPU)
  377. var wg sync.WaitGroup
  378. wg.Add(nCPU)
  379. for i := 0; i < nCPU; i++ {
  380. go func(cpu int) {
  381. sortKvs(buckets[cpu])
  382. var err error
  383. txs[cpu], err = t.db.NewTx()
  384. if err != nil {
  385. panic(err) // TODO
  386. }
  387. bucketTree := Tree{tx: txs[cpu], db: t.db, maxLevels: t.maxLevels,
  388. hashFunction: t.hashFunction, root: t.emptyHash}
  389. currInvalids, err := bucketTree.buildTreeBottomUpSingleThread(buckets[cpu])
  390. if err != nil {
  391. panic(err) // TODO
  392. }
  393. invalidsInBucket[cpu] = currInvalids
  394. subRoots[cpu] = bucketTree.root
  395. wg.Done()
  396. }(i)
  397. }
  398. wg.Wait()
  399. newRoot, err := t.upFromKeys(subRoots)
  400. if err != nil {
  401. return nil, err
  402. }
  403. t.root = newRoot
  404. var invalids []int
  405. for i := 0; i < len(invalidsInBucket); i++ {
  406. invalids = append(invalids, invalidsInBucket[i]...)
  407. }
  408. return invalids, err
  409. }
  410. // buildTreeBottomUpSingleThread builds the tree with the given []kv from bottom
  411. // to the root. keys & values must be sorted by path, and the array ks must be
  412. // length multiple of 2
  413. func (t *Tree) buildTreeBottomUpSingleThread(kvs []kv) ([]int, error) {
  414. // TODO check that log2(len(leafs)) < t.maxLevels, if not, maxLevels
  415. // would be reached and should return error
  416. var invalids []int
  417. // build the leafs
  418. leafKeys := make([][]byte, len(kvs))
  419. for i := 0; i < len(kvs); i++ {
  420. // TODO handle the case where Key&Value == 0
  421. leafKey, leafValue, err := newLeafValue(t.hashFunction, kvs[i].k, kvs[i].v)
  422. if err != nil {
  423. // return nil, err
  424. invalids = append(invalids, kvs[i].pos)
  425. }
  426. // store leafKey & leafValue to db
  427. if err := t.tx.Put(leafKey, leafValue); err != nil {
  428. // return nil, err
  429. invalids = append(invalids, kvs[i].pos)
  430. }
  431. leafKeys[i] = leafKey
  432. }
  433. r, err := t.upFromKeys(leafKeys)
  434. if err != nil {
  435. return invalids, err
  436. }
  437. t.root = r
  438. return invalids, nil
  439. }
  440. // keys & values must be sorted by path, and the array ks must be length
  441. // multiple of 2
  442. func (t *Tree) upFromKeys(ks [][]byte) ([]byte, error) {
  443. if len(ks) == 1 {
  444. return ks[0], nil
  445. }
  446. var rKs [][]byte
  447. for i := 0; i < len(ks); i += 2 {
  448. // TODO handle the case where Key&Value == 0
  449. k, v, err := newIntermediate(t.hashFunction, ks[i], ks[i+1])
  450. if err != nil {
  451. return nil, err
  452. }
  453. // store k-v to db
  454. if err = t.tx.Put(k, v); err != nil {
  455. return nil, err
  456. }
  457. rKs = append(rKs, k)
  458. }
  459. return t.upFromKeys(rKs)
  460. }
  461. func (t *Tree) getLeafs(root []byte) ([][]byte, [][]byte, error) {
  462. var ks, vs [][]byte
  463. err := t.iter(root, func(k, v []byte) {
  464. if v[0] != PrefixValueLeaf {
  465. return
  466. }
  467. leafK, leafV := readLeafValue(v)
  468. ks = append(ks, leafK)
  469. vs = append(vs, leafV)
  470. })
  471. return ks, vs, err
  472. }
  473. func (t *Tree) getKeysAtLevel(l int) ([][]byte, error) {
  474. var keys [][]byte
  475. err := t.iterWithStop(t.root, 0, func(currLvl int, k, v []byte) bool {
  476. if currLvl == l {
  477. keys = append(keys, k)
  478. }
  479. if currLvl >= l {
  480. return true // to stop the iter from going down
  481. }
  482. return false
  483. })
  484. return keys, err
  485. }
  486. // cutPowerOfTwo returns []kv of length that is a power of 2, and a second []kv
  487. // with the extra elements that don't fit in a power of 2 length
  488. func cutPowerOfTwo(kvs []kv) ([]kv, []kv) {
  489. x := len(kvs)
  490. if (x & (x - 1)) != 0 {
  491. p2 := highestPowerOfTwo(x)
  492. return kvs[:p2], kvs[p2:]
  493. }
  494. return kvs, nil
  495. }
  496. func highestPowerOfTwo(n int) int {
  497. res := 0
  498. for i := n; i >= 1; i-- {
  499. if (i & (i - 1)) == 0 {
  500. res = i
  501. break
  502. }
  503. }
  504. return res
  505. }
  506. // func computeSimpleAddCost(nLeafs int) int {
  507. // // nLvls 2^nLvls
  508. // nLvls := int(math.Log2(float64(nLeafs)))
  509. // return nLvls * int(math.Pow(2, float64(nLvls)))
  510. // }
  511. //
  512. // func computeBottomUpAddCost(nLeafs int) int {
  513. // // 2^nLvls * 2 - 1
  514. // nLvls := int(math.Log2(float64(nLeafs)))
  515. // return (int(math.Pow(2, float64(nLvls))) * 2) - 1
  516. // }