Skip to content

Commit e12699b

Browse files
committed
Bugfix: treeHash for not-locally-available block
1 parent 64116ee commit e12699b

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

index.js

+6-2
Original file line numberDiff line numberDiff line change
@@ -1047,12 +1047,16 @@ module.exports = class Hypercore extends EventEmitter {
10471047
return this.core.append(buffers, { keyPair, signature, preappend })
10481048
}
10491049

1050-
async treeHash (length) {
1050+
async treeHash (length, opts = {}) {
1051+
if (!this.opened) await this.ready()
1052+
10511053
if (length === undefined) {
1052-
await this.ready()
10531054
length = this.core.tree.length
10541055
}
10551056

1057+
// Ensure the block corresponding with the length is locally available
1058+
if (length > 0) await this.get(length - 1, opts)
1059+
10561060
const roots = await this.core.tree.getRoots(length)
10571061
return this.crypto.tree(roots)
10581062
}

test/basic.js

+28
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,34 @@ test('treeHash with default length', async function (t) {
183183
t.unlike(await core.treeHash(), await core2.treeHash())
184184
})
185185

186+
test('treeHash of not-locally-available length works', async function (t) {
187+
const core = new Hypercore(RAM)
188+
await core.append('entry')
189+
const remoteCore = new Hypercore(RAM, core.key)
190+
191+
const s1 = core.replicate(true, { keepAlive: false })
192+
const s2 = remoteCore.replicate(false, { keepAlive: false })
193+
s1.pipe(s2).pipe(s1)
194+
195+
await remoteCore.ready()
196+
t.is(remoteCore.length, 0, 'Sanity check: initially unsynced')
197+
198+
const treeHash = await remoteCore.treeHash(1)
199+
t.pass('No error when getting treeHash from unsynced core')
200+
t.alike(treeHash, await core.treeHash(), 'Sanity check: correct treeHash')
201+
})
202+
203+
test('treeHash of not-locally-available length works at length 0', async function (t) {
204+
const core = new Hypercore(RAM)
205+
const remoteCore = new Hypercore(RAM, core.key)
206+
207+
t.alike(
208+
await core.treeHash(0),
209+
await remoteCore.treeHash(0),
210+
'Can get treeHash(0) on remote core (even without replication)'
211+
)
212+
})
213+
186214
test('snapshot locks the state', async function (t) {
187215
const core = new Hypercore(RAM)
188216
await core.ready()

0 commit comments

Comments
 (0)