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.

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