Skip to content

Commit 54fea3c

Browse files
Add getRaw method to Batch API (#488)
* add batch.getRaw method for raw block data * return block if no encryption is present * unsolo test * add raw flag to batch and hypercore get * break up if statements
1 parent cea0c56 commit 54fea3c

File tree

3 files changed

+51
-2
lines changed

3 files changed

+51
-2
lines changed

index.js

+2
Original file line numberDiff line numberDiff line change
@@ -875,6 +875,8 @@ module.exports = class Hypercore extends EventEmitter {
875875
let block = await req
876876
if (!block) return null
877877

878+
if (opts && opts.raw) return block
879+
878880
if (this.encryption && (!opts || opts.decrypt !== false)) {
879881
// Copy the block as it might be shared with other sessions.
880882
block = b4a.from(block)

lib/batch.js

+9-2
Original file line numberDiff line numberDiff line change
@@ -170,12 +170,19 @@ module.exports = class HypercoreBatch extends EventEmitter {
170170
throw BLOCK_NOT_AVAILABLE()
171171
}
172172

173-
async get (index, opts) {
173+
async get (index, opts = {}) {
174174
if (this.opened === false) await this.opening
175175
if (this.closing) throw SESSION_CLOSED()
176176

177177
const length = this._sessionLength
178-
if (index < length) return this.session.get(index, { ...opts, tree: this._sessionBatch })
178+
179+
if (index < length) {
180+
return this.session.get(index, { ...opts, tree: this._sessionBatch })
181+
}
182+
183+
if (opts && opts.raw) {
184+
return this._appendsActual[index - length] || null
185+
}
179186

180187
const buffer = this._appends[index - length] || null
181188
if (!buffer) throw BLOCK_NOT_AVAILABLE()

test/batch.js

+40
Original file line numberDiff line numberDiff line change
@@ -643,3 +643,43 @@ test('clear', async function (t) {
643643

644644
t.is(b2.length, 1, 'reset the batch')
645645
})
646+
647+
test('copy from with encrypted batch', async function (t) {
648+
const encryptionKey = b4a.alloc(32, 2)
649+
650+
const core = await create({ encryptionKey })
651+
652+
const blocks = 290
653+
654+
const b = core.batch({ autoClose: false })
655+
656+
for (let i = 0; i < blocks; i++) {
657+
await b.append('block' + i)
658+
}
659+
660+
await b.flush({ keyPair: null })
661+
662+
t.is(core.length, 0)
663+
t.is(b._sessionLength, blocks)
664+
665+
const manifest = {
666+
prologue: {
667+
length: b._sessionLength,
668+
hash: b.createTreeBatch().hash()
669+
},
670+
encryptionKey
671+
}
672+
673+
const clone = await create({
674+
manifest,
675+
encryptionKey
676+
})
677+
678+
const tree = clone.core.tree.batch()
679+
680+
for (let i = 0; i < blocks; i++) {
681+
await tree.append(await b.get(i, { raw: true }))
682+
}
683+
684+
t.alike(tree.hash(), manifest.prologue.hash)
685+
})

0 commit comments

Comments
 (0)