OverviewFilesCommitsIssuesDocsReleasesPeers

keet-daemon / test / probe-isolate-rotate.mjs

108 lines · javascript ref:
// ISOLATION: phantom-check (3/3 PASS) vs rotmethod (3/3 FAIL) use the SAME fresh-writer
// promotion but disagree. This probe is EXACTLY the phantom-check harness with ONE toggle at
// the rotation step: ROTATE_MODE=inline (phantom's fresh keypair + setLocal + start-indexing)
// vs ROTATE_MODE=method (C.rotateAndPromote()). Everything else identical.
//   inline PASS + method PASS → the method is fine; rotmethod's HARNESS (weaker convergence
//                                wait / settle) was the culprit. Also proves leave/rejoin works.
//   inline PASS + method FAIL → rotateAndPromote() itself is the culprit → narrow inside it.
import { StateBaseV3 } from '../lib/state-base-v3.js'
import createTestnet from 'hyperdht/testnet'
import crypto from 'hypercore-crypto'
import b4a from 'b4a'
import fs from 'bare-fs'
import path from 'bare-path'
import os from 'bare-os'
import process from 'bare-process'

const MODE = (process.env.ROTATE_MODE || 'inline').toLowerCase()
const ROOT = path.join(os.tmpdir(), 'sbv3-isolate-' + Bare.pid)
try { fs.rmSync(ROOT, { recursive: true, force: true }) } catch {}
const hex = (b) => b4a.toString(b, 'hex')

let kpA = crypto.keyPair(); let kpB = crypto.keyPair()
if (hex(kpB.publicKey) < hex(kpA.publicKey)) { const t = kpA; kpA = kpB; kpB = t }
const kpC = crypto.keyPair()
const members = [
  { key: hex(kpA.publicKey), role: 1 },
  { key: hex(kpB.publicKey), role: 1 },
  { key: hex(kpC.publicKey), role: 3 }
]
let pass = 0; let fail = 0
const ok = (c, m) => { if (c) { pass++; console.log('  ok  ' + m) } else { fail++; console.log('  FAIL ' + m) } }
const sleep = (ms) => new Promise(r => setTimeout(r, ms))
const idx = (sb) => { try { return sb.base.linearizer.indexers.length } catch { return '?' } }
const slen = (sb) => { try { return sb.base.signedLength } catch { return -1 } }

let A, B, C
const live = () => [A, B, C].filter(x => x && x.base && !x._closing)
let hb = 0
const churn = async (predicate, maxMs, writeC = true) => {
  const deadline = Date.now() + maxMs
  while (Date.now() < deadline) {
    for (const x of live()) { if (x.base.writable && (x !== C || writeC)) { try { await x.set('__hb__:' + hex(x._selfKey).slice(0, 6), hb++) } catch {} } }
    for (const x of live()) await x.base.update().catch(() => {})
    await sleep(150)
    if (predicate && await predicate()) return true
  }
  return predicate ? await predicate() : true
}
const measure = async (label, ms) => {
  const before = slen(B)
  await churn(null, ms)
  const after = slen(B)
  console.log('  [measure] %s: B.signedLength %d → %d (Δ%d) | idx A=%s B=%s C=%s', label, before, after, after - before, idx(A), idx(B), idx(C))
  return after - before
}

let stage = 'init'
const watchdog = setTimeout(() => { console.log('  [WATCHDOG] stuck at stage=' + stage + ' — exiting'); Bare.exit(3) }, 260000)

async function main () {
  console.log('  ROTATE_MODE: ' + MODE)
  stage = 'testnet'
  const testnet = await createTestnet(3)
  const bootstrap = testnet.bootstrap
  const roomSeed = crypto.randomBytes(32)
  const opt = (kp) => ({ roomSeed, encryptionKey: roomSeed, network: true, swarmOpts: { bootstrap }, selfKeyPair: kp, selfKey: kp.publicKey, getMembers: async () => members, promoteRetryMs: 9999999 })

  stage = 'A'; A = new StateBaseV3(path.join(ROOT, 'A'), crypto.randomBytes(32), opt(kpA)); await A.ready(); await A.projectMembers(members)
  stage = 'B'; B = new StateBaseV3(path.join(ROOT, 'B'), A._roomKey, opt(kpB)); await B.ready()
  stage = 'C'; C = new StateBaseV3(path.join(ROOT, 'C'), A._roomKey, opt(kpC)); await C.ready()
  await churn(async () => (B.base.length || 0) > 0 && (C.base.length || 0) > 0, 45000)

  stage = 'growB'; await B.requestWriter({ timeoutMs: 60000, startIndexing: true })
  ok(await churn(async () => idx(A) === 2 && idx(B) === 2, 90000), '1. {A,B}=2 indexers')

  stage = 'measA'; const dA = await measure('STAGE-A pre-rotation {A,B} online', 12000)
  ok(dA > 0, '2. CONTROL: signedLength advances pre-rotation')

  stage = 'play'; await C.set('c:score', { pts: 100 }); await churn(async () => (await C.effectiveWritable()) === true, 40000)
  members[2].role = 1; await A.projectMembers(members); await churn(async () => (await C.getProjectedRole(hex(kpC.publicKey))) === 1, 30000)
  await churn(null, 4000, false)

  stage = 'rotate'
  if (MODE === 'method') {
    const rr = await C.rotateAndPromote({ timeoutMs: 60000 })
    console.log('  [diag] rotateAndPromote →', JSON.stringify(rr))
  } else {
    const freshKp = crypto.keyPair(); const freshCore = C.store.get({ keyPair: freshKp }); await freshCore.ready()
    await C.base.setLocal(freshCore.key); await C.base.update()
    await C.requestWriter({ timeoutMs: 60000, startIndexing: true })
  }
  ok(await churn(async () => C._isLocalIndexer() === true && idx(A) === 3 && idx(B) === 3 && idx(C) === 3, 60000), '3. C is indexer; set=3 on all')

  stage = 'measB'; const dB = await measure('STAGE-B post-rotation, ALL online', 15000)
  ok(dB > 0, '4. post-rotation signedLength advances (all online)')

  stage = 'closeA'; try { A._closing = true; await A.close() } catch {}
  const dC = await measure('STAGE-C genesis OFFLINE (needs B+C)', 20000)
  console.log('\n  VERDICT (' + MODE + '): rotated C is %s', dC > 0 ? 'a REAL signer' : 'a PHANTOM')
  ok(dC > 0, '5. genesis OFFLINE: rotated C co-signs (durable)')

  clearTimeout(watchdog)
  console.log('\n  RESULT (' + MODE + '): ' + pass + ' passed, ' + fail + ' failed (deltas A=' + dA + ' B=' + dB + ' C=' + dC + ')')
  Bare.exit(fail === 0 ? 0 : 1)
}

main().catch((e) => { console.log('  FATAL ' + (e && e.stack || e)); Bare.exit(2) })