Skip to content

Commit

Permalink
Unslab roots
Browse files Browse the repository at this point in the history
  • Loading branch information
HDegroote committed Jul 26, 2024
1 parent c311102 commit efa3736
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
16 changes: 16 additions & 0 deletions lib/merkle-tree.js
Original file line number Diff line number Diff line change
Expand Up @@ -440,6 +440,22 @@ module.exports = class MerkleTree {
this.truncateTo = 0
}

get roots () {
return this._roots
}

set roots (roots) {
if (roots) { // 1 slab for all roots
const hashes = roots.map(r => r.hash)
const unslabbed = unslab.all(hashes)
for (let i = 0; i < roots.length; i++) {
roots[i].hash = unslabbed[i]
}
}

this._roots = roots
}

addNode (node) {
if (node.size === 0 && b4a.equals(node.hash, BLANK_HASH)) node = blankNode(node.index)
this.unflushed.set(node.index, node)
Expand Down
31 changes: 31 additions & 0 deletions test/merkle-tree.js
Original file line number Diff line number Diff line change
Expand Up @@ -602,6 +602,37 @@ test('checkout nodes in a batch', async t => {
t.alike(nodes, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 24, 25, 26, 28])
})

test('roots get unslabbed in one slab', async function (t) {
const tree = await create()

const b = tree.batch()

for (let i = 0; i < 100; i++) {
b.append(b4a.from([i]))
}

b.commit()

t.is(tree.roots.length > 1, true, 'sanity check')

const rootByteLength = 32
const nrRoots = 3
const buffer = tree.roots[0].hash.buffer

t.is(
buffer.byteLength,
nrRoots * rootByteLength,
'unslabbed the roots, and put them all in the same slab'
)

// Sanity check
for (const root of tree.roots) {
if (root.hash.buffer !== buffer) {
t.fail('a root lives on a different slab')
}
}
})

test('buffer of cached nodes is copied to small slab', async function (t) {
// RAM does not use slab-allocated memory,
// so we need to us random-access-file to reproduce this issue
Expand Down

0 comments on commit efa3736

Please sign in to comment.