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.

700 lines
16 KiB

  1. // Package arbo > vt.go implements the Virtual Tree, which computes a tree
  2. // without computing any hash. With the idea of once all the leafs are placed in
  3. // their positions, the hashes can be computed, avoiding computing a node hash
  4. // more than one time.
  5. package arbo
  6. import (
  7. "bytes"
  8. "encoding/hex"
  9. "fmt"
  10. "io"
  11. "math"
  12. "runtime"
  13. "sync"
  14. )
  15. type node struct {
  16. l *node
  17. r *node
  18. k []byte
  19. v []byte
  20. path []bool
  21. h []byte
  22. }
  23. type params struct {
  24. maxLevels int
  25. hashFunction HashFunction
  26. emptyHash []byte
  27. dbg *dbgStats
  28. }
  29. type kv struct {
  30. pos int // original position in the inputted array
  31. keyPath []byte
  32. k []byte
  33. v []byte
  34. }
  35. func (p *params) keysValuesToKvs(ks, vs [][]byte) ([]kv, error) {
  36. if len(ks) != len(vs) {
  37. return nil, fmt.Errorf("len(keys)!=len(values) (%d!=%d)",
  38. len(ks), len(vs))
  39. }
  40. kvs := make([]kv, len(ks))
  41. for i := 0; i < len(ks); i++ {
  42. keyPath := make([]byte, p.hashFunction.Len())
  43. copy(keyPath[:], ks[i])
  44. kvs[i].pos = i
  45. kvs[i].keyPath = keyPath
  46. kvs[i].k = ks[i]
  47. kvs[i].v = vs[i]
  48. }
  49. return kvs, nil
  50. }
  51. // vt stands for virtual tree. It's a tree that does not have any computed hash
  52. // while placing the leafs. Once all the leafs are placed, it computes all the
  53. // hashes. In this way, each node hash is only computed one time (at the end)
  54. // and the tree is computed in memory.
  55. type vt struct {
  56. root *node
  57. params *params
  58. }
  59. func newVT(maxLevels int, hash HashFunction) vt {
  60. return vt{
  61. root: nil,
  62. params: &params{
  63. maxLevels: maxLevels,
  64. hashFunction: hash,
  65. emptyHash: make([]byte, hash.Len()), // empty
  66. },
  67. }
  68. }
  69. // addBatch adds a batch of key-values to the VirtualTree. Returns an array
  70. // containing the indexes of the keys failed to add. Does not include the
  71. // computation of hashes of the nodes neither the storage of the key-values of
  72. // the tree into the db. After addBatch, vt.computeHashes should be called to
  73. // compute the hashes of all the nodes of the tree.
  74. func (t *vt) addBatch(ks, vs [][]byte) ([]int, error) {
  75. nCPU := flp2(runtime.NumCPU())
  76. if nCPU == 1 || len(ks) < nCPU {
  77. var invalids []int
  78. for i := 0; i < len(ks); i++ {
  79. if err := t.add(0, ks[i], vs[i]); err != nil {
  80. invalids = append(invalids, i)
  81. }
  82. }
  83. return invalids, nil
  84. }
  85. l := int(math.Log2(float64(nCPU)))
  86. kvs, err := t.params.keysValuesToKvs(ks, vs)
  87. if err != nil {
  88. return nil, err
  89. }
  90. buckets := splitInBuckets(kvs, nCPU)
  91. nodesAtL, err := t.getNodesAtLevel(l)
  92. if err != nil {
  93. return nil, err
  94. }
  95. if len(nodesAtL) != nCPU && t.root != nil {
  96. /*
  97. Already populated Tree but Unbalanced
  98. - Need to fill M1 and M2, and then will be able to continue with the flow
  99. - Search for M1 & M2 in the inputed Keys
  100. - Add M1 & M2 to the Tree
  101. - From here can continue with the flow
  102. R
  103. / \
  104. / \
  105. / \
  106. * *
  107. | \
  108. | \
  109. | \
  110. L: M1 * M2 * (where M1 and M2 are empty)
  111. / | /
  112. / | /
  113. / | /
  114. A * *
  115. / \ | \
  116. / \ | \
  117. / \ | \
  118. B * * C
  119. / \ |\
  120. ... ... | \
  121. | \
  122. D E
  123. */
  124. // add one key at each bucket, and then continue with the flow
  125. for i := 0; i < len(buckets); i++ {
  126. // add one leaf of the bucket, if there is an error when
  127. // adding the k-v, try to add the next one of the bucket
  128. // (until one is added)
  129. inserted := -1
  130. for j := 0; j < len(buckets[i]); j++ {
  131. if err := t.add(0, buckets[i][j].k, buckets[i][j].v); err == nil {
  132. inserted = j
  133. break
  134. }
  135. }
  136. // remove the inserted element from buckets[i]
  137. if inserted != -1 {
  138. buckets[i] = append(buckets[i][:inserted], buckets[i][inserted+1:]...)
  139. }
  140. }
  141. nodesAtL, err = t.getNodesAtLevel(l)
  142. if err != nil {
  143. return nil, err
  144. }
  145. }
  146. if len(nodesAtL) != nCPU {
  147. return nil, fmt.Errorf("This error should not be reached."+
  148. " len(nodesAtL) != nCPU, len(nodesAtL)=%d, nCPU=%d."+
  149. " Please report it in a new issue:"+
  150. " https://github.com/vocdoni/arbo/issues/new", len(nodesAtL), nCPU)
  151. }
  152. subRoots := make([]*node, nCPU)
  153. invalidsInBucket := make([][]int, nCPU)
  154. var wg sync.WaitGroup
  155. wg.Add(nCPU)
  156. for i := 0; i < nCPU; i++ {
  157. go func(cpu int) {
  158. bucketVT := newVT(t.params.maxLevels, t.params.hashFunction)
  159. bucketVT.root = nodesAtL[cpu]
  160. for j := 0; j < len(buckets[cpu]); j++ {
  161. if err = bucketVT.add(l, buckets[cpu][j].k, buckets[cpu][j].v); err != nil {
  162. invalidsInBucket[cpu] = append(invalidsInBucket[cpu], buckets[cpu][j].pos)
  163. }
  164. }
  165. subRoots[cpu] = bucketVT.root
  166. wg.Done()
  167. }(i)
  168. }
  169. wg.Wait()
  170. var invalids []int
  171. for i := 0; i < len(invalidsInBucket); i++ {
  172. invalids = append(invalids, invalidsInBucket[i]...)
  173. }
  174. newRootNode, err := upFromNodes(subRoots)
  175. if err != nil {
  176. return nil, err
  177. }
  178. t.root = newRootNode
  179. return invalids, nil
  180. }
  181. func (t *vt) getNodesAtLevel(l int) ([]*node, error) {
  182. if t.root == nil {
  183. var r []*node
  184. nChilds := int(math.Pow(2, float64(l))) //nolint:gomnd
  185. for i := 0; i < nChilds; i++ {
  186. r = append(r, nil)
  187. }
  188. return r, nil
  189. }
  190. return t.root.getNodesAtLevel(0, l)
  191. }
  192. func (n *node) getNodesAtLevel(currLvl, l int) ([]*node, error) {
  193. if n == nil {
  194. var r []*node
  195. nChilds := int(math.Pow(2, float64(l-currLvl))) //nolint:gomnd
  196. for i := 0; i < nChilds; i++ {
  197. r = append(r, nil)
  198. }
  199. return r, nil
  200. }
  201. typ := n.typ()
  202. if currLvl == l && typ != vtEmpty {
  203. return []*node{n}, nil
  204. }
  205. if currLvl >= l {
  206. return nil, fmt.Errorf("This error should not be reached."+
  207. " currLvl >= l, currLvl=%d, l=%d."+
  208. " Please report it in a new issue:"+
  209. " https://github.com/vocdoni/arbo/issues/new", currLvl, l)
  210. }
  211. var nodes []*node
  212. nodesL, err := n.l.getNodesAtLevel(currLvl+1, l)
  213. if err != nil {
  214. return nil, err
  215. }
  216. nodes = append(nodes, nodesL...)
  217. nodesR, err := n.r.getNodesAtLevel(currLvl+1, l)
  218. if err != nil {
  219. return nil, err
  220. }
  221. nodes = append(nodes, nodesR...)
  222. return nodes, nil
  223. }
  224. // upFromNodes builds the tree from the bottom to up
  225. func upFromNodes(ns []*node) (*node, error) {
  226. if len(ns) == 1 {
  227. return ns[0], nil
  228. }
  229. var res []*node
  230. for i := 0; i < len(ns); i += 2 {
  231. if (ns[i].typ() == vtEmpty && ns[i+1].typ() == vtEmpty) ||
  232. (ns[i].typ() == vtLeaf && ns[i+1].typ() == vtEmpty) {
  233. // when both sub nodes are empty, the parent is also empty
  234. // or
  235. // when 1st sub node is a leaf but the 2nd is empty, the
  236. // leaf is used as parent
  237. res = append(res, ns[i])
  238. continue
  239. }
  240. if ns[i].typ() == vtEmpty && ns[i+1].typ() == vtLeaf {
  241. // when 2nd sub node is a leaf but the 1st is empty, the
  242. // leaf is used as 'parent'
  243. res = append(res, ns[i+1])
  244. continue
  245. }
  246. n := &node{
  247. l: ns[i],
  248. r: ns[i+1],
  249. }
  250. res = append(res, n)
  251. }
  252. return upFromNodes(res)
  253. }
  254. // add adds a key&value as a leaf in the VirtualTree
  255. func (t *vt) add(fromLvl int, k, v []byte) error {
  256. leaf := newLeafNode(t.params, k, v)
  257. if t.root == nil {
  258. t.root = leaf
  259. return nil
  260. }
  261. if err := t.root.add(t.params, fromLvl, leaf); err != nil {
  262. return err
  263. }
  264. return nil
  265. }
  266. // computeHashes should be called after all the vt.add is used, once all the
  267. // leafs are in the tree. Computes the hashes of the tree, parallelizing in the
  268. // available CPUs.
  269. func (t *vt) computeHashes() ([][2][]byte, error) {
  270. var err error
  271. nCPU := flp2(runtime.NumCPU())
  272. l := int(math.Log2(float64(nCPU)))
  273. nodesAtL, err := t.getNodesAtLevel(l)
  274. if err != nil {
  275. return nil, err
  276. }
  277. subRoots := make([]*node, nCPU)
  278. bucketPairs := make([][][2][]byte, nCPU)
  279. dbgStatsPerBucket := make([]*dbgStats, nCPU)
  280. errs := make([]error, nCPU)
  281. var wg sync.WaitGroup
  282. wg.Add(nCPU)
  283. for i := 0; i < nCPU; i++ {
  284. go func(cpu int) {
  285. bucketVT := newVT(t.params.maxLevels-l, t.params.hashFunction)
  286. bucketVT.params.dbg = newDbgStats()
  287. bucketVT.root = nodesAtL[cpu]
  288. bucketPairs[cpu], err = bucketVT.root.computeHashes(l,
  289. t.params.maxLevels, bucketVT.params, bucketPairs[cpu])
  290. if err != nil {
  291. errs[cpu] = err
  292. }
  293. subRoots[cpu] = bucketVT.root
  294. dbgStatsPerBucket[cpu] = bucketVT.params.dbg
  295. wg.Done()
  296. }(i)
  297. }
  298. wg.Wait()
  299. for i := 0; i < len(errs); i++ {
  300. if errs[i] != nil {
  301. return nil, errs[i]
  302. }
  303. }
  304. for i := 0; i < len(dbgStatsPerBucket); i++ {
  305. t.params.dbg.add(dbgStatsPerBucket[i])
  306. }
  307. var pairs [][2][]byte
  308. for i := 0; i < len(bucketPairs); i++ {
  309. pairs = append(pairs, bucketPairs[i]...)
  310. }
  311. nodesAtL, err = t.getNodesAtLevel(l)
  312. if err != nil {
  313. return nil, err
  314. }
  315. for i := 0; i < len(nodesAtL); i++ {
  316. nodesAtL = subRoots
  317. }
  318. pairs, err = t.root.computeHashes(0, l, t.params, pairs)
  319. if err != nil {
  320. return nil, err
  321. }
  322. return pairs, nil
  323. }
  324. func newLeafNode(p *params, k, v []byte) *node {
  325. keyPath := make([]byte, p.hashFunction.Len())
  326. copy(keyPath[:], k)
  327. path := getPath(p.maxLevels, keyPath)
  328. n := &node{
  329. k: k,
  330. v: v,
  331. path: path,
  332. }
  333. return n
  334. }
  335. type virtualNodeType int
  336. const (
  337. vtEmpty = 0 // for convenience uses same value that PrefixValueEmpty
  338. vtLeaf = 1 // for convenience uses same value that PrefixValueLeaf
  339. vtMid = 2 // for convenience uses same value that PrefixValueIntermediate
  340. )
  341. func (n *node) typ() virtualNodeType {
  342. if n == nil {
  343. return vtEmpty
  344. }
  345. if n.l == nil && n.r == nil && n.k != nil {
  346. return vtLeaf
  347. }
  348. if n.l != nil || n.r != nil {
  349. return vtMid
  350. }
  351. return vtEmpty
  352. }
  353. func (n *node) add(p *params, currLvl int, leaf *node) error {
  354. if currLvl > p.maxLevels-1 {
  355. return ErrMaxVirtualLevel
  356. }
  357. if n == nil {
  358. // n = leaf // TMP!
  359. return nil
  360. }
  361. t := n.typ()
  362. switch t {
  363. case vtMid:
  364. if leaf.path[currLvl] {
  365. //right
  366. if n.r == nil {
  367. // empty sub-node, add the leaf here
  368. n.r = leaf
  369. return nil
  370. }
  371. if err := n.r.add(p, currLvl+1, leaf); err != nil {
  372. return err
  373. }
  374. } else {
  375. if n.l == nil {
  376. // empty sub-node, add the leaf here
  377. n.l = leaf
  378. return nil
  379. }
  380. if err := n.l.add(p, currLvl+1, leaf); err != nil {
  381. return err
  382. }
  383. }
  384. case vtLeaf:
  385. if bytes.Equal(n.k, leaf.k) {
  386. return fmt.Errorf("%s. Existing node: %s, trying to add node: %s",
  387. ErrKeyAlreadyExists, hex.EncodeToString(n.k),
  388. hex.EncodeToString(leaf.k))
  389. }
  390. oldLeaf := &node{
  391. k: n.k,
  392. v: n.v,
  393. path: n.path,
  394. }
  395. // remove values from current node (converting it to mid node)
  396. n.k = nil
  397. n.v = nil
  398. n.h = nil
  399. n.path = nil
  400. if err := n.downUntilDivergence(p, currLvl, oldLeaf, leaf); err != nil {
  401. return err
  402. }
  403. case vtEmpty:
  404. return fmt.Errorf("virtual tree node.add() with empty node %v", n)
  405. default:
  406. return fmt.Errorf("virtual tree node.add() with unknown node type %v", n)
  407. }
  408. return nil
  409. }
  410. func (n *node) downUntilDivergence(p *params, currLvl int, oldLeaf, newLeaf *node) error {
  411. if currLvl > p.maxLevels-1 {
  412. return ErrMaxVirtualLevel
  413. }
  414. if oldLeaf.path[currLvl] != newLeaf.path[currLvl] {
  415. // reached divergence in next level
  416. if newLeaf.path[currLvl] {
  417. n.l = oldLeaf
  418. n.r = newLeaf
  419. } else {
  420. n.l = newLeaf
  421. n.r = oldLeaf
  422. }
  423. return nil
  424. }
  425. // no divergence yet, continue going down
  426. if newLeaf.path[currLvl] {
  427. // right
  428. n.r = &node{}
  429. if err := n.r.downUntilDivergence(p, currLvl+1, oldLeaf, newLeaf); err != nil {
  430. return err
  431. }
  432. } else {
  433. // left
  434. n.l = &node{}
  435. if err := n.l.downUntilDivergence(p, currLvl+1, oldLeaf, newLeaf); err != nil {
  436. return err
  437. }
  438. }
  439. return nil
  440. }
  441. func splitInBuckets(kvs []kv, nBuckets int) [][]kv {
  442. buckets := make([][]kv, nBuckets)
  443. // 1. classify the keyvalues into buckets
  444. for i := 0; i < len(kvs); i++ {
  445. pair := kvs[i]
  446. // bucketnum := keyToBucket(pair.k, nBuckets)
  447. bucketnum := keyToBucket(pair.keyPath, nBuckets)
  448. buckets[bucketnum] = append(buckets[bucketnum], pair)
  449. }
  450. return buckets
  451. }
  452. // TODO rename in a more 'real' name (calculate bucket from/for key)
  453. func keyToBucket(k []byte, nBuckets int) int {
  454. nLevels := int(math.Log2(float64(nBuckets)))
  455. b := make([]int, nBuckets)
  456. for i := 0; i < nBuckets; i++ {
  457. b[i] = i
  458. }
  459. r := b
  460. mid := len(r) / 2 //nolint:gomnd
  461. for i := 0; i < nLevels; i++ {
  462. if int(k[i/8]&(1<<(i%8))) != 0 {
  463. r = r[mid:]
  464. mid = len(r) / 2 //nolint:gomnd
  465. } else {
  466. r = r[:mid]
  467. mid = len(r) / 2 //nolint:gomnd
  468. }
  469. }
  470. return r[0]
  471. }
  472. // flp2 computes the floor power of 2, the highest power of 2 under the given
  473. // value.
  474. func flp2(n int) int {
  475. res := 0
  476. for i := n; i >= 1; i-- {
  477. if (i & (i - 1)) == 0 {
  478. res = i
  479. break
  480. }
  481. }
  482. return res
  483. }
  484. // computeHashes computes the hashes under the node from which is called the
  485. // method. Returns an array of key-values to store in the db
  486. func (n *node) computeHashes(currLvl, maxLvl int, p *params, pairs [][2][]byte) (
  487. [][2][]byte, error) {
  488. if n == nil || currLvl >= maxLvl {
  489. // no need to compute any hash
  490. return pairs, nil
  491. }
  492. if pairs == nil {
  493. pairs = [][2][]byte{}
  494. }
  495. var err error
  496. t := n.typ()
  497. switch t {
  498. case vtLeaf:
  499. p.dbg.incHash()
  500. leafKey, leafValue, err := newLeafValue(p.hashFunction, n.k, n.v)
  501. if err != nil {
  502. return pairs, err
  503. }
  504. n.h = leafKey
  505. kv := [2][]byte{leafKey, leafValue}
  506. pairs = append(pairs, kv)
  507. case vtMid:
  508. if n.l != nil {
  509. pairs, err = n.l.computeHashes(currLvl+1, maxLvl, p, pairs)
  510. if err != nil {
  511. return pairs, err
  512. }
  513. } else {
  514. n.l = &node{
  515. h: p.emptyHash,
  516. }
  517. }
  518. if n.r != nil {
  519. pairs, err = n.r.computeHashes(currLvl+1, maxLvl, p, pairs)
  520. if err != nil {
  521. return pairs, err
  522. }
  523. } else {
  524. n.r = &node{
  525. h: p.emptyHash,
  526. }
  527. }
  528. // once the sub nodes are computed, can compute the current node
  529. // hash
  530. p.dbg.incHash()
  531. k, v, err := newIntermediate(p.hashFunction, n.l.h, n.r.h)
  532. if err != nil {
  533. return nil, err
  534. }
  535. n.h = k
  536. kv := [2][]byte{k, v}
  537. pairs = append(pairs, kv)
  538. case vtEmpty:
  539. default:
  540. return nil, fmt.Errorf("error: n.computeHashes type (%d) no match", t)
  541. }
  542. return pairs, nil
  543. }
  544. //nolint:unused
  545. func (t *vt) graphviz(w io.Writer) error {
  546. fmt.Fprintf(w, `digraph hierarchy {
  547. node [fontname=Monospace,fontsize=10,shape=box]
  548. `)
  549. if _, err := t.root.graphviz(w, t.params, 0); err != nil {
  550. return err
  551. }
  552. fmt.Fprintf(w, "}\n")
  553. return nil
  554. }
  555. //nolint:unused
  556. func (n *node) graphviz(w io.Writer, p *params, nEmpties int) (int, error) {
  557. if n == nil {
  558. return nEmpties, nil
  559. }
  560. t := n.typ()
  561. switch t {
  562. case vtLeaf:
  563. leafKey, _, err := newLeafValue(p.hashFunction, n.k, n.v)
  564. if err != nil {
  565. return nEmpties, err
  566. }
  567. fmt.Fprintf(w, "\"%p\" [style=filled,label=\"%v\"];\n", n, hex.EncodeToString(leafKey[:nChars]))
  568. k := n.k
  569. v := n.v
  570. if len(n.k) >= nChars {
  571. k = n.k[:nChars]
  572. }
  573. if len(n.v) >= nChars {
  574. v = n.v[:nChars]
  575. }
  576. fmt.Fprintf(w, "\"%p\" -> {\"k:%v\\nv:%v\"}\n", n,
  577. hex.EncodeToString(k),
  578. hex.EncodeToString(v))
  579. fmt.Fprintf(w, "\"k:%v\\nv:%v\" [style=dashed]\n",
  580. hex.EncodeToString(k),
  581. hex.EncodeToString(v))
  582. case vtMid:
  583. fmt.Fprintf(w, "\"%p\" [label=\"\"];\n", n)
  584. lStr := fmt.Sprintf("%p", n.l)
  585. rStr := fmt.Sprintf("%p", n.r)
  586. eStr := ""
  587. if n.l == nil {
  588. lStr = fmt.Sprintf("empty%v", nEmpties)
  589. eStr += fmt.Sprintf("\"%v\" [style=dashed,label=0];\n",
  590. lStr)
  591. nEmpties++
  592. }
  593. if n.r == nil {
  594. rStr = fmt.Sprintf("empty%v", nEmpties)
  595. eStr += fmt.Sprintf("\"%v\" [style=dashed,label=0];\n",
  596. rStr)
  597. nEmpties++
  598. }
  599. fmt.Fprintf(w, "\"%p\" -> {\"%v\" \"%v\"}\n", n, lStr, rStr)
  600. fmt.Fprint(w, eStr)
  601. nEmpties, err := n.l.graphviz(w, p, nEmpties)
  602. if err != nil {
  603. return nEmpties, err
  604. }
  605. nEmpties, err = n.r.graphviz(w, p, nEmpties)
  606. if err != nil {
  607. return nEmpties, err
  608. }
  609. case vtEmpty:
  610. default:
  611. return nEmpties, fmt.Errorf("ERR")
  612. }
  613. return nEmpties, nil
  614. }
  615. //nolint:unused
  616. func (t *vt) printGraphviz() error {
  617. w := bytes.NewBufferString("")
  618. fmt.Fprintf(w,
  619. "--------\nGraphviz:\n")
  620. err := t.graphviz(w)
  621. if err != nil {
  622. fmt.Println(w)
  623. return err
  624. }
  625. fmt.Fprintf(w,
  626. "End of Graphviz --------\n")
  627. fmt.Println(w)
  628. return nil
  629. }