forked from WikiDeck/wikideck
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>
212 lines
11 KiB
TypeScript
212 lines
11 KiB
TypeScript
/**
|
|
* Server-side ownership for constructed play (Night 2, #57). Signature agreed with host-pvp (#56).
|
|
*
|
|
* The host never trusts card data from a client. A deck arrives as token ids only; each one
|
|
* must be on the canonical chain, owned by one of the account's linked wallets, and confirmed
|
|
* enough. The card is then rebuilt from its own block (article + mint stats snapshot).
|
|
*
|
|
* Off-chain only: nothing here moves, burns or locks a card, and nothing touches consensus.
|
|
* No Wikipedia calls; the only I/O is the injected ID-token verifier (Dex JWKS, cached).
|
|
*/
|
|
import type { Account } from '../account/store.ts';
|
|
import type { Article } from '../../shared/protocol.ts';
|
|
import type { MintStatsSnapshot } from '../../shared/enrichment.ts';
|
|
import type { TestnetBlock } from '../../shared/testnet.ts';
|
|
|
|
export type OwnershipRules = {
|
|
/** Exact deck size for constructed play. Production is 40; a testnet mode file may lower it. */
|
|
deckSize: number;
|
|
/** MTG-style copy limit: cards minted from the same Wikipedia pageId. */
|
|
maxCopiesPerPage: number;
|
|
/** Minimum confirmations of each card's mint block (1 casual, 3 rated). */
|
|
minConfirmations: number;
|
|
};
|
|
export const DEFAULT_OWNERSHIP_RULES: Readonly<OwnershipRules> = Object.freeze({ deckSize: 40, maxCopiesPerPage: 4, minConfirmations: 1 });
|
|
export const RATED_MIN_CONFIRMATIONS = 3;
|
|
/** Upper bound on any deck request we will even look at (a deck is 40; this only guards the loop). */
|
|
export const MAX_DECK_TOKENS = 200;
|
|
/** Guard against an unbounded collection. Far above anything the chain can mint for one player soon. */
|
|
export const MAX_COLLECTION = 20_000;
|
|
/** server/testnet/ledger.ts MAX_DECK_PAGE. */
|
|
const PAGE = 24;
|
|
/** A tip change mid-scan restarts the scan; give up after this many rather than loop forever. */
|
|
const MAX_RESTARTS = 4;
|
|
|
|
// Structural: server/testnet/ledger.ts `Ledger` and server/account/store.ts `AccountStore`
|
|
// satisfy these, and tests pass in-memory fixtures.
|
|
export type OwnershipLedger = {
|
|
nft(tokenId: string): { block: TestnetBlock; owner: string; sequence: number; confirmations: number } | undefined;
|
|
deck(address: string, offset: number, limit: number): {
|
|
tip: string; total: number; next: number | null;
|
|
nfts: { block: TestnetBlock; sequence: number; confirmations: number }[];
|
|
};
|
|
summary(): { tip: string; height: number };
|
|
};
|
|
export type OwnershipAccounts = { wallets(sub: string): { address: string }[]; upsert?(a: Account): void };
|
|
export type OwnershipDeps = {
|
|
ledger: OwnershipLedger;
|
|
accounts: OwnershipAccounts;
|
|
/** server/account/router.ts accountVerifier(); throws an error with status 401 for a bad token. */
|
|
verifyIdToken(idToken: string): Promise<Account>;
|
|
};
|
|
|
|
/** One owned NFT as built from its canonical block (never from client JSON). */
|
|
export type ChainCard = {
|
|
tokenId: string;
|
|
/** Current owner (after transfers), one of the account's linked wallets. */
|
|
owner: string;
|
|
confirmations: number;
|
|
pageId: number;
|
|
title: string;
|
|
revisionId: number;
|
|
url: string;
|
|
extract: string;
|
|
imageUrl?: string;
|
|
height: number;
|
|
blockHash: string;
|
|
createdAt: number;
|
|
powHash: string;
|
|
article: Article;
|
|
statsSnapshot: MintStatsSnapshot;
|
|
};
|
|
|
|
export type DeckErrorCode = 'auth' | 'size' | 'duplicate-token' | 'unknown-token' | 'not-owned' | 'unconfirmed' | 'copy-limit';
|
|
const STATUS: Record<DeckErrorCode, 400 | 401 | 403> = {
|
|
auth: 401, size: 400, 'duplicate-token': 400, 'unknown-token': 400, 'not-owned': 403, unconfirmed: 400, 'copy-limit': 400,
|
|
};
|
|
export class DeckError extends Error {
|
|
readonly code: DeckErrorCode;
|
|
/** Every offending token of this class, so the UI can highlight them. */
|
|
readonly tokenIds: string[];
|
|
readonly status: 400 | 401 | 403;
|
|
readonly pageId?: number;
|
|
constructor(code: DeckErrorCode, message: string, tokenIds: string[] = [], pageId?: number) {
|
|
super(message);
|
|
this.name = 'DeckError';
|
|
this.code = code; this.tokenIds = tokenIds; this.status = STATUS[code];
|
|
if (pageId !== undefined) this.pageId = pageId;
|
|
}
|
|
}
|
|
/** Thrown when Dex or the ledger cannot answer right now (not the player's fault). */
|
|
export class OwnershipUnavailable extends Error { readonly status = 503; }
|
|
|
|
const TOKEN = /^[a-f0-9]{64}$/;
|
|
const isInt = (n: unknown, min: number, max: number): n is number => Number.isSafeInteger(n) && (n as number) >= min && (n as number) <= max;
|
|
|
|
/** Merges partial rules over the defaults and rejects nonsense (mode files are data, so validate). */
|
|
export function ownershipRules(rules: Partial<OwnershipRules> = {}): OwnershipRules {
|
|
const defined = Object.fromEntries(Object.entries(rules).filter(([, v]) => v !== undefined)) as Partial<OwnershipRules>;
|
|
const r = { ...DEFAULT_OWNERSHIP_RULES, ...defined };
|
|
if (!isInt(r.deckSize, 1, MAX_DECK_TOKENS)) throw new RangeError(`deckSize must be 1..${MAX_DECK_TOKENS}`);
|
|
if (!isInt(r.maxCopiesPerPage, 1, MAX_DECK_TOKENS)) throw new RangeError(`maxCopiesPerPage must be 1..${MAX_DECK_TOKENS}`);
|
|
if (!isInt(r.minConfirmations, 1, 1_000_000)) throw new RangeError('minConfirmations must be >= 1');
|
|
return r;
|
|
}
|
|
|
|
/** Builds the card from the canonical block. `owner` is the current owner from the index, not the miner. */
|
|
export function cardFromChain(nft: { block: TestnetBlock; confirmations: number }, owner: string): ChainCard {
|
|
const b = structuredClone(nft.block);
|
|
const card: ChainCard = { tokenId: b.tokenId, owner, confirmations: nft.confirmations,
|
|
pageId: b.article.pageId, title: b.article.title, revisionId: b.article.revisionId, url: b.article.url, extract: b.article.extract,
|
|
height: b.height, blockHash: b.hash, createdAt: b.createdAt, powHash: b.powHash, article: b.article, statsSnapshot: b.statsSnapshot };
|
|
if (b.article.image) card.imageUrl = b.article.image;
|
|
return card;
|
|
}
|
|
|
|
/** Verifies a Dex ID token from a request body. Throws DeckError('auth') or OwnershipUnavailable. */
|
|
export async function verifyAccount(deps: Pick<OwnershipDeps, 'verifyIdToken'>, idToken: unknown): Promise<Account> {
|
|
if (typeof idToken !== 'string' || !idToken || idToken.length > 8192) throw new DeckError('auth', 'Log in with your eom.dev account to play with your cards');
|
|
try { return await deps.verifyIdToken(idToken); }
|
|
catch (e) {
|
|
if ((e as { status?: number }).status === 401) throw new DeckError('auth', (e as Error).message || 'Log in again with your eom.dev account');
|
|
throw new OwnershipUnavailable('eom.dev login is temporarily unavailable');
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Verifies a constructed deck for an already-verified account. Resolves to the cards in the
|
|
* order given, or throws the first class of DeckError found (listing every offending token).
|
|
*/
|
|
export async function resolveDeck(deps: Pick<OwnershipDeps, 'ledger' | 'accounts'>, account: Pick<Account, 'sub'>, tokenIds: unknown,
|
|
opts?: Partial<OwnershipRules>): Promise<ChainCard[]> {
|
|
const r = ownershipRules(opts);
|
|
if (!Array.isArray(tokenIds) || tokenIds.length > MAX_DECK_TOKENS) throw new DeckError('size', `A deck is exactly ${r.deckSize} cards`);
|
|
const invalid = tokenIds.filter(t => typeof t !== 'string' || !TOKEN.test(t)).map(t => String(t).slice(0, 80)).slice(0, 10);
|
|
if (invalid.length) throw new DeckError('unknown-token', 'Invalid card identifier', invalid);
|
|
const ids = tokenIds as string[];
|
|
if (ids.length !== r.deckSize) throw new DeckError('size', `A deck is exactly ${r.deckSize} cards (got ${ids.length})`);
|
|
const seen = new Set<string>(), dupes = new Set<string>();
|
|
for (const id of ids) (seen.has(id) ? dupes : seen).add(id);
|
|
if (dupes.size) throw new DeckError('duplicate-token', 'The same card appears more than once', [...dupes]);
|
|
|
|
const wallets = new Set(deps.accounts.wallets(account.sub).map(w => w.address));
|
|
if (!wallets.size) throw new DeckError('not-owned', 'Link a wallet to your eom.dev account to play with your cards', ids);
|
|
|
|
const cards: ChainCard[] = [], missing: string[] = [], foreign: string[] = [], young: string[] = [];
|
|
for (const id of ids) {
|
|
const nft = deps.ledger.nft(id);
|
|
if (!nft || nft.block.tokenId !== id) { missing.push(id); continue; }
|
|
if (!wallets.has(nft.owner)) { foreign.push(id); continue; }
|
|
if (nft.confirmations < r.minConfirmations) { young.push(id); continue; }
|
|
cards.push(cardFromChain(nft, nft.owner));
|
|
}
|
|
if (missing.length) throw new DeckError('unknown-token', 'Card not found on the canonical chain', missing);
|
|
if (foreign.length) throw new DeckError('not-owned', 'Card is not owned by a wallet linked to this account', foreign);
|
|
if (young.length) throw new DeckError('unconfirmed', `Card needs ${r.minConfirmations} confirmation${r.minConfirmations === 1 ? '' : 's'}`, young);
|
|
|
|
const byPage = new Map<number, string[]>();
|
|
for (const c of cards) byPage.set(c.pageId, [...(byPage.get(c.pageId) ?? []), c.tokenId]);
|
|
for (const [pageId, tokens] of byPage)
|
|
if (tokens.length > r.maxCopiesPerPage) throw new DeckError('copy-limit', `At most ${r.maxCopiesPerPage} copies of the same article`, tokens, pageId);
|
|
return cards;
|
|
}
|
|
|
|
/**
|
|
* Every card the account owns across its linked wallets, read at one canonical tip (restarting
|
|
* if the tip moves), with no snapshot cap. Only cards with `minConfirmations` (default 1).
|
|
*/
|
|
export async function collection(deps: Pick<OwnershipDeps, 'ledger' | 'accounts'>, account: Pick<Account, 'sub'>,
|
|
opts: { minConfirmations?: number } = {}): Promise<ChainCard[]> {
|
|
return collectionAt(deps, account, opts).cards;
|
|
}
|
|
|
|
/** collection() plus the tip and wallets it was read at. Synchronous. */
|
|
export function collectionAt(deps: Pick<OwnershipDeps, 'ledger' | 'accounts'>, account: Pick<Account, 'sub'>,
|
|
opts: { minConfirmations?: number } = {}): { tip: string; wallets: string[]; cards: ChainCard[] } {
|
|
const minConfirmations = ownershipRules({ minConfirmations: opts.minConfirmations }).minConfirmations;
|
|
const wallets = [...new Set(deps.accounts.wallets(account.sub).map(w => w.address))];
|
|
for (let attempt = 0; attempt <= MAX_RESTARTS; attempt++) {
|
|
const tip = deps.ledger.summary().tip;
|
|
const cards = scan(deps.ledger, wallets, tip, minConfirmations);
|
|
if (cards) return { tip, wallets, cards };
|
|
}
|
|
throw new OwnershipUnavailable('The chain is moving too fast to read a consistent collection; try again');
|
|
}
|
|
|
|
/** Returns null if the tip moved during the scan. */
|
|
function scan(ledger: OwnershipLedger, wallets: string[], tip: string, minConfirmations: number): ChainCard[] | null {
|
|
const cards: ChainCard[] = [];
|
|
for (const address of wallets) {
|
|
let offset: number | null = 0;
|
|
while (offset !== null) {
|
|
const page = ledger.deck(address, offset, PAGE);
|
|
if (page.tip !== tip) return null;
|
|
for (const nft of page.nfts) {
|
|
if (nft.confirmations >= minConfirmations) cards.push(cardFromChain(nft, address));
|
|
if (cards.length > MAX_COLLECTION) throw new OwnershipUnavailable('Collection too large to list');
|
|
}
|
|
// Defensive: a page that makes no progress would loop forever.
|
|
offset = page.next !== null && page.next > offset ? page.next : null;
|
|
}
|
|
}
|
|
return cards;
|
|
}
|
|
|
|
/** How many of these cards a legal deck could use under the copy limit: Σ min(copies, limit) per pageId. */
|
|
export function playableCount(cards: Pick<ChainCard, 'pageId'>[], maxCopiesPerPage: number): number {
|
|
const perPage = new Map<number, number>();
|
|
for (const c of cards) perPage.set(c.pageId, (perPage.get(c.pageId) ?? 0) + 1);
|
|
let n = 0; for (const count of perPage.values()) n += Math.min(count, maxCopiesPerPage);
|
|
return n;
|
|
}
|