Skip to content

Commit de55e09

Browse files
copyFrom sets fork before creating batch (#485)
* copyFrom sets fork before creating batch * add test for cloning with explicit fork
1 parent 3081b42 commit de55e09

File tree

2 files changed

+51
-2
lines changed

2 files changed

+51
-2
lines changed

lib/core.js

+3-2
Original file line numberDiff line numberDiff line change
@@ -279,6 +279,8 @@ module.exports = class Core {
279279

280280
await this.tree.flush()
281281

282+
this.tree.fork = fork
283+
282284
let batch = this.tree.batch()
283285

284286
// add additional blocks
@@ -334,9 +336,8 @@ module.exports = class Core {
334336

335337
await batch.commit()
336338

337-
this.tree.fork = fork
338-
339339
this.header.tree.length = this.tree.length
340+
this.header.tree.fork = this.tree.fork
340341
this.header.tree.rootHash = this.tree.hash()
341342
this.header.tree.signature = this.tree.signature
342343

test/core.js

+48
Original file line numberDiff line numberDiff line change
@@ -560,6 +560,54 @@ test('core - clone fills in with additional', async function (t) {
560560
t.alike(await clone.blocks.get(1), b4a.from('b'))
561561
})
562562

563+
test('core - clone with different fork', async function (t) {
564+
const { core } = await create()
565+
const { core: clone } = await create({ keyPair: { publicKey: core.header.keyPair.publicKey } })
566+
const { core: clone2 } = await create({ compat: false })
567+
const { core: fail } = await create({ manifest: clone2.header.manifest })
568+
569+
t.alike(clone.header.keyPair.publicKey, core.header.keyPair.publicKey)
570+
t.unlike(clone2.header.keyPair.publicKey, core.header.keyPair.publicKey)
571+
572+
await core.truncate(0, 1)
573+
574+
t.is(core.tree.fork, 1)
575+
t.is(core.header.tree.fork, 1)
576+
577+
await core.append([b4a.from('a')])
578+
579+
await clone.copyFrom(core, core.tree.signature)
580+
581+
t.is(clone.tree.fork, 1)
582+
t.is(clone.header.tree.fork, 1)
583+
584+
await core.append([b4a.from('b')])
585+
586+
const batch = core.tree.batch()
587+
batch.fork = 0
588+
589+
const signature = clone2.verifier.sign(batch, clone2.header.keyPair)
590+
591+
// fail with same fork
592+
await t.exception(fail.copyFrom(core, signature), /INVALID_SIGNATURE/)
593+
594+
await clone2.copyFrom(core, signature, { fork: 0 })
595+
596+
t.is(clone2.tree.fork, 0)
597+
t.is(clone2.header.tree.fork, 0)
598+
599+
await clone2.append([b4a.from('c')])
600+
601+
// verify state
602+
t.is(clone.tree.length, 1)
603+
t.is(core.tree.length, 2)
604+
t.is(clone2.tree.length, 3)
605+
606+
t.alike(await clone.blocks.get(0), b4a.from('a'))
607+
t.alike(await core.blocks.get(1), b4a.from('b'))
608+
t.alike(await clone2.blocks.get(2), b4a.from('c'))
609+
})
610+
563611
async function create (opts) {
564612
const storage = new Map()
565613

0 commit comments

Comments
 (0)