Skip to content
This repository has been archived by the owner on Dec 28, 2022. It is now read-only.

Commit

Permalink
fix(open from existing): create encrypted core from unencrypted core
Browse files Browse the repository at this point in the history
same logic in core.session() added to core._openFromExisting with one
difference; new core will override existing.encryption

Closes hypercore-protocol/corestore-next#17
  • Loading branch information
Nuhvi committed May 23, 2022
1 parent 26049ef commit 165fdc8
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 10 deletions.
22 changes: 12 additions & 10 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -191,16 +191,7 @@ module.exports = class Hypercore extends EventEmitter {

s._passCapabilities(this)

if (opts.encryptionKey) {
// Only override the block encryption if its either not already set or if
// the caller provided a different key.
if (
!s.encryption ||
!b4a.equals(s.encryption.key, opts.encryptionKey)
) {
s.encryption = new BlockEncryption(opts.encryptionKey, s.key)
}
}
ensureEncryption(s, opts)

this.sessions.push(s)

Expand Down Expand Up @@ -229,6 +220,8 @@ module.exports = class Hypercore extends EventEmitter {
this.storage = from.storage
this.replicator.findingPeers += this._findingPeers

ensureEncryption(this, opts)

this.sessions.push(this)
}

Expand Down Expand Up @@ -797,3 +790,12 @@ function preappend (blocks) {
this.encryption.encrypt(offset + i, blocks[i], fork)
}
}

function ensureEncryption (core, opts) {
if (!opts.encryptionKey) return
// Only override the block encryption if its either not already set or if
// the caller provided a different key.
if (!core.encryption || !b4a.equals(core.encryption.key, opts.encryptionKey)) {
core.encryption = new BlockEncryption(opts.encryptionKey, core.key)
}
}
13 changes: 13 additions & 0 deletions test/encryption.js
Original file line number Diff line number Diff line change
Expand Up @@ -165,3 +165,16 @@ test('encrypted session on encrypted core, different keys', async function (t) {
const encrypted = await a.get(0)
t.absent(encrypted.includes('hello'))
})

test('encrypted core from existing unencrypted core', async function (t) {
const a = await create({ encryptionKey: Buffer.alloc(32, 'a') })
const b = await create({ from: a, encryptionKey })

t.alike(b.key, a.key)
t.alike(b.encryptionKey, encryptionKey)

await b.append(['hello'])

const unencrypted = await b.get(0)
t.alike(unencrypted, Buffer.from('hello'))
})

0 comments on commit 165fdc8

Please sign in to comment.