OverviewFilesCommitsIssuesDocsReleasesPeers

hyper-note / test / unit / shared-registry-keypair.test.js

62 lines · javascript ref:
import test from 'brittle'
import fs from 'bare-fs'
import path from 'bare-path'
import os from 'bare-os'
import b4a from 'b4a'
import Corestore from 'corestore'
import crypto from 'hypercore-crypto'
import { SharedRegistry } from '../../lib/multiwriter/shared-registry.js'

function tmpStore () {
  const dir = path.join(os.tmpdir(), 'hn-srkp-' + Date.now() + '-' + Math.random().toString(36).slice(2))
  fs.mkdirSync(dir, { recursive: true })
  return { store: new Corestore(dir), dir }
}

function rmrf (dir) {
  try {
    for (const f of fs.readdirSync(dir)) {
      const fp = path.join(dir, f)
      if (fs.statSync(fp).isDirectory()) rmrf(fp)
      else fs.unlinkSync(fp)
    }
    fs.rmdirSync(dir)
  } catch {}
}

test('SharedRegistry - stable keyPair makes localWriterKey deterministic + bootstrap-independent', async (t) => {
  const keyPair = crypto.keyPair()

  // Same keyPair, DIFFERENT store, DIFFERENT bootstrap → SAME writer key.
  const a = tmpStore()
  const reg1 = new SharedRegistry(a.store, { keyPair })
  await reg1.ready()
  const k1 = reg1.localWriterKey

  const b = tmpStore()
  const reg2 = new SharedRegistry(b.store, { keyPair, bootstrapKey: crypto.keyPair().publicKey })
  await reg2.ready()
  const k2 = reg2.localWriterKey

  t.ok(b4a.equals(k1, k2), 'writer key is identical across store + bootstrap — knowable before pairing')

  await reg1.close(); await reg2.close()
  rmrf(a.dir); rmrf(b.dir)
})

test('SharedRegistry - no keyPair preserves the old random-per-namespace behaviour', async (t) => {
  const keyPair = crypto.keyPair()
  const c = tmpStore()
  const stable = new SharedRegistry(c.store, { keyPair })
  await stable.ready()

  const d = tmpStore()
  const random = new SharedRegistry(d.store, {})
  await random.ready()

  t.absent(b4a.equals(stable.localWriterKey, random.localWriterKey), 'unkeyed registry keeps a distinct (default) writer key')

  await stable.close(); await random.close()
  rmrf(c.dir); rmrf(d.dir)
})