Files
wikideck/tests/ownership-deck.test.ts
claudeanderic dbb89ce9c5 Night 2: 40-card Magic-style duel, PvP with owned decks, polite Wikimedia client, Android mining (#23)
Night 2 (2026-11-17), from the `claude/wikideck` fork's `night/2026-11-17` branch. It follows Night 1 (#22).

## What's in it
- **Duel engine** (fork #72, #80): 40-card decks of cards you own, Notability/Citations, keywords, effects T1–T12, Connected, a hidden-information-safe `viewFor`/`logFor`, and replay. Balance v1 tuning (#84) gives the first player about 51%.
- **Card profiles** (#70, #82): Figure, Location, Event, Institution or Doctrine, plus stats, keywords and rules text, all derived from real article data. Templates only.
- **Design and story** (#66, #69, #83): DUEL_DESIGN.md, plus the match log and the encyclopedic "Battle of X (2026)" recap.
- **PvP** (#74, #77, #81, #76, #85):
  - The server checks ownership, and 40-card eligibility is enforced.
  - Modes: Classic (ranked), Draft and Trending.
  - Invites, quick match, Elo, a ladder and recap pages. Online matches render on the duel board.
- **Duel board UI** (#79): MTG-style card faces and combat declaration, built for 360 px first.
- **Polite Wikimedia client** (#73, #75): throttled, cached and identified requests, the mint-path fix, and a prefetch pool.
- **Android mining** (#78): native RandomX, as a sideload build. The emulator mined a testnet block.
- **Testnet ops** (#67, #68).

PR numbers refer to `claude/wikideck`.

## Status
- **Tests:** 423, of which 422 pass, 0 fail and 1 is skipped. The build is OK (`node:24-alpine`, `--network none`).
- **Testnet:** running this commit (036489c) on r350.
- **Untouched:** no changes to `server/testnet/consensus.ts`, `randomx.ts`, `native/` or the mainnet compose.
- **Review:** night-review reviewed fork #66–#79. #80–#85 came from the agents' unfinished branches and were not reviewed.
- **Known gaps:**
  - The PvP end-to-end test hasn't been run (it needs two eom.dev accounts).
  - Bot matches aren't reachable from Play.
  - Card identity pre-bake hasn't been done.
  - The RandomX verifier latch (`server/testnet/randomx.ts:140`) is still open.

This PR is for Eric to merge.

🤖 Generated with [Claude Code](https://claude.com/claude-code)Reviewed-on: WikiDeck/wikideck#23

Co-authored-by: Claude <claude@eom.dev>
2026-11-18 18:12:24 +00:00

292 lines
15 KiB
TypeScript

import test from 'node:test';
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import express from 'express';
import type { AddressInfo } from 'node:net';
import { resolveDeck, collection, verifyAccount, playableCount, ownershipRules, DEFAULT_OWNERSHIP_RULES,
DeckError, OwnershipUnavailable, type OwnershipDeps, type OwnershipLedger } from '../server/game/ownership.ts';
import { collectionRouter, collectionResponse } from '../server/game/collection.ts';
import type { Account } from '../server/account/store.ts';
import type { TestnetBlock } from '../shared/testnet.ts';
// In-memory fixture: the same shape as Ledger.nft/deck/summary and AccountStore.wallets. No network.
const hex = (s: string) => createHash('sha256').update(s).digest('hex');
const ALICE = hex('alice'), ALICE2 = hex('alice-2'), BOB = hex('bob');
function block(n: number, pageId: number, miner: string): TestnetBlock {
return {
version: 6, network: 'testnet', chainId: 'test', height: n, previousHash: hex(`b${n - 1}`), createdAt: 1_800_000_000 + n,
article: { pageId, title: `Article ${pageId}`, extract: `Extract ${pageId}.`, url: `https://en.wikipedia.org/?curid=${pageId}`,
revisionId: 1000 + pageId, source: 'live', category: 'History' },
statsSnapshot: { capturedAt: '2026-11-17T00:00:00Z', revisionId: 1000 + pageId, pageBytes: 5000 + pageId, languageCount: 3,
languagesTruncated: false, pageviews: null } as unknown as TestnetBlock['statsSnapshot'],
owner: miner, publicKey: 'pk', nonce: 0, target: 'f'.repeat(64), key: '0'.repeat(64), transactionsRoot: '0'.repeat(64),
stateRoot: '0'.repeat(64), hash: hex(`b${n}`), tokenId: hex(`t${n}`), powHash: hex(`p${n}`), signature: 'sig', transactions: [],
} as unknown as TestnetBlock;
}
class FakeLedger implements OwnershipLedger {
tip = 'tip-0';
height = 0;
cards: { block: TestnetBlock; owner: string }[] = [];
deckCalls = 0;
onDeck?: () => void;
mint(owner: string, pageId: number): string {
const b = block(++this.height, pageId, owner);
this.cards.push({ block: b, owner });
this.tip = `tip-${this.height}`;
return b.tokenId;
}
mineEmpty(n = 1) { this.height += n; this.tip = `tip-${this.height}`; }
transfer(token: string, to: string) { this.cards.find(c => c.block.tokenId === token)!.owner = to; }
private conf(b: TestnetBlock) { return this.height - b.height + 1; }
nft(token: string) {
const c = this.cards.find(x => x.block.tokenId === token);
return c ? { block: structuredClone(c.block), owner: c.owner, sequence: 0, confirmations: this.conf(c.block) } : undefined;
}
deck(address: string, offset: number, limit: number) {
this.deckCalls++;
assert.ok(limit <= 24, 'ledger pages are at most 24');
const mine = this.cards.filter(c => c.owner === address);
const nfts = mine.slice(offset, offset + limit).map(c => ({ block: structuredClone(c.block), sequence: 0, confirmations: this.conf(c.block) }));
const result = { tip: this.tip, total: mine.length, next: offset + nfts.length < mine.length ? offset + nfts.length : null, nfts };
this.onDeck?.();
return result;
}
summary() { return { tip: this.tip, height: this.height, network: 'testnet', chainId: 'test' }; }
}
function fixture(wallets: Record<string, string[]> = { alice: [ALICE, ALICE2], bob: [BOB] }) {
const ledger = new FakeLedger();
const deps: OwnershipDeps = { ledger, accounts: { wallets: sub => (wallets[sub] ?? []).map(address => ({ address })) },
verifyIdToken: async (t: string): Promise<Account> => {
const m = /^good\.token\.(\w+)$/.exec(t);
if (m) return { sub: m[1], issuer: 'https://dex.example/', name: m[1], username: m[1] };
if (t === 'dex.is.down') throw new Error('fetch failed');
throw Object.assign(new Error('Token expired'), { status: 401 });
} };
return { ledger, deps };
}
/** n cards for `owner`, distinct pageIds starting at `firstPage`. */
const mintMany = (l: FakeLedger, owner: string, n: number, firstPage = 1) => Array.from({ length: n }, (_, i) => l.mint(owner, firstPage + i));
const ALICE_ACCT = { sub: 'alice' }, BOB_ACCT = { sub: 'bob' };
async function rejects(p: Promise<unknown>, code: string, tokenIds?: string[]) {
await assert.rejects(p, (e: unknown) => {
assert.ok(e instanceof DeckError, String(e));
assert.equal(e.code, code);
if (tokenIds) assert.deepEqual(e.tokenIds, tokenIds);
return true;
});
}
test('defaults are a 40-card deck, 4 copies per article, 1 confirmation', () => {
assert.deepEqual({ ...DEFAULT_OWNERSHIP_RULES }, { deckSize: 40, maxCopiesPerPage: 4, minConfirmations: 1 });
assert.equal(ownershipRules({ deckSize: 10, minConfirmations: undefined }).minConfirmations, 1);
assert.throws(() => ownershipRules({ deckSize: 0 }), RangeError);
assert.throws(() => ownershipRules({ maxCopiesPerPage: 1.5 }), RangeError);
assert.throws(() => ownershipRules({ minConfirmations: 0 }), RangeError);
});
test('verifyAccount maps token failures to DeckError(auth) and Dex outages to OwnershipUnavailable', async () => {
const { deps } = fixture();
assert.equal((await verifyAccount(deps, 'good.token.alice')).sub, 'alice');
for (const t of [undefined, '', 42, 'x'.repeat(9000)]) await rejects(verifyAccount(deps, t), 'auth');
await assert.rejects(verifyAccount(deps, 'bad'), (e: unknown) => e instanceof DeckError && e.code === 'auth' && e.status === 401 && e.message === 'Token expired');
await assert.rejects(verifyAccount(deps, 'dex.is.down'), (e: unknown) => e instanceof OwnershipUnavailable && e.status === 503);
});
test('resolveDeck accepts 40 owned cards across linked wallets and builds them from the chain, in order', async () => {
const { ledger, deps } = fixture();
const ids = [...mintMany(ledger, ALICE, 25, 1), ...mintMany(ledger, ALICE2, 15, 100)].reverse();
const cards = await resolveDeck(deps, ALICE_ACCT, ids);
assert.equal(cards.length, 40);
assert.deepEqual(cards.map(c => c.tokenId), ids);
const c = cards.find(x => x.pageId === 100)!;
const chain = ledger.nft(c.tokenId)!.block;
assert.equal(c.owner, ALICE2);
assert.equal(c.title, 'Article 100');
assert.equal(c.revisionId, 1100);
assert.equal(c.article.title, 'Article 100');
assert.equal(c.statsSnapshot.pageBytes, 5100);
assert.equal(c.blockHash, chain.hash);
assert.equal(c.powHash, chain.powHash);
assert.equal(c.height, chain.height);
});
test('resolveDeck takes token ids only: card data is never taken from the client', async () => {
const { ledger, deps } = fixture();
const ids = mintMany(ledger, ALICE, 40);
const forged = ids.map(tokenId => ({ tokenId, article: { title: 'Barack Obama' }, statsSnapshot: { pageBytes: 9e9 } }));
await rejects(resolveDeck(deps, ALICE_ACCT, forged), 'unknown-token');
});
test('resolveDeck enforces the exact deck size from ruleset data', async () => {
const { ledger, deps } = fixture();
const ids = mintMany(ledger, ALICE, 41);
for (const deck of [ids.slice(0, 39), ids, [], 'nope', null, Array(10_000).fill(ids[0])]) await rejects(resolveDeck(deps, ALICE_ACCT, deck), 'size');
assert.equal((await resolveDeck(deps, ALICE_ACCT, ids.slice(0, 10), { deckSize: 10 })).length, 10, 'a testnet mode may lower deckSize');
});
test('resolveDeck rejects malformed and duplicated token ids', async () => {
const { ledger, deps } = fixture();
const ids = mintMany(ledger, ALICE, 40);
await rejects(resolveDeck(deps, ALICE_ACCT, [...ids.slice(0, 39), 'ABC']), 'unknown-token', ['ABC']);
await rejects(resolveDeck(deps, ALICE_ACCT, [...ids.slice(0, 39), ids[0]]), 'duplicate-token', [ids[0]]);
});
test('resolveDeck requires a linked wallet', async () => {
const { ledger, deps } = fixture();
const ids = mintMany(ledger, ALICE, 40);
await assert.rejects(resolveDeck(deps, { sub: 'stranger' }, ids), (e: unknown) => e instanceof DeckError && e.code === 'not-owned' && e.status === 403 && /Link a wallet/.test(e.message));
});
test('resolveDeck rejects unknown cards and cards owned by someone else, listing every one', async () => {
const { ledger, deps } = fixture();
const ids = mintMany(ledger, ALICE, 38);
const bobs = mintMany(ledger, BOB, 2, 500);
await rejects(resolveDeck(deps, ALICE_ACCT, [...ids, ...bobs]), 'not-owned', bobs);
await rejects(resolveDeck(deps, ALICE_ACCT, [...ids, hex('nope'), bobs[0]]), 'unknown-token', [hex('nope')]);
// Bob cannot field Alice's cards either, even though they exist.
await rejects(resolveDeck(deps, BOB_ACCT, [...ids, ...bobs]), 'not-owned', ids);
});
test('ownership follows transfers: the current owner, not the miner, may play the card', async () => {
const { ledger, deps } = fixture();
const ids = mintMany(ledger, ALICE, 40);
ledger.transfer(ids[7], BOB);
await rejects(resolveDeck(deps, ALICE_ACCT, ids), 'not-owned', [ids[7]]);
const cards = await resolveDeck(deps, BOB_ACCT, [ids[7], ...mintMany(ledger, BOB, 39, 300)]);
assert.equal(cards[0].owner, BOB);
});
test('resolveDeck requires minConfirmations (3 for rated play)', async () => {
const { ledger, deps } = fixture();
const ids = mintMany(ledger, ALICE, 40);
// The last card has 1 confirmation, the one before it 2.
await rejects(resolveDeck(deps, ALICE_ACCT, ids, { minConfirmations: 3 }), 'unconfirmed', ids.slice(38));
ledger.mineEmpty(2);
assert.equal((await resolveDeck(deps, ALICE_ACCT, ids, { minConfirmations: 3 })).length, 40);
});
test('duplicates of an article count as separate cards, up to 4 copies per pageId', async () => {
const { ledger, deps } = fixture();
const base = mintMany(ledger, ALICE, 35, 1);
const copies = Array.from({ length: 5 }, () => ledger.mint(ALICE, 777));
await assert.rejects(resolveDeck(deps, ALICE_ACCT, [...base, ...copies]),
(e: unknown) => e instanceof DeckError && e.code === 'copy-limit' && e.pageId === 777 && e.tokenIds.length === 5);
const cards = await resolveDeck(deps, ALICE_ACCT, [...base, ...copies.slice(0, 4), ledger.mint(ALICE, 900)]);
assert.equal(cards.filter(c => c.pageId === 777).length, 4);
assert.equal((await resolveDeck(deps, ALICE_ACCT, [...base, ...copies], { maxCopiesPerPage: 5 })).length, 40, 'the copy limit is ruleset data');
});
test('playableCount applies the copy limit', () => {
const cards = [1, 1, 1, 1, 1, 1, 2, 3].map(pageId => ({ pageId }));
assert.equal(playableCount(cards, 4), 6);
assert.equal(playableCount(cards, 1), 3);
});
test('collection lists every owned card across wallets with no 128-block cap', async () => {
const { ledger, deps } = fixture();
mintMany(ledger, ALICE, 150, 1);
mintMany(ledger, BOB, 10, 1000);
mintMany(ledger, ALICE2, 3, 2000);
const cards = await collection(deps, ALICE_ACCT);
assert.equal(cards.length, 153);
assert.equal(new Set(cards.map(x => x.tokenId)).size, 153);
assert.ok(cards.every(x => x.owner === ALICE || x.owner === ALICE2));
const r = collectionResponse(deps, 'alice');
assert.equal(r.owned, 153); assert.equal(r.playable, 153); assert.equal(r.needed, 0); assert.equal(r.eligible, true);
assert.deepEqual(r.wallets, [ALICE, ALICE2]);
assert.equal(r.tip, ledger.tip);
assert.deepEqual(await collection(deps, { sub: 'stranger' }), []);
});
test('collection shows progress toward 40 and applies the copy limit to eligibility', () => {
const { ledger, deps } = fixture();
mintMany(ledger, ALICE, 20, 1);
for (let i = 0; i < 10; i++) ledger.mint(ALICE, 4242);
const c = collectionResponse(deps, 'alice');
assert.equal(c.owned, 30); assert.equal(c.playable, 24); assert.equal(c.needed, 16); assert.equal(c.eligible, false);
assert.equal(c.deckSize, 40); assert.equal(c.copyLimit, 4); assert.equal(c.maxCopiesPerPage, 4);
assert.equal(collectionResponse(deps, 'alice', { deckSize: 20 }).eligible, true);
const none = collectionResponse(deps, 'stranger');
assert.equal(none.owned, 0); assert.equal(none.needed, 40); assert.deepEqual(none.cards, []);
});
test('collection only counts cards with enough confirmations', async () => {
const { ledger, deps } = fixture();
mintMany(ledger, ALICE, 5);
assert.equal((await collection(deps, ALICE_ACCT, { minConfirmations: 3 })).length, 3);
});
test('collection restarts when the tip moves mid-scan and gives up if it never settles', async () => {
const { ledger, deps } = fixture();
mintMany(ledger, ALICE, 60);
let moves = 1;
ledger.onDeck = () => { if (moves-- > 0) ledger.mint(ALICE, 9999); };
const c = collectionResponse(deps, 'alice');
assert.equal(c.owned, 61);
assert.equal(c.tip, ledger.tip);
ledger.onDeck = () => { ledger.mineEmpty(); };
await assert.rejects(collection(deps, ALICE_ACCT), OwnershipUnavailable);
});
async function serve(router: express.Router) {
const app = express();
app.use('/api/game/collection', router);
const server = app.listen(0, '127.0.0.1');
await new Promise(r => server.once('listening', r));
const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}/api/game/collection`;
return { base, close: () => new Promise(r => server.close(r)) };
}
test('GET /api/game/collection requires a verified eom.dev token (local loopback only, no upstream)', async () => {
const { ledger, deps } = fixture();
mintMany(ledger, ALICE, 23);
const { base, close } = await serve(collectionRouter(deps));
const as = (t: string) => ({ headers: { authorization: `Bearer ${t}` } });
try {
let res = await fetch(base);
assert.equal(res.status, 401);
res = await fetch(base, as('bad.token.x!'));
assert.equal(res.status, 401);
res = await fetch(base, as('expired.token.x'));
assert.equal(res.status, 401);
assert.equal((await res.json()).error, 'Token expired');
res = await fetch(base, as('dex.is.down'));
assert.equal(res.status, 503);
res = await fetch(`${base}?minConfirmations=abc`, as('good.token.alice'));
assert.equal(res.status, 400);
res = await fetch(base, as('good.token.alice'));
assert.equal(res.status, 200);
assert.equal(res.headers.get('cache-control'), 'no-store');
const body = await res.json();
assert.equal(body.owned, 23); assert.equal(body.playable, 23); assert.equal(body.needed, 17);
assert.equal(body.eligible, false); assert.equal(body.deckSize, 40); assert.equal(body.copyLimit, 4);
assert.equal(body.cards.length, 23);
assert.equal(body.cards[0].title, 'Article 1');
assert.equal(body.cards[0].pageId, 1);
res = await fetch(`${base}?minConfirmations=3`, as('good.token.alice'));
assert.equal((await res.json()).owned, 21);
res = await fetch(base, as('good.token.bob'));
assert.equal((await res.json()).owned, 0);
} finally { await close(); }
});
test('GET /api/game/collection attaches the injected duel card when one is ready, and omits it otherwise', async () => {
const { ledger, deps } = fixture();
mintMany(ledger, ALICE, 3);
const duelCard = (c: { pageId: number }) => {
if (c.pageId === 2) return undefined; // profile pending
if (c.pageId === 3) throw new Error('boom'); // never breaks the collection
return { kind: 'Figure', pageId: c.pageId };
};
const { base, close } = await serve(collectionRouter({ ...deps, duelCard }));
try {
const body = await (await fetch(base, { headers: { authorization: 'Bearer good.token.alice' } })).json();
assert.deepEqual(body.cards.map((c: { duel?: unknown }) => c.duel), [{ kind: 'Figure', pageId: 1 }, undefined, undefined]);
assert.ok(!('duel' in body.cards[1]));
} finally { await close(); }
});