Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bugfix: treeHash for not-locally-available block #489

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -1047,12 +1047,16 @@ module.exports = class Hypercore extends EventEmitter {
return this.core.append(buffers, { keyPair, signature, preappend })
}

async treeHash (length) {
async treeHash (length, opts = {}) {
if (!this.opened) await this.ready()

if (length === undefined) {
await this.ready()
length = this.core.tree.length
}

// Ensure the block corresponding with the length is locally available
if (length > 0) await this.get(length - 1, opts)

const roots = await this.core.tree.getRoots(length)
return this.crypto.tree(roots)
}
Expand Down
28 changes: 28 additions & 0 deletions test/basic.js
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,34 @@ test('treeHash with default length', async function (t) {
t.unlike(await core.treeHash(), await core2.treeHash())
})

test('treeHash of not-locally-available length works', async function (t) {
const core = new Hypercore(RAM)
await core.append('entry')
const remoteCore = new Hypercore(RAM, core.key)

const s1 = core.replicate(true, { keepAlive: false })
const s2 = remoteCore.replicate(false, { keepAlive: false })
s1.pipe(s2).pipe(s1)

await remoteCore.ready()
t.is(remoteCore.length, 0, 'Sanity check: initially unsynced')

const treeHash = await remoteCore.treeHash(1)
t.pass('No error when getting treeHash from unsynced core')
t.alike(treeHash, await core.treeHash(), 'Sanity check: correct treeHash')
})

test('treeHash of not-locally-available length works at length 0', async function (t) {
const core = new Hypercore(RAM)
const remoteCore = new Hypercore(RAM, core.key)

t.alike(
await core.treeHash(0),
await remoteCore.treeHash(0),
'Can get treeHash(0) on remote core (even without replication)'
)
})

test('snapshot locks the state', async function (t) {
const core = new Hypercore(RAM)
await core.ready()
Expand Down
Loading