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.

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