Overnight build by 17 Claude agents (2026-11-16 22:45 → 01:30 EST), coordinated in [claude/wikideck milestone 63](https://gitea.eom.dev/claude/wikideck/milestone/63). **For Eric's review. Do not merge without it.** The full write-up is in `docs/night/REPORT.md`. **What's in it** (38 reviewed PRs, squash-merged into `night/2026-11-16`): - **Edit War:** - a 3-lane, 6-turn card game built on what WikiDeck cards actually hold - a pure, deterministic, off-chain rules engine (`shared/game/`, with the API in `docs/game/ENGINE_API.md`); rules are data and v1.1 is the default - a mobile-first Play UI with a lobby, deck builder, four loaner starter decks, a match against the AI, results and a tutorial - a landing page (fixes #3) - **Design and balance:** `docs/game/DESIGN.md`, `CARD_DATA.md` (236 sampled articles) and `BALANCE.md` (bot simulations). Starter pairings went from 23–77% on v1 to roughly even on v1.1. - **eom.dev accounts:** Dex OIDC with PKCE, plus off-chain wallet linking, where the client builds the message it signs (`server/account/`, `src/auth/`). - **Peer-hosted game modes:** modes are JSON data, never code. Node API at `/api/game/*`, with host credit and leaderboards. Three example modes (`shared/game/modes.ts`, `server/game/`, `docs/game/HOSTING.md`). - **Mobile:** Capacitor 7 Android app (a debug APK played a full match against the AI in the emulator), and an iOS project waiting on Xcode (`docs/night/ANDROID.md`, `docs/night/IOS.md`). - **Testnet tooling:** `deploy/night/` (LAN-only, 3 nodes) and an optional `WIKIDECK_USER_AGENT` (the default is unchanged). **Not touched:** consensus and protocol (`server/chain.ts`, `shared/protocol.ts`, `server/testnet/{consensus,ledger,…}.ts`, `native/`), the live deployment and mainnet. Matches run off-chain and never move or burn NFTs. **Checks:** the final integration gate passed in `node:24-alpine`: `npm test` 241/242 with 0 fail (1 skipped), and `npm run build` passes. The repo needs Node 24, because Node 20 fails 12 tests falsely. **Decisions for Eric** (see REPORT.md, Known issues and Next steps): 1. whether the live node should set `WIKIDECK_USER_AGENT` 2. the Xcode licence, which you should accept yourself 3. #49 in the fork, a bot change held after the freeze 4. on-chain host rewards (proposal only, in HOSTING.md) 🤖 Generated with [Claude Code](https://claude.com/claude-code)Reviewed-on: #22 Co-authored-by: Claude <claude@eom.dev>
101 lines
6.1 KiB
TypeScript
101 lines
6.1 KiB
TypeScript
// sim-testnet: multi-worker native RandomX miner for the PRIVATE wikideck-night testnet.
|
|
// Runs inside the wikideck:testnet image (which ships the native engine). Testnet only.
|
|
// Usage: node --experimental-strip-types /night/mine.ts <blocks> <workers>
|
|
import { mkdirSync, readFileSync, writeFileSync, existsSync, appendFileSync } from 'node:fs';
|
|
import { randomInt, webcrypto } from 'node:crypto';
|
|
import { RandomX } from '/app/server/testnet/randomx.ts';
|
|
import { CHAIN_ID, sha256, miningBlob, mintId, blockSchema, address } from '/app/server/testnet/consensus.ts';
|
|
import { blockClaimMessage, NETWORK, type MiningTemplate, type TestnetBlock } from '/app/shared/testnet.ts';
|
|
import { encryptWallet } from '/app/shared/wallet-backup.ts';
|
|
|
|
if (!NETWORK.includes('testnet')) throw new Error('testnet only');
|
|
const blocks = Number(process.argv[2] ?? 45), workers = Number(process.argv[3] ?? 4);
|
|
if (!(workers >= 1 && workers <= 8)) throw new Error('1..8 workers');
|
|
const NODES = ['http://node-a:3001', 'http://node-b:3001', 'http://node-c:3001'];
|
|
const WALLET_NAMES = ['alice', 'bob', 'carol', 'dave'];
|
|
// PUBLIC, TESTNET-ONLY password for the disposable wallets' browser backups (posted on #4). Never reuse.
|
|
const PASSWORD = process.env.TESTNET_WALLET_PASSWORD ?? 'wikideck-night-testnet';
|
|
const STATE = process.env.STATE_DIR ?? '/state';
|
|
const dir = `${STATE}/wallets`;
|
|
mkdirSync(dir, { recursive: true });
|
|
const subtle = webcrypto.subtle;
|
|
|
|
type W = { name: string; address: string; publicKey: string; privateKey: CryptoKey };
|
|
async function loadOrCreate(name: string): Promise<W> {
|
|
const keyFile = `${dir}/${name}.jwk.json`;
|
|
let jwk: JsonWebKey;
|
|
if (existsSync(keyFile)) jwk = JSON.parse(readFileSync(keyFile, 'utf8'));
|
|
else {
|
|
const kp = await subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, ['sign', 'verify']) as CryptoKeyPair;
|
|
jwk = await subtle.exportKey('jwk', kp.privateKey);
|
|
writeFileSync(keyFile, JSON.stringify(jwk), { mode: 0o600 });
|
|
}
|
|
const privateKey = await subtle.importKey('jwk', jwk, { name: 'ECDSA', namedCurve: 'P-256' }, true, ['sign']);
|
|
const pubJwk = { kty: jwk.kty, crv: jwk.crv, x: jwk.x, y: jwk.y };
|
|
const pub = await subtle.importKey('jwk', pubJwk, { name: 'ECDSA', namedCurve: 'P-256' }, true, ['verify']);
|
|
const publicKey = Buffer.from(await subtle.exportKey('spki', pub)).toString('base64');
|
|
const w = { name, address: address(publicKey), publicKey, privateKey };
|
|
const backupFile = `${dir}/${name}.backup.json`;
|
|
if (!existsSync(backupFile)) writeFileSync(backupFile, JSON.stringify(await encryptWallet(privateKey, publicKey, PASSWORD), null, 2));
|
|
return w;
|
|
}
|
|
const wallets = await Promise.all(WALLET_NAMES.map(loadOrCreate));
|
|
writeFileSync(`${dir}/addresses.json`, JSON.stringify(Object.fromEntries(wallets.map(w => [w.name, w.address])), null, 2));
|
|
console.log(`chain ${CHAIN_ID}; wallets: ${wallets.map(w => `${w.name}=${w.address.slice(0, 12)}`).join(' ')}`);
|
|
|
|
async function api(node: string, path: string, body?: unknown) {
|
|
const r = await fetch(node + path, { method: body ? 'POST' : 'GET', redirect: 'error', signal: AbortSignal.timeout(60000),
|
|
headers: body ? { 'Content-Type': 'application/json' } : {}, body: body ? JSON.stringify(body) : undefined });
|
|
const data = await r.json();
|
|
if (!r.ok) throw new Error(data.error ?? `HTTP ${r.status}`);
|
|
return data;
|
|
}
|
|
const engines = Array.from({ length: workers }, () => new RandomX());
|
|
const close = () => { for (const e of engines) e.close(); };
|
|
process.once('SIGTERM', () => { close(); process.exit(0); });
|
|
|
|
let accepted = 0, round = 0, fails = 0;
|
|
// Each template costs several Wikipedia API calls, and Wikipedia rate-limits this egress IP:
|
|
// pace templates (>= MIN_GAP s apart) and back off exponentially on failure.
|
|
const MIN_GAP = Number(process.env.MIN_GAP ?? 45), sleep = (s: number) => new Promise(r => setTimeout(r, s * 1000));
|
|
let lastTemplate = 0;
|
|
try {
|
|
while (accepted < blocks) {
|
|
const wait = lastTemplate + MIN_GAP * 1000 - Date.now(); if (wait > 0) await sleep(wait / 1000);
|
|
lastTemplate = Date.now();
|
|
const node = NODES[round % NODES.length], w = wallets[accepted % wallets.length]; round++;
|
|
let template: MiningTemplate;
|
|
try { template = await api(node, '/api/mining/template', { owner: w.address, publicKey: w.publicKey }); fails = 0; }
|
|
catch (e) { fails++; const b = Math.min(60 * 2 ** (fails - 1), 600); console.error(`template ${node}: ${(e as Error).message} (fail ${fails}, backoff ${b}s)`); await sleep(b); continue; }
|
|
const h = template.header; if (h.chainId !== CHAIN_ID) throw new Error('wrong chain');
|
|
const started = Date.now(); let attempts = 0; let found: { hash: string; nonce: number } | null = null;
|
|
let base = randomInt(0, 2 ** 40); const BATCH = 64;
|
|
while (!found) {
|
|
const results = await Promise.all(engines.map((e, i) => {
|
|
const hdr = { ...h, nonce: base + i * BATCH };
|
|
return e.mine(h.key, miningBlob(hdr), h.target, 32, BATCH);
|
|
}));
|
|
attempts += BATCH * workers; base += BATCH * workers;
|
|
found = results.find(Boolean) ?? null;
|
|
if (!found && Date.now() / 1000 - h.createdAt > 600) break; // stale template
|
|
}
|
|
if (!found) continue;
|
|
h.nonce = found.nonce;
|
|
const hash = sha256(miningBlob(h));
|
|
const signature = Buffer.from(await subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, w.privateKey,
|
|
new TextEncoder().encode(blockClaimMessage(hash)))).toString('base64');
|
|
const block: TestnetBlock = { ...h, hash, tokenId: mintId(h), powHash: found.hash, signature, transactions: template.transactions };
|
|
blockSchema.parse(block);
|
|
try {
|
|
const res = await api(node, '/api/blocks', block);
|
|
if (!res.accepted) { console.error(`not accepted: ${JSON.stringify(res).slice(0, 200)}`); continue; }
|
|
accepted++;
|
|
const secs = (Date.now() - started) / 1000;
|
|
const line = `#${h.height} ${w.name} "${h.article.title}" token=${block.tokenId} via=${node} ${attempts}H ${(attempts / secs).toFixed(0)}H/s`;
|
|
console.log(`[${accepted}/${blocks}] ${line}`);
|
|
appendFileSync(`${STATE}/mined.log`, `${new Date().toISOString()} ${line}\n`);
|
|
} catch (e) { console.error(`submit: ${(e as Error).message}`); }
|
|
}
|
|
} finally { close(); }
|
|
console.log('done');
|