Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
00195e9f14 | ||
|
|
3d133cbd14 | ||
|
|
83ae18a17f | ||
|
|
a0a051c10a | ||
|
|
b67192a08b | ||
|
|
2f1bba5e4c | ||
|
|
ec75875f0d | ||
|
|
a61c1a1342 | ||
|
|
75791f5861 | ||
|
|
7474b1c71d | ||
|
|
2cfdd9f437 | ||
|
|
26ad924565 | ||
|
|
86e544ea2e | ||
|
|
4bbc341bcb | ||
|
|
52c40bd3e3 | ||
|
|
bd6c7094b1 | ||
|
|
361efaa1d6 | ||
|
|
0f774f13b3 | ||
|
|
974c2651bf | ||
|
|
c9c901c7f2 | ||
|
|
8e448c26f2 | ||
|
|
4a4941c6ff | ||
|
|
6bd2dab74b | ||
|
|
4657a58800 | ||
|
|
df6bd04042 | ||
|
|
482de6ce3c | ||
|
|
5a83d34c59 | ||
|
|
a0bd095c4e | ||
|
|
b5c90d2dc1 | ||
|
|
ae50e62535 | ||
|
|
feae445f5a | ||
|
|
e7e51aecdb | ||
|
|
6fb9a2e8b4 | ||
|
|
b2ec917af4 | ||
|
|
c1a1325564 | ||
|
|
2e7b05bdad | ||
|
|
53d30e5cae | ||
|
|
7390a17a91 | ||
|
|
f507b0eaed | ||
|
|
1d3c5e5743 | ||
|
|
636f5b9c77 | ||
|
|
1edf2e6200 | ||
|
|
0b9061372b
|
||
|
|
716c9612cc | ||
|
|
9c93c9ec15 | ||
|
|
45785fb627
|
||
|
|
6155e8b3ed
|
||
|
|
9625ee2db7 | ||
|
|
f26e38b096 | ||
|
|
4fefffe4a1
|
||
|
|
bc6471fc54
|
||
|
|
4b47386853
|
||
|
|
10b5466f88 | ||
|
|
6d3f470922
|
@@ -0,0 +1,20 @@
|
||||
node_modules
|
||||
dist
|
||||
.git
|
||||
data
|
||||
native/build
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
**/*.wallet.json
|
||||
**/*backup*.json
|
||||
**/*.sqlite
|
||||
**/*.sqlite-*
|
||||
**/*.pem
|
||||
**/*.key
|
||||
**/*.p12
|
||||
**/*.pfx
|
||||
*.log
|
||||
.vscode
|
||||
.idea
|
||||
|
||||
@@ -1,6 +1,30 @@
|
||||
venv/*
|
||||
mine_data/*
|
||||
mariadb_data/*
|
||||
*.pem
|
||||
*__pycache__*
|
||||
*.swp
|
||||
node_modules/
|
||||
dist/
|
||||
data/
|
||||
native/build/
|
||||
*.wallet.json
|
||||
.env
|
||||
*.log# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
[submodule "native/build/_deps/randomx-src"]
|
||||
path = native/build/_deps/randomx-src
|
||||
url = https://github.com/tevador/RandomX.git
|
||||
@@ -1,6 +1,66 @@
|
||||
FROM ericomeehan/httpd-mod-wsgi
|
||||
RUN apt update && apt upgrade -y
|
||||
RUN apt install -y libmariadb3 libmariadb-dev python3-dev python3-pip
|
||||
COPY . /usr/local/apache2/htdocs
|
||||
RUN pip3 install --break-system-packages -r /usr/local/apache2/htdocs/requirements.txt
|
||||
EXPOSE 80
|
||||
# syntax=docker/dockerfile:1
|
||||
FROM node:24-alpine AS randomx-build
|
||||
RUN apk add --no-cache build-base cmake git linux-headers
|
||||
WORKDIR /native
|
||||
COPY native/CMakeLists.txt native/randomx-engine.cpp ./
|
||||
RUN cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DWIKIDECK_RANDOMX_TESTS=ON \
|
||||
&& cmake --build build --parallel 2 \
|
||||
&& ctest --test-dir build --output-on-failure
|
||||
|
||||
FROM node:24-alpine AS build
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci
|
||||
COPY . .
|
||||
ARG WIKIDECK_NETWORK=mainnet
|
||||
ARG WIKIDECK_GENESIS_TIME=1793491200
|
||||
ENV VITE_WIKIDECK_NETWORK=$WIKIDECK_NETWORK
|
||||
ENV VITE_WIKIDECK_GENESIS_TIME=$WIKIDECK_GENESIS_TIME
|
||||
RUN npm run build
|
||||
|
||||
FROM build AS test
|
||||
RUN apk add --no-cache libstdc++
|
||||
ENV WIKIDECK_NETWORK=testnet \
|
||||
WIKIDECK_GENESIS_TIME=1792411200 \
|
||||
VITE_WIKIDECK_NETWORK=testnet \
|
||||
VITE_WIKIDECK_GENESIS_TIME=1792411200
|
||||
RUN npm run build
|
||||
COPY --from=randomx-build /native/build/wikideck-randomx /app/native/wikideck-randomx
|
||||
ENV RANDOMX_BINARY=/app/native/wikideck-randomx
|
||||
CMD ["npm", "test"]
|
||||
|
||||
FROM node:24-alpine AS production-deps
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci --omit=dev --ignore-scripts && npm cache clean --force
|
||||
|
||||
FROM node:24-alpine AS runtime
|
||||
RUN apk add --no-cache libstdc++
|
||||
ARG WIKIDECK_NETWORK=mainnet
|
||||
ARG WIKIDECK_GENESIS_TIME=1793491200
|
||||
ENV NODE_ENV=production \
|
||||
HOST=0.0.0.0 \
|
||||
PORT=3001 \
|
||||
WIKIDECK_DATA_DIR=/app/data \
|
||||
RANDOMX_BINARY=/app/native/wikideck-randomx \
|
||||
WIKIDECK_NETWORK=$WIKIDECK_NETWORK \
|
||||
WIKIDECK_GENESIS_TIME=$WIKIDECK_GENESIS_TIME \
|
||||
WIKIDECK_IMAGE_NETWORK=$WIKIDECK_NETWORK \
|
||||
WIKIDECK_IMAGE_GENESIS_TIME=$WIKIDECK_GENESIS_TIME
|
||||
WORKDIR /app
|
||||
COPY --from=production-deps /app/node_modules ./node_modules
|
||||
COPY package.json ./
|
||||
COPY --from=build /app/dist ./dist
|
||||
COPY server ./server
|
||||
COPY shared ./shared
|
||||
COPY scripts/node-backup.ts ./scripts/node-backup.ts
|
||||
COPY scripts/ops-check.ts ./scripts/ops-check.ts
|
||||
COPY --from=randomx-build /native/build/wikideck-randomx ./native/wikideck-randomx
|
||||
RUN mkdir -p /app/data && chown node:node /app/data
|
||||
USER node
|
||||
EXPOSE 3001
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=60s --retries=3 \
|
||||
CMD ["node", "-e", "fetch('http://127.0.0.1:3001/healthz', {signal: AbortSignal.timeout(4000)}).then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))"]
|
||||
# Node 24 strips the server's erasable TypeScript; no tsx/dev dependencies at runtime.
|
||||
CMD ["node", "--experimental-strip-types", "server/index.ts"]
|
||||
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
FROM node:24-alpine
|
||||
WORKDIR /app
|
||||
COPY package.json ./
|
||||
RUN npm install --package-lock-only --ignore-scripts
|
||||
@@ -1,10 +1,164 @@
|
||||
# WikiDeck
|
||||
An [NFT](https://en.wikipedia.org/wiki/Non-fungible_token)
|
||||
[blockchain](https://en.wikipedia.org/wiki/Blockchain) that rewards Wikipedia trading cards.
|
||||
|
||||
## Use
|
||||
See `test/Mine/TestMine.py` for a demonstration of the basic client workflow.
|
||||
|
||||
## Status
|
||||
At present, only the files in `wikideck/Mine` are functional - and only partially so. This
|
||||
project is currently a proof-of-concept.
|
||||
# Wikideck
|
||||
|
||||
Wikideck is an experimental blockchain game about **mining, collecting, and trading illustrated Wikipedia cards**. Mine a block with the native RandomX CPU miner to earn a card, build a collection in a local wallet, and trade cards directly with another player.
|
||||
|
||||
**Mainnet-first, still NO-GO:** the default image, runtime profile, and Compose service are mainnet, but the network is experimental, unaudited, and not launched. A local build is not production approval. See the [card-only production plan](docs/card-only-production-plan.md) and [mainnet launch gates](docs/mainnet-launch.md).
|
||||
|
||||
Mining uses **RandomX, the proof-of-work algorithm also used by Monero**, designed to keep general-purpose consumer CPUs competitive. Wikideck is an independent blockchain, not part of Monero or its mining/security network. Hardware, total network hashpower and difficulty determine results; no particular mining reward rate or profitability is guaranteed.
|
||||
|
||||
**Mainnet is a gated candidate, not an operating public network or an investment product.** There are no hosted nodes, public bootnodes, or automatic peer discovery. No external audit is planned; the operator accepts that residual risk. Cards have no promised monetary value. Do not use funds or valuable assets. This project is not affiliated with Wikipedia or the Wikimedia Foundation.
|
||||
|
||||
## Mine, collect, and trade cards
|
||||
|
||||
- **Mine Wikipedia cards.** Each accepted block mints a native NFT for the miner from a random illustrated English Wikipedia article. The card records the article snapshot and mint-time statistics. The same page can appear on more than one distinct card. The reward is a card representing a page—not ownership of the page, its copyright, or a payment to Wikipedia.
|
||||
- **Build collections.** Browse chain discoveries or focus on a subject, series, or theme. Cards are controlled by your encrypted local wallet.
|
||||
- **Trade directly.** Look up another public wallet and exchange up to eight cards on each side in one signed, atomic trade. Offers are shared between the two players; the app does not list cards for sale or process payments.
|
||||
- **Gameplay is not included yet.** The current release supports mining, collecting, transfers, and direct trades. Playable card games are future work.
|
||||
|
||||
**Licensing status:** this checkout does not yet contain a project LICENSE file. Source availability alone does not grant open-source modification/redistribution rights. Wikipedia text/images and dependencies retain their separate licenses.
|
||||
|
||||
## What's available now
|
||||
|
||||
| Available in the mainnet-first codebase | Not included |
|
||||
| --- | --- |
|
||||
| RandomX mining and illustrated Wikipedia card rewards | Playable card games |
|
||||
| Encrypted local wallets, collections, transfers, and atomic card trades | Production network launch |
|
||||
| Mainnet candidate by default; testnet only as an explicit local development fixture | Public bootstrap network or production readiness |
|
||||
|
||||
## Default: mainnet candidate (Docker)
|
||||
|
||||
The default mainnet genesis is fixed at **November 1, 2026, 00:00 UTC**
|
||||
(`1793491200`). Rebuilding the current Dockerfile requires no special genesis
|
||||
argument and no wait until January. Publish the rebuilt image as
|
||||
`ericomeehan/wikideck:latest` before using the three-node Ansible playbook; it reads
|
||||
the chain ID automatically and configures the risk acknowledgment and internal
|
||||
peers. This updates source defaults, not an already published image or an existing
|
||||
ledger's chain identity. Create/unlock a wallet in the deployed HTTPS UI and run
|
||||
the native miner to produce cards and confirm transfers/trades.
|
||||
|
||||
Install Docker Desktop with Linux containers and Docker Compose v2. From the repository root:
|
||||
|
||||
```sh
|
||||
docker compose up --build -d
|
||||
docker compose ps
|
||||
```
|
||||
|
||||
The default Compose service is mainnet-first and binds only to **http://127.0.0.1:3201** behind a separately configured HTTPS edge. It intentionally exits until the exact chain approval, explicit unaudited-risk acceptance, genesis time, HTTPS origin, and at least two valid public HTTPS peers are configured. Do not set these to placeholders just to make the process start. See [mainnet launch gates](docs/mainnet-launch.md). The node does not mine automatically. Stop it with `docker compose down`; the ledger volume remains. **Do not add `-v` unless you intend to delete that data.**
|
||||
|
||||
For isolated development, use the explicitly testnet-only [three-node fixture](#explicit-testnet-development-fixture-docker). `npm run dev` also pins both the API and Vite browser build to that testnet fixture; it does not silently change a production build.
|
||||
|
||||
## Explicit testnet development fixture (Docker)
|
||||
|
||||
Install Docker Desktop with Linux containers and Docker Compose v2. From the repository root, start three connected nodes:
|
||||
|
||||
```sh
|
||||
docker compose -f compose.testnet.yaml up --build -d
|
||||
docker compose -f compose.testnet.yaml ps
|
||||
docker compose -f compose.testnet.yaml logs -f node-a
|
||||
```
|
||||
|
||||
Open **http://127.0.0.1:3101**. The other nodes are at **http://127.0.0.1:3102** and **http://127.0.0.1:3103**. Each node validates blocks independently and stores its ledger in a separate Docker volume. Mining does not start automatically. A healthy node is not necessarily connected to its peers; check the peer status in the interface or request `/api/peers`. Nodes need outbound access to Wikipedia when generating mining templates and capturing mint-time statistics. If that data is unavailable, the node returns an error and mining can be retried.
|
||||
|
||||
Stop the nodes with:
|
||||
|
||||
```sh
|
||||
docker compose -f compose.testnet.yaml down
|
||||
```
|
||||
|
||||
The target block interval is **15 minutes**. The volumes persist across stops and rebuilds. **Do not add `-v` unless you intend to delete all three ledgers.** Back up wallets separately. Protocol v6 adds atomic multi-card trades and a new chain identity; earlier v2–v5 ledgers and encrypted backups are not compatible. To keep old Docker data intact while trying v6, use a separate Compose project name, for example `docker compose -p wikideck-v6 -f compose.testnet.yaml up --build -d`, and use the same `-p wikideck-v6` for subsequent Compose commands. The default `docker compose up --build -d` uses [compose.yaml](compose.yaml): it starts one isolated node on port 3001 with a different volume.
|
||||
|
||||
For an existing host install, keep the old data directory intact and set `WIKIDECK_DATA_DIR` to a new empty directory before starting protocol v6. The node intentionally fails closed on an old-protocol ledger; it does not reset or migrate it. A v6 JSON ledger is imported into SQLite on first startup and left in place as a recovery copy. `npm start` defaults to the gated mainnet identity; use `npm run dev` only for local testnet development.
|
||||
|
||||
## Run on your host
|
||||
|
||||
Requirements: Node.js 24, npm, Git, CMake 3.24+, and a C/C++17 toolchain. The first native-engine configuration downloads the pinned RandomX source over HTTPS. On Windows, install a compatible toolchain (for example, MinGW-w64 and make) and use the matching CMake generator. Do not change generators in an existing `native/build` directory; use a fresh build directory when switching toolchains.
|
||||
|
||||
Install dependencies and build the native RandomX engine:
|
||||
|
||||
```sh
|
||||
npm install
|
||||
npm run native:configure
|
||||
npm run native:build
|
||||
npm run test:native
|
||||
npm run build
|
||||
npm start
|
||||
```
|
||||
|
||||
On Windows with MinGW, configure with `npm run native:configure -- -G "MinGW Makefiles"`. If PowerShell blocks the `npm` shim, use `npm.cmd`; follow your organization's execution policy rather than bypassing it. The optional platform scripts are [scripts/build-randomx.ps1](scripts/build-randomx.ps1) and [scripts/build-randomx.sh](scripts/build-randomx.sh). See [native engine setup and protocol](docs/randomx-native.md) for toolchain details.
|
||||
|
||||
The node listens at **http://127.0.0.1:3001** by default. For development, `npm run dev` starts the API on port 3001 and Vite on **http://127.0.0.1:5173**. Keep both services on loopback; Vite proxies the browser's `/api` requests to the API. The native miner should connect directly to the API port, not Vite.
|
||||
|
||||
## Wallets and backups
|
||||
|
||||
Open the wallet panel to explicitly create an encrypted local P-256 wallet, unlock an existing vault, or encrypt a legacy plaintext wallet without changing its identity. Nothing is silently generated or unlocked at startup. Choose a strong local password of at least 12 characters. **Wallet backup & recovery** downloads a separately password-encrypted portable backup; keep the file outside the repository and its password separately, and test recovery in another browser profile.
|
||||
|
||||
New/migrated local vaults encrypt the key in an IndexedDB database scoped to the exact chain ID; v2 encrypted backups authenticate that same chain ID. Original fixed-testnet v1 backups remain recoverable only on that original testnet. The unlocked key remains exportable in tab memory for signing and backup. Manual locking, five-minute inactivity, a four-hour absolute lifetime, reload, or hiding/leaving the tab ends the session. Same-origin compromise can still capture passwords or abuse an unlocked signer. Forgotten local passwords cannot be reset: recover from a usable backup. Legacy disk copies may retain old plaintext keys even after migration. Wallets are scoped to an origin (scheme, hostname, and port), so a backup must be restored at another origin to use the same identity there. Recovery does not move assets between chains. See [encrypted wallet lifecycle and remaining risks](docs/wallet-security.md).
|
||||
|
||||
Each genesis has a separate browser wallet store, and backups cannot cross chain identities. Testnet remains only as an explicit development fixture; there is no automatic migration from older demos. See [consensus, wallets, and operational limits](docs/testnet-consensus.md) and the in-app backup warnings for more detail.
|
||||
|
||||
## Mine Wikipedia cards with RandomX
|
||||
|
||||
Mining uses the native CPU RandomX engine. First build the engine, download an encrypted wallet backup, then run the CLI from an interactive terminal and enter the password at its hidden prompt:
|
||||
|
||||
```sh
|
||||
npm run miner:testnet -- --wallet "path/to/encrypted-backup.json" --consent --node http://127.0.0.1:3101 --blocks 3
|
||||
```
|
||||
|
||||
The example is intentionally testnet-only and uses node-a; the dedicated command pins that profile and its fixed genesis. For mainnet, use `npm run miner` with a chain-bound mainnet backup and the configured HTTPS node origin after satisfying the mainnet launch gates. The miner defaults to one worker, light mode, and one block; `--blocks 3` requests up to three accepted blocks. Press **Ctrl+C** to stop it. Do not put the backup password in a command, environment variable, or repository file. The backup and password are decrypted locally and are not sent to the node.
|
||||
|
||||
Each template request asks English Wikipedia for up to ten random pages and retries at most three times to find one with an image and readable extract. The same page may be selected again. The node also captures page size, language-link count, revision, pageviews, and derived scores for the mint-time snapshot. If Wikipedia cannot supply the article or its metadata, template creation returns an error; there is no fixed-article fallback. Validators check and commit the included snapshot without contacting Wikipedia during consensus validation.
|
||||
|
||||
Light mode needs a 256 MiB cache plus scratchpad and process overhead. `--fast` is optional and needs over 2.3 GiB per miner process. Mining consumes CPU, power, and time; RandomX is not a guarantee of ASIC resistance. Do not expose an HTTP miner endpoint remotely; use HTTPS. Detailed resource, native build, and line-protocol notes are in [docs/randomx-native.md](docs/randomx-native.md).
|
||||
|
||||
## What the app shows
|
||||
|
||||
- **Discover** shows preview examples until the node has mined blocks; previews are not owned NFTs. Minted cards can reference the same page, but each carries its own captured stats snapshot.
|
||||
- **My collection** shows NFTs owned by the active local wallet on the connected node's canonical chain.
|
||||
- **Block explorer** distinguishes block IDs, NFT token IDs, and RandomX proof hashes. A submitted transfer is pending until a block confirms it. Reorganizations can change canonical ownership and confirmations.
|
||||
- **Trade cards** lets you look up another public wallet by receive address, select up to eight cards on each side, prepare a signed offer, and accept another player's offer. Offers are shared as JSON for the other player to review; they are not submitted until accepted. The two parties sign the same card list, and validators apply the whole bundle atomically or reject it entirely. Offers are not reservations: before acceptance the app re-checks ownership, maturity, sequences, and pending activity; stale offers must be recreated.
|
||||
- Each minted card shows current Wikipedia statistics alongside its immutable at-mint snapshot: pageviews, article size, language links, revision, and derived scores. Current values may change; at-mint values are committed to the block. Missing pageview data stays unavailable, not zero.
|
||||
- The appearance selector offers Catppuccin Mocha, Macchiato, Frappé, and Latte themes.
|
||||
|
||||
The browser interface trusts the connected node's reported state. It does not independently verify the chain or provide an SPV client. Transfers are irreversible once confirmed; check the recipient address carefully.
|
||||
|
||||
## Mainnet candidate · launch gated
|
||||
|
||||
**Production status: NO-GO pending network, capacity, deployment, and recovery evidence.** External audits are not planned; the operator accepts the residual risk, and the candidate must not be described as audited or certified. See the [security review](docs/security-review.md) and [operator launch checklist](docs/operator-launch.md). A read-only `launch:preflight` script reports blockers and local gate status without launching or granting approval.
|
||||
|
||||
The mainnet profile is the default and has a deployment-pinned network/genesis identity, separate ledger directory, chain-ID-scoped browser wallet, and chain-bound backups. The alternate [Compose definition](compose.mainnet.yaml) is also explicitly mainnet. Testnet is available only through the dedicated development/test harness. **No production network has been launched or certified by this work.** Startup requires explicit chain-specific approval, explicit unaudited-risk acceptance, the chosen genesis time in the built image, HTTPS origin, and multiple configured public peers. See [the mainnet launch gates and production checklist](docs/mainnet-launch.md).
|
||||
|
||||
## Tests and development checks
|
||||
|
||||
Offline preparation tools: `analyze:consensus` reports deterministic retarget/timestamp scenarios; `benchmark:randomx` runs a bounded native benchmark only with explicit `--consent`. Neither launches a node nor changes consensus or approval settings. See [calibration evidence and limitations](docs/consensus-calibration.md) before interpreting rates or illustrative targets.
|
||||
|
||||
```sh
|
||||
npm test
|
||||
npm run build
|
||||
npm run test:native
|
||||
```
|
||||
|
||||
`npm test` runs the application test suite, including fast test-only proof tests. `npm run test:native` runs the real upstream RandomX known-vector test and requires a native build configured with tests enabled; the documented `npm run native:configure` command enables them. The Docker build also builds RandomX and runs its native test.
|
||||
|
||||
The Dockerfile also provides a **test** target containing Node 24, development dependencies, the tests, and the compiled Linux-native RandomX binary. Build that target and run the resulting image to exercise the full native HTTP suite without relying on a host-platform binary. TypeScript compilation enforces erasable syntax because the production runtime strips types directly.
|
||||
|
||||
To explicitly test propagation and transfer behavior across the three local Docker nodes, first build the host native engine and start the three-node testnet, then run:
|
||||
|
||||
```sh
|
||||
node --experimental-strip-types scripts/testnet-smoke.ts --consent
|
||||
```
|
||||
|
||||
This mines three real blocks using disposable identities. It changes the testnet, and is not run automatically.
|
||||
|
||||
## Network and safety limits
|
||||
|
||||
[Deployment and recovery preparation](docs/operations-recovery.md) includes explicit trusted-proxy configuration, opt-in loopback-only diagnostics and `ops:check`, plus stopped-node `node:backup` create/verify/new-directory restore tooling. New backups contain the ledger only; creation refuses to proceed if legacy financial journals or bindings remain, so archive those separately before retiring old deployments. Tools do not configure TLS/alerts or authorize production launch/restore.
|
||||
|
||||
[Stage-1 node resource controls](docs/node-resources.md) bound global RPC admission, response bytes and canonical page sizes. The UI reuses paged history; legacy full-state responses stop beyond 128 blocks. A consent-gated loopback-only smoke-load script is available as `test:rpc-load`. This does not resolve long-chain/DAG storage limits or establish production capacity.
|
||||
|
||||
Nodes use only explicitly configured peers; there is no discovery service or public bootstrap network. The peer, storage, and HTTP configuration is documented in [docs/testnet-consensus.md](docs/testnet-consensus.md). The implementation is experimental: it has no established economic security and remains vulnerable to resource exhaustion, isolation/eclipsing, censorship, majority-hashpower attacks, and reorganizations. The ledger now uses transactional SQLite/WAL storage and sparse per-block NFT-state deltas, but nodes still retain DAG block records in memory, rebuild state roots over the full NFT set, and revalidate all proofs at startup. It is not yet an archival-scale production design. HTTPS, container hardening, and passing tests do not constitute a security audit.
|
||||
|
||||
Before considering any broader deployment, complete adversarial network testing, hardened abuse controls, and recovery procedures. External protocol/cryptography audits are not planned; this leaves accepted residual risk. Do not expose a public node or use valuable assets on this experimental network.
|
||||
|
||||
## Attribution
|
||||
|
||||
The four original starter summaries in the interface are preview examples only; they are not mintable. Mined cards contain short snapshots from Wikipedia contributors, licensed under [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/), and a Wikimedia-hosted picture. Open each card's **Image & license** link and review the file-specific license and attribution before reuse. A native NFT does not grant copyright or exclusive rights to article text or images.
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
# Using Android gitignore template: https://github.com/github/gitignore/blob/HEAD/Android.gitignore
|
||||
|
||||
# Built application files
|
||||
*.apk
|
||||
*.aar
|
||||
*.ap_
|
||||
*.aab
|
||||
|
||||
# Files for the ART/Dalvik VM
|
||||
*.dex
|
||||
|
||||
# Java class files
|
||||
*.class
|
||||
|
||||
# Generated files
|
||||
bin/
|
||||
gen/
|
||||
out/
|
||||
# Uncomment the following line in case you need and you don't have the release build type files in your app
|
||||
# release/
|
||||
|
||||
# Gradle files
|
||||
.gradle/
|
||||
build/
|
||||
|
||||
# Local configuration file (sdk path, etc)
|
||||
local.properties
|
||||
|
||||
# Proguard folder generated by Eclipse
|
||||
proguard/
|
||||
|
||||
# Log Files
|
||||
*.log
|
||||
|
||||
# Android Studio Navigation editor temp files
|
||||
.navigation/
|
||||
|
||||
# Android Studio captures folder
|
||||
captures/
|
||||
|
||||
# IntelliJ
|
||||
*.iml
|
||||
.idea/workspace.xml
|
||||
.idea/tasks.xml
|
||||
.idea/gradle.xml
|
||||
.idea/assetWizardSettings.xml
|
||||
.idea/dictionaries
|
||||
.idea/libraries
|
||||
# Android Studio 3 in .gitignore file.
|
||||
.idea/caches
|
||||
.idea/modules.xml
|
||||
# Comment next line if keeping position of elements in Navigation Editor is relevant for you
|
||||
.idea/navEditor.xml
|
||||
|
||||
# Keystore files
|
||||
# Uncomment the following lines if you do not want to check your keystore files in.
|
||||
#*.jks
|
||||
#*.keystore
|
||||
|
||||
# External native build folder generated in Android Studio 2.2 and later
|
||||
.externalNativeBuild
|
||||
.cxx/
|
||||
|
||||
# Google Services (e.g. APIs or Firebase)
|
||||
# google-services.json
|
||||
|
||||
# Freeline
|
||||
freeline.py
|
||||
freeline/
|
||||
freeline_project_description.json
|
||||
|
||||
# fastlane
|
||||
fastlane/report.xml
|
||||
fastlane/Preview.html
|
||||
fastlane/screenshots
|
||||
fastlane/test_output
|
||||
fastlane/readme.md
|
||||
|
||||
# Version control
|
||||
vcs.xml
|
||||
|
||||
# lint
|
||||
lint/intermediates/
|
||||
lint/generated/
|
||||
lint/outputs/
|
||||
lint/tmp/
|
||||
# lint/reports/
|
||||
|
||||
# Android Profiling
|
||||
*.hprof
|
||||
|
||||
# Cordova plugins for Capacitor
|
||||
capacitor-cordova-android-plugins
|
||||
|
||||
# Copied web assets
|
||||
app/src/main/assets/public
|
||||
|
||||
# Generated Config files
|
||||
app/src/main/assets/capacitor.config.json
|
||||
app/src/main/assets/capacitor.plugins.json
|
||||
app/src/main/res/xml/config.xml
|
||||
@@ -0,0 +1,2 @@
|
||||
/build/*
|
||||
!/build/.npmkeep
|
||||
@@ -0,0 +1,54 @@
|
||||
apply plugin: 'com.android.application'
|
||||
|
||||
android {
|
||||
namespace "dev.eom.wikideck"
|
||||
compileSdk rootProject.ext.compileSdkVersion
|
||||
defaultConfig {
|
||||
applicationId "dev.eom.wikideck"
|
||||
minSdkVersion rootProject.ext.minSdkVersion
|
||||
targetSdkVersion rootProject.ext.targetSdkVersion
|
||||
versionCode 1
|
||||
versionName "1.0"
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
aaptOptions {
|
||||
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
|
||||
// Default: https://android.googlesource.com/platform/frameworks/base/+/282e181b58cf72b6ca770dc7ca5f91f135444502/tools/aapt/AaptAssets.cpp#61
|
||||
ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~'
|
||||
}
|
||||
}
|
||||
buildTypes {
|
||||
release {
|
||||
minifyEnabled false
|
||||
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
repositories {
|
||||
flatDir{
|
||||
dirs '../capacitor-cordova-android-plugins/src/main/libs', 'libs'
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation fileTree(include: ['*.jar'], dir: 'libs')
|
||||
implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
|
||||
implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion"
|
||||
implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion"
|
||||
implementation project(':capacitor-android')
|
||||
testImplementation "junit:junit:$junitVersion"
|
||||
androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
|
||||
androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"
|
||||
implementation project(':capacitor-cordova-android-plugins')
|
||||
}
|
||||
|
||||
apply from: 'capacitor.build.gradle'
|
||||
|
||||
try {
|
||||
def servicesJSON = file('google-services.json')
|
||||
if (servicesJSON.text) {
|
||||
apply plugin: 'com.google.gms.google-services'
|
||||
}
|
||||
} catch(Exception e) {
|
||||
logger.info("google-services.json not found, google-services plugin not applied. Push Notifications won't work")
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN
|
||||
|
||||
android {
|
||||
compileOptions {
|
||||
sourceCompatibility JavaVersion.VERSION_21
|
||||
targetCompatibility JavaVersion.VERSION_21
|
||||
}
|
||||
}
|
||||
|
||||
apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle"
|
||||
dependencies {
|
||||
implementation project(':capacitor-app')
|
||||
implementation project(':capacitor-browser')
|
||||
|
||||
}
|
||||
|
||||
|
||||
if (hasProperty('postBuildExtras')) {
|
||||
postBuildExtras()
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
# Add project specific ProGuard rules here.
|
||||
# You can control the set of applied configuration files using the
|
||||
# proguardFiles setting in build.gradle.
|
||||
#
|
||||
# For more details, see
|
||||
# http://developer.android.com/guide/developing/tools/proguard.html
|
||||
|
||||
# If your project uses WebView with JS, uncomment the following
|
||||
# and specify the fully qualified class name to the JavaScript interface
|
||||
# class:
|
||||
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
|
||||
# public *;
|
||||
#}
|
||||
|
||||
# Uncomment this to preserve the line number information for
|
||||
# debugging stack traces.
|
||||
#-keepattributes SourceFile,LineNumberTable
|
||||
|
||||
# If you keep the line number information, uncomment this to
|
||||
# hide the original source file name.
|
||||
#-renamesourcefileattribute SourceFile
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.getcapacitor.myapp;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import android.content.Context;
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4;
|
||||
import androidx.test.platform.app.InstrumentationRegistry;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
/**
|
||||
* Instrumented test, which will execute on an Android device.
|
||||
*
|
||||
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
|
||||
*/
|
||||
@RunWith(AndroidJUnit4.class)
|
||||
public class ExampleInstrumentedTest {
|
||||
|
||||
@Test
|
||||
public void useAppContext() throws Exception {
|
||||
// Context of the app under test.
|
||||
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
|
||||
|
||||
assertEquals("com.getcapacitor.app", appContext.getPackageName());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<application
|
||||
android:allowBackup="true"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
android:supportsRtl="true"
|
||||
android:usesCleartextTraffic="true"
|
||||
android:theme="@style/AppTheme">
|
||||
|
||||
<activity
|
||||
android:windowSoftInputMode="adjustResize"
|
||||
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode|navigation"
|
||||
android:name=".MainActivity"
|
||||
android:label="@string/title_activity_main"
|
||||
android:theme="@style/AppTheme.NoActionBarLaunch"
|
||||
android:launchMode="singleTask"
|
||||
android:exported="true">
|
||||
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
|
||||
<!-- SSO redirect (RFC 8252 private-use scheme, registered with Dex as dev.eom.wikideck:/oauth/callback) -->
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.VIEW" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<category android:name="android.intent.category.BROWSABLE" />
|
||||
<data android:scheme="dev.eom.wikideck" />
|
||||
</intent-filter>
|
||||
|
||||
</activity>
|
||||
|
||||
<provider
|
||||
android:name="androidx.core.content.FileProvider"
|
||||
android:authorities="${applicationId}.fileprovider"
|
||||
android:exported="false"
|
||||
android:grantUriPermissions="true">
|
||||
<meta-data
|
||||
android:name="android.support.FILE_PROVIDER_PATHS"
|
||||
android:resource="@xml/file_paths"></meta-data>
|
||||
</provider>
|
||||
</application>
|
||||
|
||||
<!-- Permissions -->
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
</manifest>
|
||||
@@ -0,0 +1,5 @@
|
||||
package dev.eom.wikideck;
|
||||
|
||||
import com.getcapacitor.BridgeActivity;
|
||||
|
||||
public class MainActivity extends BridgeActivity {}
|
||||
|
After Width: | Height: | Size: 7.5 KiB |
|
After Width: | Height: | Size: 3.9 KiB |
|
After Width: | Height: | Size: 9.0 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 7.7 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 9.6 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 17 KiB |
@@ -0,0 +1,34 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:aapt="http://schemas.android.com/aapt"
|
||||
android:width="108dp"
|
||||
android:height="108dp"
|
||||
android:viewportHeight="108"
|
||||
android:viewportWidth="108">
|
||||
<path
|
||||
android:fillType="evenOdd"
|
||||
android:pathData="M32,64C32,64 38.39,52.99 44.13,50.95C51.37,48.37 70.14,49.57 70.14,49.57L108.26,87.69L108,109.01L75.97,107.97L32,64Z"
|
||||
android:strokeColor="#00000000"
|
||||
android:strokeWidth="1">
|
||||
<aapt:attr name="android:fillColor">
|
||||
<gradient
|
||||
android:endX="78.5885"
|
||||
android:endY="90.9159"
|
||||
android:startX="48.7653"
|
||||
android:startY="61.0927"
|
||||
android:type="linear">
|
||||
<item
|
||||
android:color="#44000000"
|
||||
android:offset="0.0" />
|
||||
<item
|
||||
android:color="#00000000"
|
||||
android:offset="1.0" />
|
||||
</gradient>
|
||||
</aapt:attr>
|
||||
</path>
|
||||
<path
|
||||
android:fillColor="#FFFFFF"
|
||||
android:fillType="nonZero"
|
||||
android:pathData="M66.94,46.02L66.94,46.02C72.44,50.07 76,56.61 76,64L32,64C32,56.61 35.56,50.11 40.98,46.06L36.18,41.19C35.45,40.45 35.45,39.3 36.18,38.56C36.91,37.81 38.05,37.81 38.78,38.56L44.25,44.05C47.18,42.57 50.48,41.71 54,41.71C57.48,41.71 60.78,42.57 63.68,44.05L69.11,38.56C69.84,37.81 70.98,37.81 71.71,38.56C72.44,39.3 72.44,40.45 71.71,41.19L66.94,46.02ZM62.94,56.92C64.08,56.92 65,56.01 65,54.88C65,53.76 64.08,52.85 62.94,52.85C61.8,52.85 60.88,53.76 60.88,54.88C60.88,56.01 61.8,56.92 62.94,56.92ZM45.06,56.92C46.2,56.92 47.13,56.01 47.13,54.88C47.13,53.76 46.2,52.85 45.06,52.85C43.92,52.85 43,53.76 43,54.88C43,56.01 43.92,56.92 45.06,56.92Z"
|
||||
android:strokeColor="#00000000"
|
||||
android:strokeWidth="1" />
|
||||
</vector>
|
||||
@@ -0,0 +1,170 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="108dp"
|
||||
android:height="108dp"
|
||||
android:viewportHeight="108"
|
||||
android:viewportWidth="108">
|
||||
<path
|
||||
android:fillColor="#26A69A"
|
||||
android:pathData="M0,0h108v108h-108z" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M9,0L9,108"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,0L19,108"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M29,0L29,108"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M39,0L39,108"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M49,0L49,108"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M59,0L59,108"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M69,0L69,108"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M79,0L79,108"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M89,0L89,108"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M99,0L99,108"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,9L108,9"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,19L108,19"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,29L108,29"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,39L108,39"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,49L108,49"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,59L108,59"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,69L108,69"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,79L108,79"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,89L108,89"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,99L108,99"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,29L89,29"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,39L89,39"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,49L89,49"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,59L89,59"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,69L89,69"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,79L89,79"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M29,19L29,89"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M39,19L39,89"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M49,19L49,89"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M59,19L59,89"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M69,19L69,89"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M79,19L79,89"
|
||||
android:strokeColor="#33FFFFFF"
|
||||
android:strokeWidth="0.8" />
|
||||
</vector>
|
||||
|
After Width: | Height: | Size: 3.9 KiB |
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||
xmlns:tools="http://schemas.android.com/tools"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
tools:context=".MainActivity">
|
||||
|
||||
<WebView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent" />
|
||||
</androidx.coordinatorlayout.widget.CoordinatorLayout>
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@color/ic_launcher_background"/>
|
||||
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
|
||||
</adaptive-icon>
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@color/ic_launcher_background"/>
|
||||
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
|
||||
</adaptive-icon>
|
||||
|
After Width: | Height: | Size: 2.7 KiB |
|
After Width: | Height: | Size: 3.4 KiB |
|
After Width: | Height: | Size: 4.2 KiB |
|
After Width: | Height: | Size: 1.8 KiB |
|
After Width: | Height: | Size: 2.1 KiB |
|
After Width: | Height: | Size: 2.7 KiB |
|
After Width: | Height: | Size: 3.9 KiB |
|
After Width: | Height: | Size: 4.9 KiB |
|
After Width: | Height: | Size: 6.4 KiB |
|
After Width: | Height: | Size: 6.5 KiB |
|
After Width: | Height: | Size: 9.6 KiB |
|
After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 9.2 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 16 KiB |
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<color name="colorPrimary">#1e1e2e</color>
|
||||
<color name="colorPrimaryDark">#11111b</color>
|
||||
<color name="colorAccent">#cba6f7</color>
|
||||
<!-- Behind the status and navigation bars: matches the dark app header. -->
|
||||
<color name="wikideckChrome">#11111b</color>
|
||||
</resources>
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<color name="ic_launcher_background">#FFFFFF</color>
|
||||
</resources>
|
||||
@@ -0,0 +1,7 @@
|
||||
<?xml version='1.0' encoding='utf-8'?>
|
||||
<resources>
|
||||
<string name="app_name">WikiDeck</string>
|
||||
<string name="title_activity_main">WikiDeck</string>
|
||||
<string name="package_name">dev.eom.wikideck</string>
|
||||
<string name="custom_url_scheme">dev.eom.wikideck</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,25 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
|
||||
<!-- Base application theme. -->
|
||||
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
|
||||
<!-- Customize your theme here. -->
|
||||
<item name="colorPrimary">@color/colorPrimary</item>
|
||||
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
|
||||
<item name="colorAccent">@color/colorAccent</item>
|
||||
</style>
|
||||
|
||||
<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.DayNight.NoActionBar">
|
||||
<item name="windowActionBar">false</item>
|
||||
<item name="windowNoTitle">true</item>
|
||||
<item name="android:background">@null</item>
|
||||
<!-- Dark behind the status/navigation bars (edge-to-edge margins) to match the app chrome. -->
|
||||
<item name="android:windowBackground">@color/wikideckChrome</item>
|
||||
<item name="android:windowLightStatusBar">false</item>
|
||||
</style>
|
||||
|
||||
|
||||
<style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen">
|
||||
<item name="android:background">@drawable/splash</item>
|
||||
</style>
|
||||
</resources>
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<paths xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<external-path name="my_images" path="." />
|
||||
<cache-path name="my_cache_images" path="." />
|
||||
</paths>
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.getcapacitor.myapp;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* Example local unit test, which will execute on the development machine (host).
|
||||
*
|
||||
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
|
||||
*/
|
||||
public class ExampleUnitTest {
|
||||
|
||||
@Test
|
||||
public void addition_isCorrect() throws Exception {
|
||||
assertEquals(4, 2 + 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
#!/bin/sh
|
||||
# Build the WikiDeck debug APK against the private Night-1 testnet.
|
||||
# Needs ANDROID_HOME and a JDK 21 (JAVA_HOME). Output: android/app/build/outputs/apk/debug/app-debug.apk
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
export VITE_WIKIDECK_NETWORK="${VITE_WIKIDECK_NETWORK:-testnet}"
|
||||
export VITE_WIKIDECK_GENESIS_TIME="${VITE_WIKIDECK_GENESIS_TIME:-1792411200}"
|
||||
export VITE_NODE_URL="${VITE_NODE_URL:-http://192.168.1.32:3101}"
|
||||
npm run build
|
||||
npx cap sync android
|
||||
cd android && ./gradlew --no-daemon -q assembleDebug
|
||||
ls -l app/build/outputs/apk/debug/app-debug.apk
|
||||
@@ -0,0 +1,29 @@
|
||||
// Top-level build file where you can add configuration options common to all sub-projects/modules.
|
||||
|
||||
buildscript {
|
||||
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
dependencies {
|
||||
classpath 'com.android.tools.build:gradle:8.7.2'
|
||||
classpath 'com.google.gms:google-services:4.4.2'
|
||||
|
||||
// NOTE: Do not place your application dependencies here; they belong
|
||||
// in the individual module build.gradle files
|
||||
}
|
||||
}
|
||||
|
||||
apply from: "variables.gradle"
|
||||
|
||||
allprojects {
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
}
|
||||
|
||||
task clean(type: Delete) {
|
||||
delete rootProject.buildDir
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN
|
||||
include ':capacitor-android'
|
||||
project(':capacitor-android').projectDir = new File('../node_modules/@capacitor/android/capacitor')
|
||||
|
||||
include ':capacitor-app'
|
||||
project(':capacitor-app').projectDir = new File('../node_modules/@capacitor/app/android')
|
||||
|
||||
include ':capacitor-browser'
|
||||
project(':capacitor-browser').projectDir = new File('../node_modules/@capacitor/browser/android')
|
||||
@@ -0,0 +1,22 @@
|
||||
# Project-wide Gradle settings.
|
||||
|
||||
# IDE (e.g. Android Studio) users:
|
||||
# Gradle settings configured through the IDE *will override*
|
||||
# any settings specified in this file.
|
||||
|
||||
# For more details on how to configure your build environment visit
|
||||
# http://www.gradle.org/docs/current/userguide/build_environment.html
|
||||
|
||||
# Specifies the JVM arguments used for the daemon process.
|
||||
# The setting is particularly useful for tweaking memory settings.
|
||||
org.gradle.jvmargs=-Xmx1536m
|
||||
|
||||
# When configured, Gradle will run in incubating parallel mode.
|
||||
# This option should only be used with decoupled projects. More details, visit
|
||||
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
|
||||
# org.gradle.parallel=true
|
||||
|
||||
# AndroidX package structure to make it clearer which packages are bundled with the
|
||||
# Android operating system, and which are packaged with your app's APK
|
||||
# https://developer.android.com/topic/libraries/support-library/androidx-rn
|
||||
android.useAndroidX=true
|
||||
@@ -0,0 +1,7 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-all.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
@@ -0,0 +1,252 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
|
||||
' "$PWD" ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
if ! command -v java >/dev/null 2>&1
|
||||
then
|
||||
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
@@ -0,0 +1,94 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
@rem SPDX-License-Identifier: Apache-2.0
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
@rem This is normally unused
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
set EXIT_CODE=%ERRORLEVEL%
|
||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||
exit /b %EXIT_CODE%
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
@@ -0,0 +1,5 @@
|
||||
include ':app'
|
||||
include ':capacitor-cordova-android-plugins'
|
||||
project(':capacitor-cordova-android-plugins').projectDir = new File('./capacitor-cordova-android-plugins/')
|
||||
|
||||
apply from: 'capacitor.settings.gradle'
|
||||
@@ -0,0 +1,16 @@
|
||||
ext {
|
||||
minSdkVersion = 23
|
||||
compileSdkVersion = 35
|
||||
targetSdkVersion = 35
|
||||
androidxActivityVersion = '1.9.2'
|
||||
androidxAppCompatVersion = '1.7.0'
|
||||
androidxCoordinatorLayoutVersion = '1.2.0'
|
||||
androidxCoreVersion = '1.15.0'
|
||||
androidxFragmentVersion = '1.8.4'
|
||||
coreSplashScreenVersion = '1.0.1'
|
||||
androidxWebkitVersion = '1.12.1'
|
||||
junitVersion = '4.13.2'
|
||||
androidxJunitVersion = '1.2.1'
|
||||
androidxEspressoCoreVersion = '3.6.1'
|
||||
cordovaAndroidVersion = '10.1.1'
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { CapacitorConfig } from '@capacitor/cli';
|
||||
|
||||
// WikiDeck mobile shell. Build the web UI with the node URL baked in, then sync:
|
||||
// VITE_WIKIDECK_NETWORK=testnet VITE_WIKIDECK_GENESIS_TIME=1792411200 \
|
||||
// VITE_NODE_URL=http://192.168.1.32:3101 npm run build && npx cap sync android
|
||||
// (see android/build-debug.sh)
|
||||
const config: CapacitorConfig = {
|
||||
appId: 'dev.eom.wikideck',
|
||||
appName: 'WikiDeck',
|
||||
webDir: 'dist',
|
||||
server: {
|
||||
androidScheme: 'https',
|
||||
// The private testnet node is plain HTTP on the LAN.
|
||||
cleartext: true,
|
||||
},
|
||||
android: {
|
||||
// Android 15 (targetSdk 35) draws edge-to-edge; keep the WebView clear of the system bars.
|
||||
adjustMarginsForEdgeToEdge: 'auto',
|
||||
},
|
||||
plugins: {
|
||||
// Route fetch through native HTTP: avoids CORS and the node's browser Origin check.
|
||||
CapacitorHttp: { enabled: true },
|
||||
},
|
||||
};
|
||||
|
||||
export default config;
|
||||
@@ -1,295 +0,0 @@
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import requests
|
||||
from typing import Optional
|
||||
from cryptography.hazmat.primitives.asymmetric import rsa
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
|
||||
|
||||
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "wikideck")));
|
||||
|
||||
from Mine.Block import Block
|
||||
from Mine.Transaction import Transaction
|
||||
|
||||
WIKIDECK_URL = os.getenv('WIKIDECK_URL', 'http://localhost:8080/');
|
||||
|
||||
|
||||
rsa_private_key: Optional[rsa.RSAPrivateKey] = None;
|
||||
msg_array: list[str] = [""];
|
||||
private_key_file: str = "privatekey.pem";
|
||||
public_key_file: str = "publickey.pem";
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
while True:
|
||||
|
||||
if (msg_array[0]):
|
||||
print(f"Last Action: {msg_array[0]}");
|
||||
|
||||
print("\n--- Wikideck CLI ---");
|
||||
print("1. Create RSA Keypair");
|
||||
print("2. Save Private Key");
|
||||
print("3. Load RSA Keypair");
|
||||
print("4. Save Public Key")
|
||||
print("5. Mine a Block");
|
||||
print("6. Generate a Transaction");
|
||||
print("7. View Deck");
|
||||
print("0. Exit");
|
||||
print("\n-------------------");
|
||||
|
||||
try:
|
||||
choice: int = int(input("Select an option: ").strip());
|
||||
except ValueError:
|
||||
msg_array[0] = "Invalid Input. Please Choose a Number Between 0-6.";
|
||||
clear_console();
|
||||
continue;
|
||||
|
||||
|
||||
if choice == 0:
|
||||
break;
|
||||
elif choice == 1:
|
||||
opt_generate_keypair(65537, 2048);
|
||||
elif choice == 2:
|
||||
opt_save_private_key(rsa_private_key);
|
||||
elif choice == 3:
|
||||
opt_load_private_key();
|
||||
elif choice == 4:
|
||||
opt_save_public_key(rsa_private_key);
|
||||
elif choice == 5:
|
||||
opt_mine_block();
|
||||
elif choice == 6:
|
||||
opt_generate_transaction();
|
||||
elif choice == 7:
|
||||
opt_view_deck();
|
||||
else:
|
||||
msg_array[0] = "Invalid Input. Please Choose a Number Between 0-6.";
|
||||
|
||||
clear_console();
|
||||
|
||||
def opt_generate_keypair(exponent=65537, size=2048):
|
||||
global rsa_private_key;
|
||||
rsa_private_key = rsa.generate_private_key(
|
||||
public_exponent = exponent,
|
||||
key_size = size,
|
||||
)
|
||||
msg_array[0] = "RSA Keypair Generated";
|
||||
return rsa_private_key;
|
||||
|
||||
def opt_save_private_key(rsa, filename=private_key_file):
|
||||
if rsa is None:
|
||||
msg_array[0] = "No RSA Keypair to extract private key. Please generate one first.";
|
||||
return None;
|
||||
else:
|
||||
with open(filename, "wb") as file:
|
||||
pem = rsa.private_bytes(
|
||||
encoding=serialization.Encoding.PEM,
|
||||
format=serialization.PrivateFormat.TraditionalOpenSSL,
|
||||
encryption_algorithm=serialization.NoEncryption()
|
||||
)
|
||||
file.write(pem);
|
||||
msg_array[0] = f"RSA Private Key Saved to {filename}";
|
||||
|
||||
def opt_save_public_key(rsa, filename=public_key_file):
|
||||
if rsa is None:
|
||||
msg_array[0] = "No RSA Keypair to extract public key. Please generate one first.";
|
||||
return None;
|
||||
|
||||
public_key = rsa.public_key();
|
||||
|
||||
public_pem = public_key.public_bytes(
|
||||
encoding=serialization.Encoding.PEM,
|
||||
format=serialization.PublicFormat.SubjectPublicKeyInfo
|
||||
)
|
||||
|
||||
with open(filename, "wb") as file:
|
||||
file.write(public_pem);
|
||||
msg_array[0] = f"RSA Public Key Saved to {filename}";
|
||||
|
||||
def opt_load_private_key():
|
||||
global rsa_private_key;
|
||||
if not os.path.exists(private_key_file):
|
||||
msg_array[0] = f"No saved key found ({private_key_file} missing)";
|
||||
return None;
|
||||
|
||||
with open(private_key_file, "rb") as file:
|
||||
rsa_private_key = serialization.load_pem_private_key(
|
||||
file.read(),
|
||||
password=None,
|
||||
)
|
||||
msg_array[0] = f"RSA Private Key Loaded From {private_key_file}";
|
||||
|
||||
def get_private_key_from_file(path):
|
||||
if not os.path.exists(path):
|
||||
msg_array[0] = f"No key file found ({path} missing)";
|
||||
return None;
|
||||
|
||||
with open(path, "rb") as file:
|
||||
key = serialization.load_pem_private_key(
|
||||
file.read(),
|
||||
password=None,
|
||||
);
|
||||
msg_array[0] = f"RSA Private Key Gotten From {path}"; #inaccessible
|
||||
|
||||
return key;
|
||||
|
||||
def opt_mine_block(path = None):
|
||||
|
||||
global rsa_private_key;
|
||||
|
||||
if (path):
|
||||
rsa_private_key = get_private_key_from_file(path);
|
||||
if not (rsa_private_key):
|
||||
return None;
|
||||
|
||||
if rsa_private_key is None:
|
||||
msg_array[0] = "You must load or generate an RSA keypair first.";
|
||||
return;
|
||||
|
||||
try:
|
||||
response = requests.get(f"{WIKIDECK_URL}/blocks");
|
||||
if response.status_code != 200:
|
||||
msg_array[0] = f"Failed to fetch block to mine: {response.status_code}";
|
||||
return;
|
||||
|
||||
block_to_mine = Block(data = response.json());
|
||||
block_to_mine.mine(rsa_private_key);
|
||||
|
||||
response = requests.post(f"{WIKIDECK_URL}/blocks", json=block_to_mine.as_dict());
|
||||
if response.status_code == 200:
|
||||
msg_array[0] = "Block successfully mined and submitted";
|
||||
else:
|
||||
msg_array[0] = f"Failed to submit mined block: {response.status_code}";
|
||||
|
||||
except Exception as e:
|
||||
msg_array[0] = f"Error during mining: {str(e)}";
|
||||
|
||||
def opt_generate_transaction(path = None, recv = None):
|
||||
global rsa_private_key;
|
||||
|
||||
if (path):
|
||||
rsa_private_key = get_private_key_from_file(path);
|
||||
if not (rsa_private_key):
|
||||
return None;
|
||||
|
||||
|
||||
if rsa_private_key is None:
|
||||
msg_array[0] = "You must load or generate an RSA keypair first.";
|
||||
return;
|
||||
|
||||
if not (recv):
|
||||
print("\nPaste the recipient's RSA Public Key (PEM format). End with an Empty Line (Press enter twice): ");
|
||||
lines = [];
|
||||
while True:
|
||||
line = input();
|
||||
if not line.strip():
|
||||
break;
|
||||
lines.append(line);
|
||||
|
||||
receiver_pem = "\n".join(lines);
|
||||
|
||||
try:
|
||||
receiver_key = serialization.load_pem_public_key(receiver_pem.encode("utf-8"));
|
||||
except Exception:
|
||||
msg_array[0] = "Invalid public key format";
|
||||
return;
|
||||
|
||||
else:
|
||||
if not os.path.isfile(recv):
|
||||
msg_array[0] = f"Reciever public key file not found {recv}";
|
||||
return None;
|
||||
with open(recv, "rb") as recv_file:
|
||||
receiver_key = serialization.load_pem_public_key(recv_file.read());
|
||||
|
||||
|
||||
|
||||
|
||||
try:
|
||||
|
||||
cards = fetch_cards_json(rsa_private_key);
|
||||
|
||||
if not cards:
|
||||
msg_array[0] = "You have no cards to send";
|
||||
return;
|
||||
|
||||
print("\nYour cards:");
|
||||
|
||||
for i, card in enumerate(cards):
|
||||
print(f"{i+1}. Card ID: {card['cardId']}, Page ID: {card['pageId']}");
|
||||
|
||||
|
||||
try:
|
||||
index: int = int(input("Select a card number to send: ").strip()) - 1;
|
||||
|
||||
if not (0 <= index < len(cards)):
|
||||
raise ValueError;
|
||||
except ValueError:
|
||||
msg_array[0] = "Invalid card selection";
|
||||
return;
|
||||
|
||||
selected_card = cards[index];
|
||||
|
||||
tx = Transaction(
|
||||
cardId = selected_card['cardId'],
|
||||
sender = rsa_private_key.public_key(),
|
||||
receiver=receiver_key,
|
||||
authorPrivateKey=rsa_private_key
|
||||
);
|
||||
|
||||
response = requests.post(f"{WIKIDECK_URL}/transactions", json=tx.as_dict());
|
||||
|
||||
if response.status_code != 200:
|
||||
msg_array[0] = f"Transaction failed: {response.status_code}";
|
||||
else:
|
||||
msg_array[0] = "Transaction submitted successfully";
|
||||
|
||||
except Exception as e:
|
||||
msg_array[0] = f"Error creating transaction: {str(e)}";
|
||||
|
||||
|
||||
def opt_view_deck():
|
||||
|
||||
global rsa_private_key;
|
||||
if rsa_private_key is None:
|
||||
msg_array[0] = "You must load or generate an RSA keypair first.";
|
||||
return;
|
||||
|
||||
try:
|
||||
cards = fetch_cards_json(rsa_private_key);
|
||||
|
||||
|
||||
if len(cards) <= 0:
|
||||
msg_array[0] = "You have no cards to view";
|
||||
return;
|
||||
|
||||
msg = "Successfully listed deck.\n"
|
||||
for card in cards:
|
||||
msg += f"Card ID: {card['cardId']}, Page ID: {card['pageId']}\n"
|
||||
msg_array[0] = msg
|
||||
|
||||
except Exception as e:
|
||||
msg_array[0] = f"Error fetching cards: {str(e)}";
|
||||
|
||||
|
||||
def fetch_cards_json(rsa):
|
||||
pem = rsa.public_key().public_bytes(
|
||||
encoding=serialization.Encoding.PEM,
|
||||
format=serialization.PublicFormat.SubjectPublicKeyInfo
|
||||
).decode("utf-8");
|
||||
|
||||
response = requests.get(f"{WIKIDECK_URL}/cards", params={"publicKey": pem});
|
||||
|
||||
if response.status_code != 200:
|
||||
msg_array[0] = f"Failed to fetch cards: {response.status_code}";
|
||||
return;
|
||||
|
||||
cards = response.json();
|
||||
return cards;
|
||||
|
||||
|
||||
def clear_console():
|
||||
os.system('cls' if os.name == 'nt' else 'clear');
|
||||
|
||||
if __name__ == "__main__":
|
||||
main();
|
||||
@@ -1,3 +0,0 @@
|
||||
cryptography
|
||||
dotenv
|
||||
wikipedia
|
||||
@@ -0,0 +1,39 @@
|
||||
# Gated candidate profile, NOT an announcement of a production-ready or launched network.
|
||||
# Review docs/mainnet-launch.md before attempting activation.
|
||||
services:
|
||||
mainnet:
|
||||
build:
|
||||
context: .
|
||||
target: runtime
|
||||
args:
|
||||
WIKIDECK_NETWORK: mainnet
|
||||
WIKIDECK_GENESIS_TIME: "${WIKIDECK_GENESIS_TIME:-1793491200}"
|
||||
ports:
|
||||
- "127.0.0.1:${WIKIDECK_MAINNET_PORT:-3201}:3001"
|
||||
environment:
|
||||
WIKIDECK_NETWORK: mainnet
|
||||
WIKIDECK_GENESIS_TIME: "${WIKIDECK_GENESIS_TIME:-1793491200}"
|
||||
PUBLIC_ORIGIN: "${WIKIDECK_MAINNET_ORIGIN:-}"
|
||||
WIKIDECK_PEERS: "${WIKIDECK_MAINNET_PEERS:-}"
|
||||
WIKIDECK_MAINNET_LAUNCH: "${WIKIDECK_MAINNET_LAUNCH:-}"
|
||||
WIKIDECK_MAINNET_RISK_ACK: "${WIKIDECK_MAINNET_RISK_ACK:-}"
|
||||
WIKIDECK_ALLOW_PRIVATE_PEERS: "0"
|
||||
# Empty by default; set only the actual edge-to-container source IP/CIDR after topology review.
|
||||
WIKIDECK_TRUSTED_PROXIES: "${WIKIDECK_TRUSTED_PROXIES:-}"
|
||||
# Diagnostics are deliberately disabled here. Never publish an operations port.
|
||||
volumes:
|
||||
- mainnet-candidate-data:/app/data
|
||||
init: true
|
||||
restart: "no"
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp:size=32m,mode=1777,noexec,nosuid
|
||||
cap_drop: [ALL]
|
||||
security_opt: [no-new-privileges:true]
|
||||
pids_limit: 128
|
||||
mem_limit: 1g
|
||||
cpus: 1.0
|
||||
stop_grace_period: 30s
|
||||
|
||||
volumes:
|
||||
mainnet-candidate-data:
|
||||
@@ -0,0 +1,74 @@
|
||||
# Three independent validators, separate volumes, no miner auto-starts.
|
||||
x-node-environment: &node-environment
|
||||
WIKIDECK_NETWORK: testnet
|
||||
services:
|
||||
node-a:
|
||||
image: wikideck:testnet
|
||||
build:
|
||||
context: .
|
||||
target: runtime
|
||||
args: { WIKIDECK_NETWORK: testnet, WIKIDECK_GENESIS_TIME: "1792411200" }
|
||||
ports: ["127.0.0.1:3101:3001"]
|
||||
environment:
|
||||
<<: *node-environment
|
||||
PUBLIC_ORIGIN: http://127.0.0.1:3101
|
||||
WIKIDECK_PEERS: http://node-b:3001,http://node-c:3001
|
||||
WIKIDECK_ALLOW_PRIVATE_PEERS: "1"
|
||||
volumes: ["testnet-a:/app/data"]
|
||||
init: true
|
||||
read_only: true
|
||||
tmpfs: ["/tmp:size=32m,mode=1777,noexec,nosuid"]
|
||||
cap_drop: [ALL]
|
||||
security_opt: ["no-new-privileges:true"]
|
||||
pids_limit: 128
|
||||
mem_limit: 1g
|
||||
cpus: 1.0
|
||||
stop_grace_period: 30s
|
||||
node-b:
|
||||
image: wikideck:testnet
|
||||
build:
|
||||
context: .
|
||||
target: runtime
|
||||
args: { WIKIDECK_NETWORK: testnet, WIKIDECK_GENESIS_TIME: "1792411200" }
|
||||
ports: ["127.0.0.1:3102:3001"]
|
||||
environment:
|
||||
<<: *node-environment
|
||||
PUBLIC_ORIGIN: http://127.0.0.1:3102
|
||||
WIKIDECK_PEERS: http://node-a:3001,http://node-c:3001
|
||||
WIKIDECK_ALLOW_PRIVATE_PEERS: "1"
|
||||
volumes: ["testnet-b:/app/data"]
|
||||
init: true
|
||||
read_only: true
|
||||
tmpfs: ["/tmp:size=32m,mode=1777,noexec,nosuid"]
|
||||
cap_drop: [ALL]
|
||||
security_opt: ["no-new-privileges:true"]
|
||||
pids_limit: 128
|
||||
mem_limit: 1g
|
||||
cpus: 1.0
|
||||
stop_grace_period: 30s
|
||||
node-c:
|
||||
image: wikideck:testnet
|
||||
build:
|
||||
context: .
|
||||
target: runtime
|
||||
args: { WIKIDECK_NETWORK: testnet, WIKIDECK_GENESIS_TIME: "1792411200" }
|
||||
ports: ["127.0.0.1:3103:3001"]
|
||||
environment:
|
||||
<<: *node-environment
|
||||
PUBLIC_ORIGIN: http://127.0.0.1:3103
|
||||
WIKIDECK_PEERS: http://node-a:3001,http://node-b:3001
|
||||
WIKIDECK_ALLOW_PRIVATE_PEERS: "1"
|
||||
volumes: ["testnet-c:/app/data"]
|
||||
init: true
|
||||
read_only: true
|
||||
tmpfs: ["/tmp:size=32m,mode=1777,noexec,nosuid"]
|
||||
cap_drop: [ALL]
|
||||
security_opt: ["no-new-privileges:true"]
|
||||
pids_limit: 128
|
||||
mem_limit: 1g
|
||||
cpus: 1.0
|
||||
stop_grace_period: 30s
|
||||
volumes:
|
||||
testnet-a:
|
||||
testnet-b:
|
||||
testnet-c:
|
||||
@@ -0,0 +1,38 @@
|
||||
services:
|
||||
wikideck:
|
||||
build:
|
||||
context: .
|
||||
target: runtime
|
||||
args:
|
||||
WIKIDECK_NETWORK: mainnet
|
||||
WIKIDECK_GENESIS_TIME: "${WIKIDECK_GENESIS_TIME:-1793491200}"
|
||||
ports:
|
||||
# Loopback only; terminate reviewed HTTPS at the operator's edge.
|
||||
- "127.0.0.1:${WIKIDECK_MAINNET_PORT:-3201}:3001"
|
||||
environment:
|
||||
WIKIDECK_NETWORK: mainnet
|
||||
WIKIDECK_GENESIS_TIME: "${WIKIDECK_GENESIS_TIME:-1793491200}"
|
||||
PUBLIC_ORIGIN: "${WIKIDECK_MAINNET_ORIGIN:-}"
|
||||
WIKIDECK_PEERS: "${WIKIDECK_MAINNET_PEERS:-}"
|
||||
WIKIDECK_MAINNET_LAUNCH: "${WIKIDECK_MAINNET_LAUNCH:-}"
|
||||
WIKIDECK_MAINNET_RISK_ACK: "${WIKIDECK_MAINNET_RISK_ACK:-}"
|
||||
WIKIDECK_ALLOW_PRIVATE_PEERS: "0"
|
||||
WIKIDECK_TRUSTED_PROXIES: "${WIKIDECK_TRUSTED_PROXIES:-}"
|
||||
volumes:
|
||||
- wikideck-mainnet-data:/app/data
|
||||
init: true
|
||||
restart: "no"
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp:size=32m,mode=1777,noexec,nosuid
|
||||
cap_drop:
|
||||
- ALL
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
pids_limit: 128
|
||||
mem_limit: 1g
|
||||
cpus: 1.0
|
||||
stop_grace_period: 30s
|
||||
|
||||
volumes:
|
||||
wikideck-mainnet-data:
|
||||
@@ -0,0 +1,45 @@
|
||||
# Kubernetes mainnet preparation
|
||||
|
||||
This directory intentionally contains no apply-ready manifests yet. The code is mainnet-first and supports a genesis frozen into the browser bundle and runtime image, but the current launch gate requires deployment facts that were not supplied. Placeholder origins, approval IDs, TLS secrets, or storage settings would not produce a working or safe deployment.
|
||||
|
||||
## Required topology for this implementation
|
||||
|
||||
- Build and publish one immutable image with `WIKIDECK_NETWORK=mainnet` and one chosen `WIKIDECK_GENESIS_TIME`. Give every peer and browser bundle that same chain identity. A runtime-only genesis override is rejected by the image manifest check.
|
||||
- Give each node a stable, unique public HTTPS origin. TLS must terminate at an operator-managed ingress/reverse proxy; the application listener itself is HTTP on port 3001.
|
||||
- Configure at least two other distinct public HTTPS peer origins per node for public peering. Private IPs/DNS and HTTP are rejected by default. An operator-controlled private candidate cluster may explicitly set `WIKIDECK_ALLOW_PRIVATE_PEERS=1` and use distinct per-node ClusterIP DNS origins. This opt-in does not change the exact chain-ID/risk/genesis gates or the HTTPS browser-origin requirement.
|
||||
- Route each public peer hostname deterministically to exactly one node. A shared load-balanced hostname is not a stable peer identity. Separate per-peer Deployments/Services/Ingress routes are the simplest current shape; each node must exclude its own origin from its peer list.
|
||||
- Give every node an exclusive persistent volume mounted at `/app/data`. Never share a ledger volume between pods. Agree the storage class, capacity, backup/restore procedure, resource limits, failure domains, and upgrade/reorg policy before enabling the launch approval.
|
||||
- Configure the exact manifest `CHAIN_ID` as `WIKIDECK_MAINNET_LAUNCH`, and explicitly set `WIKIDECK_MAINNET_RISK_ACK=operator-accepts-unaudited-risk`. The latter accepts unaudited residual risk; it is not an audit or readiness check.
|
||||
|
||||
## Pod hardening baseline
|
||||
|
||||
Use a dedicated namespace and least-privilege service account (or disable token automount if no Kubernetes API access is needed), non-root execution matching the image's `node` user, read-only root filesystem, dropped Linux capabilities, `allowPrivilegeEscalation: false`, `seccompProfile: RuntimeDefault`, and a bounded writable `/tmp` volume. Use resource requests and limits based on measured RandomX/replay/sync behavior, not guesses. Readiness/liveness should use `/healthz`; allow a startup grace period for ledger replay and native engine initialization. Restrict ingress to the reviewed edge and egress to DNS, the configured public peers, and required Wikimedia endpoints. Add NetworkPolicy, TLS, image provenance/signature enforcement, monitoring, and tested encrypted backups through the cluster's established platform controls.
|
||||
|
||||
Do not make the public origin or configured peers imply that peers are independent or that the network is secure. This software has no external audit, public bootstrap service, peer discovery, or demonstrated production capacity.
|
||||
|
||||
## Private candidate cluster
|
||||
|
||||
Deploy the public node and two internal peers as three separate single-replica
|
||||
role instances, each with its own Service and PVC. Configure each peer list with
|
||||
the other two Services, for example `http://wikideck-peer-a.wikideck.svc.cluster.local:80`.
|
||||
Allow same-namespace validator pods on target TCP 3001 through both ingress and
|
||||
egress NetworkPolicy; Service port 80 is translated to that target port. Only the
|
||||
public node needs ingress; all nodes may use the public node's HTTPS browser
|
||||
origin. Keep API credentials and wallet keys out of validator pods.
|
||||
|
||||
Read `--network-manifest` from the exact published image to obtain the candidate
|
||||
chain ID without opening storage or starting a listener. Its
|
||||
`privatePeersSupported: true` capability distinguishes updated images from older
|
||||
images that reject this topology. Do not override genesis at runtime. The default
|
||||
image genesis is now fixed at November 1, 2026, 00:00 UTC (`1793491200`), so no
|
||||
January wait or custom build argument is needed. Rebuild and publish the updated
|
||||
image; an older published image still contains its previous genesis. Existing
|
||||
ledgers and wallets must retain their original chain identity.
|
||||
|
||||
Private peer RPC is unauthenticated and, with HTTP, unencrypted. Use a trusted
|
||||
cluster boundary and scoped policies; add mesh transport protection if needed.
|
||||
This topology does not demonstrate independent peers/miners or production readiness.
|
||||
|
||||
## Values needed before manifests can be finalized
|
||||
|
||||
Choose the genesis timestamp and image registry/digest; provide the namespace, ingress class and TLS/certificate mechanism, public DNS name per node, peer topology, storage class/size, resource budget, network-policy egress model, backup destination/retention, and desired availability/recovery behavior. Then calculate and publish the exact manifest and chain approval. Until those values and the peer topology are available, this checklist is the safe preparation artifact rather than a misleading runnable YAML template.
|
||||
@@ -0,0 +1,41 @@
|
||||
# Example for nginx on the SAME host as loopback-bound node :3201.
|
||||
# Not installed by this repository. Replace host/cert paths and validate real topology.
|
||||
# Node: WIKIDECK_TRUSTED_PROXIES=127.0.0.1,::1 (never use this for a container bridge without adjustment).
|
||||
limit_req_zone $binary_remote_addr zone=wikideck_ip:10m rate=5r/s;
|
||||
limit_conn_zone $binary_remote_addr zone=wikideck_conn:10m;
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name wikideck.example.invalid;
|
||||
return 308 https://$host$request_uri;
|
||||
}
|
||||
server {
|
||||
listen 443 ssl;
|
||||
server_name wikideck.example.invalid;
|
||||
ssl_certificate /etc/ssl/wikideck/fullchain.pem;
|
||||
ssl_certificate_key /etc/ssl/wikideck/private.key;
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
server_tokens off;
|
||||
client_max_body_size 68k;
|
||||
client_body_timeout 15s;
|
||||
client_header_timeout 10s;
|
||||
keepalive_timeout 10s;
|
||||
send_timeout 30s;
|
||||
limit_conn wikideck_conn 16;
|
||||
limit_req_status 429;
|
||||
# Do not proxy private operations listener. Its port must never be publicly published.
|
||||
location / {
|
||||
limit_req zone=wikideck_ip burst=20 nodelay;
|
||||
proxy_pass http://127.0.0.1:3201;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
# Overwrite, do NOT append an untrusted client-supplied X-Forwarded-For chain.
|
||||
proxy_set_header X-Forwarded-For $remote_addr;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Forwarded "";
|
||||
proxy_set_header Connection "";
|
||||
proxy_connect_timeout 5s;
|
||||
proxy_send_timeout 15s;
|
||||
proxy_read_timeout 30s;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
# Night 1 private testnet (sim-testnet)
|
||||
|
||||
A 3-node **testnet-only** fixture on poweredge-r350. It is reachable on the LAN only, and uses the Docker project `wikideck-night`.
|
||||
|
||||
| node | URL |
|
||||
|---|---|
|
||||
| node-a | http://192.168.1.32:3101 |
|
||||
| node-b | http://192.168.1.32:3102 |
|
||||
| node-c | http://192.168.1.32:3103 |
|
||||
|
||||
- `compose.lan.yaml` overrides only the published ports (bound to `192.168.1.32`, never `0.0.0.0`) and `PUBLIC_ORIGIN`. It changes nothing in consensus or the image.
|
||||
- `mine.ts` is a multi-worker native RandomX miner. It runs inside the `wikideck:testnet` image, which ships the native engine, so the host needs no cmake.
|
||||
- It mines to 4 disposable wallets (alice, bob, carol, dave) and writes chain-bound encrypted browser backups to `$STATE_DIR/wallets/`.
|
||||
- It never changes consensus code. Speed comes from the protocol's own testnet parameters: the initial target accepts 1/16 of hashes, and each 10-block retarget at most quadruples the difficulty.
|
||||
- Each template costs several Wikipedia API calls, and Wikipedia rate-limits our egress IP. The miner therefore paces templates (`MIN_GAP`, default 45 s) and backs off exponentially on failure.
|
||||
- `compose.lan.yaml` also sets, per node:
|
||||
- `WIKIDECK_USER_AGENT`, a Wikimedia-policy UA with a project URL (#19). Without it, Wikipedia returned 429 to our egress and templates failed.
|
||||
- the game-mode env from #22: A = classic and trending, B = draft, C = all three.
|
||||
- `autodeploy.sh` follows the integration branch. Run it from a dedicated detached worktree: `git worktree add --detach ../deploy-src origin/night/2026-11-16 && cd ../deploy-src && deploy/night/autodeploy.sh`. It polls the Gitea API every 3 min and redeploys whenever the head moves.
|
||||
- `testnet.sh` has `up`, `mine N [workers]`, `status` and `down`. Run it from the repo root on a checkout of the integration branch. `up` rebuilds the image from that checkout; the ledgers persist in the named volumes.
|
||||
|
||||
Never point this at mainnet or the live `wikideck` namespace.
|
||||
@@ -0,0 +1,40 @@
|
||||
#!/bin/sh
|
||||
# sim-testnet: keep the wikideck-night testnet on the integration branch head.
|
||||
# Run from the root of a *dedicated* checkout (e.g. a detached git worktree): it checks out
|
||||
# each new head of $BRANCH and runs `deploy/night/testnet.sh rolling` (ledgers persist in the volumes):
|
||||
# nodes restart one at a time, and deploys wait (up to FORCE_AFTER) while matches or lobbies are live,
|
||||
# because lobbies are in memory and a restart ends games in progress.
|
||||
# Head detection uses the public Gitea API, which also works where SSH auth isn't available.
|
||||
set -u
|
||||
BRANCH=${BRANCH:-night/2026-11-16}
|
||||
API=${API:-https://gitea.eom.dev/api/v1/repos/claude/wikideck}
|
||||
INTERVAL=${INTERVAL:-180}
|
||||
LOG=${LOG:-/tmp/wikideck-night-autodeploy.log}
|
||||
FORCE_AFTER=${FORCE_AFTER:-900} # defer while matches/lobbies are live, but at most this many seconds
|
||||
deferred_since=
|
||||
enc=$(printf %s "$BRANCH" | sed 's#/#%2F#g')
|
||||
while :; do
|
||||
new=$(node -e "fetch('$API/branches/$enc',{signal:AbortSignal.timeout(15000)}).then(r=>r.json()).then(b=>console.log(b.commit.id)).catch(()=>{})")
|
||||
cur=$(git rev-parse HEAD)
|
||||
if [ -z "$new" ]; then echo "WARN branch API failed"
|
||||
elif [ "$new" != "$cur" ]; then
|
||||
if ! git fetch -q origin "+refs/heads/$BRANCH:refs/remotes/origin/$BRANCH" 2>"$LOG"; then
|
||||
echo "WARN fetch failed: $(tail -1 "$LOG")"
|
||||
else
|
||||
busy=$(deploy/night/testnet.sh busy 2>/dev/null || echo 0)
|
||||
now=$(date +%s)
|
||||
if [ "${busy:-0}" -gt 0 ] && { [ -z "$deferred_since" ] || [ $((now - deferred_since)) -lt "$FORCE_AFTER" ]; }; then
|
||||
[ -z "$deferred_since" ] && { deferred_since=$now; echo "DEFER ${new%"${new#???????}"}: $busy live matches/lobbies"; }
|
||||
sleep 60; continue
|
||||
fi
|
||||
[ -n "$deferred_since" ] && [ "${busy:-0}" -gt 0 ] && echo "FORCE deploy after ${FORCE_AFTER}s ($busy still live)"
|
||||
deferred_since=
|
||||
git checkout -q --detach "$new"
|
||||
echo "DEPLOY start $(git log --oneline -1 | cut -c1-90)"
|
||||
if deploy/night/testnet.sh rolling >"$LOG" 2>&1; then
|
||||
sleep 20; echo "DEPLOY ok $(git rev-parse --short HEAD): $(deploy/night/testnet.sh status 2>&1 | tr '\n' ' ')"
|
||||
else echo "DEPLOY FAILED $(git rev-parse --short HEAD): $(tail -3 "$LOG" | tr '\n' ' ')"; fi
|
||||
fi
|
||||
fi
|
||||
sleep "$INTERVAL"
|
||||
done
|
||||
@@ -0,0 +1,28 @@
|
||||
# sim-testnet override: publish the fixture on r350's LAN address only (not 0.0.0.0).
|
||||
# WIKIDECK_USER_AGENT identifies the testnet to Wikimedia (UA policy; no personal contact info).
|
||||
# Game-mode env (modes team, #6) is inert until night/modes/hosting merges.
|
||||
services:
|
||||
node-a:
|
||||
ports: !override ["192.168.1.32:3101:3001"]
|
||||
environment:
|
||||
PUBLIC_ORIGIN: http://192.168.1.32:3101
|
||||
WIKIDECK_USER_AGENT: &ua WikiDeck-testnet/0.1 (https://gitea.eom.dev/claude/wikideck; private testnet)
|
||||
WIKIDECK_MODES: classic,trending
|
||||
WIKIDECK_GAME_OPERATOR: Testnet A
|
||||
WIKIDECK_GAME_PEERS: http://192.168.1.32:3102,http://192.168.1.32:3103
|
||||
node-b:
|
||||
ports: !override ["192.168.1.32:3102:3001"]
|
||||
environment:
|
||||
PUBLIC_ORIGIN: http://192.168.1.32:3102
|
||||
WIKIDECK_USER_AGENT: *ua
|
||||
WIKIDECK_MODES: draft
|
||||
WIKIDECK_GAME_OPERATOR: Testnet B
|
||||
WIKIDECK_GAME_PEERS: http://192.168.1.32:3101,http://192.168.1.32:3103
|
||||
node-c:
|
||||
ports: !override ["192.168.1.32:3103:3001"]
|
||||
environment:
|
||||
PUBLIC_ORIGIN: http://192.168.1.32:3103
|
||||
WIKIDECK_USER_AGENT: *ua
|
||||
WIKIDECK_MODES: classic,trending,draft
|
||||
WIKIDECK_GAME_OPERATOR: Testnet C
|
||||
WIKIDECK_GAME_PEERS: http://192.168.1.32:3101,http://192.168.1.32:3102
|
||||
@@ -0,0 +1,100 @@
|
||||
// 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');
|
||||
@@ -0,0 +1,49 @@
|
||||
#!/bin/sh
|
||||
# sim-testnet: private 3-node testnet fixture for WikiDeck Night 1 (poweredge-r350, LAN only).
|
||||
# Usage (from the repo root):
|
||||
# deploy/night/testnet.sh up build the image from this checkout and (re)start the 3 nodes
|
||||
# deploy/night/testnet.sh rolling build, then restart node-a, b, c one at a time (waits for /healthz)
|
||||
# deploy/night/testnet.sh busy print live matches + open lobbies across the 3 nodes
|
||||
# deploy/night/testnet.sh mine N [W] mine N real RandomX blocks with W workers (default 4, max 8)
|
||||
# deploy/night/testnet.sh status tip/height of each node
|
||||
# deploy/night/testnet.sh down stop the nodes (volumes, i.e. the ledgers, are kept)
|
||||
# STATE_DIR (default ~/.local/share/wikideck-night) holds the disposable testnet wallets and mined.log.
|
||||
# It is outside the repo on purpose: never commit wallets.
|
||||
set -eu
|
||||
P=wikideck-night
|
||||
LAN_IP=${LAN_IP:-192.168.1.32}
|
||||
STATE_DIR=${STATE_DIR:-$HOME/.local/share/wikideck-night}
|
||||
DC="docker compose -p $P -f compose.testnet.yaml -f deploy/night/compose.lan.yaml"
|
||||
case "${1:-}" in
|
||||
up) $DC build node-a && $DC up -d --no-build ;;
|
||||
down) $DC down ;;
|
||||
rolling)
|
||||
# Never take the whole testnet dark: one node at a time, each must pass /healthz before the next.
|
||||
$DC build node-a
|
||||
for n in a b c; do
|
||||
port=$(( 3100 + $(printf %d "'$n") - 96 ))
|
||||
$DC up -d --no-build --no-deps node-$n
|
||||
i=0
|
||||
until node -e "fetch('http://$LAN_IP:$port/healthz',{signal:AbortSignal.timeout(3000)}).then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"; do
|
||||
i=$((i+1)); [ $i -ge 60 ] && { echo "node-$n not healthy after 120 s"; exit 1; }; sleep 2
|
||||
done
|
||||
echo "node-$n healthy"
|
||||
done ;;
|
||||
busy)
|
||||
# Sum of liveMatches + openLobbies over all hosted modes on all nodes (unreachable node counts 0).
|
||||
node -e "Promise.all([3101,3102,3103].map(p=>fetch('http://$LAN_IP:'+p+'/api/game/modes',{signal:AbortSignal.timeout(5000)}).then(r=>r.json()).then(m=>m.modes.reduce((t,x)=>t+(x.stats?.liveMatches??0)+(x.stats?.openLobbies??0),0)).catch(()=>0))).then(v=>console.log(v.reduce((a,b)=>a+b,0)))" ;;
|
||||
mine)
|
||||
mkdir -p "$STATE_DIR"
|
||||
W=${3:-4}
|
||||
docker rm -f $P-miner >/dev/null 2>&1 || true
|
||||
docker run -d --name $P-miner --network ${P}_default --cpus "$W" --memory 1600m \
|
||||
--user "$(id -u):$(id -g)" -e WIKIDECK_NETWORK=testnet -e WIKIDECK_GENESIS_TIME=1792411200 \
|
||||
-e MIN_GAP="${MIN_GAP:-45}" -v "$STATE_DIR":/state -v "$PWD/deploy/night":/night:ro \
|
||||
wikideck:testnet node --experimental-strip-types /night/mine.ts "$2" "$W"
|
||||
echo "follow with: docker logs -f $P-miner" ;;
|
||||
status)
|
||||
for port in 3101 3102 3103; do
|
||||
docker run --rm --network host wikideck:testnet node -e "fetch('http://$LAN_IP:$port/p2p/status').then(r=>r.json()).then(s=>console.log($port,'blocks',s.size,'tip',s.tip.slice(0,16))).catch(e=>console.log($port,'DOWN',e.message))"
|
||||
done ;;
|
||||
*) sed -n 2,11p "$0"; exit 1 ;;
|
||||
esac
|
||||
@@ -1,30 +0,0 @@
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
wikideck-mine:
|
||||
image: ericomeehan/wikideck:latest
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
environment:
|
||||
ROLE: mine
|
||||
DATA_PATH: /tmp
|
||||
DIFFICULTY_REQUIREMENT: 10
|
||||
MINE_DB_HOST: mariadb-mine
|
||||
MINE_DB_USER: mine
|
||||
MINE_DB_PASSWORD: 123abc
|
||||
MINE_LOG_FILE: /tmp/mine.log
|
||||
depends_on:
|
||||
- mariadb-mine
|
||||
ports:
|
||||
- "8080:80"
|
||||
|
||||
mariadb-mine:
|
||||
image: mariadb:latest
|
||||
environment:
|
||||
MARIADB_ROOT_PASSWORD: abc123
|
||||
MARIADB_DATABASE: mine
|
||||
MARIADB_USER: mine
|
||||
MARIADB_PASSWORD: 123abc
|
||||
ports:
|
||||
- "3306:3306"
|
||||
@@ -0,0 +1,17 @@
|
||||
# Canonical ledger indexes
|
||||
|
||||
The ledger maintains SQLite indexes for canonical NFT ownership/sequence, mint ordering, block identity, and transaction inclusion. The UI uses these indexes for wallet decks, NFT metadata, and current-chain pagination; they do not change consensus rules or replace proof validation.
|
||||
|
||||
## Persistence and reorganization behavior
|
||||
|
||||
Accepted blocks, pending transactions, index connect/disconnect updates, undo records, and canonical event history commit in one SQLite transaction. Losing side branches and mempool submissions do not create canonical ownership events. On a reorganization, disconnects apply tip-first and connects ancestor-first. A failed write leaves both the stored ledger and in-memory tip unchanged.
|
||||
|
||||
On initial open, stored blocks are replayed and validated before the local index is built or checked. Later opens verify indexed block identity, ownership, transaction inclusion, and event continuity against that validated chain. Inconsistent state fails closed; no automatic reset or history pruning occurs. These local indexes and event records are not consensus data or a public proof that a node observed an honest network.
|
||||
|
||||
Wallet-deck results are paged and can be pinned to a canonical tip; stale tips return HTTP 409. Canonical block pages are bounded. Direct trades continue to be validated as complete atomic transactions against the canonical ownership state. No market journal, reconciliation worker, payment observer, or NFT sale-lock signer is part of this design.
|
||||
|
||||
## Validation and capacity limits
|
||||
|
||||
The regression suite covers indexed ownership and sequence against replay for transfers, atomic multi-card trades and forks; append/disconnect/reconnect ordering; side-branch and mempool exclusion; durable restart; failed writes; and stale-tip pagination.
|
||||
|
||||
The [canonical-index benchmark](../scripts/benchmark-canonical-index.ts), available as `npm run benchmark:index -- 10000`, creates and removes its own temporary SQL fixture. Its synthetic results are a baseline only—not production acceptance limits. Real PoW validation, startup replay, full DAG memory, concurrent HTTP load, and the intended deployment hardware must be measured independently. Indexes improve lookups but do not solve the retained-DAG and full-state costs described in the [consensus reference](testnet-consensus.md) and [production plan](card-only-production-plan.md).
|
||||
@@ -0,0 +1,113 @@
|
||||
# Card-only production readiness plan
|
||||
|
||||
**Status:** proposed readiness plan, updated 2026-10-28. This is not launch approval, security certification, or permission to expose a public node.
|
||||
|
||||
## Product and release boundary
|
||||
|
||||
Wikideck's current product scope is **RandomX mining, collecting cards, and direct player-to-player card transfers/trades**. This release will not implement or offer a marketplace, auctions, sales, custody, XMR deposits/withdrawals, or real-money checkout. Direct card trades are signed and applied atomically by the chain; they are not paid orders.
|
||||
|
||||
The nearest reasonable release target is a **publicly hosted, non-monetary testnet beta**. It must be labeled experimental and valueless. It is not a mainnet launch, a promise of ownership permanence, an investment product, or an independently secured network. Mining consumes compute, electricity, and time; no reward rate or profitability is promised.
|
||||
|
||||
Mainnet or valuable-card use is a separate, higher bar. It remains **NO-GO** until consensus, wallet, network, capacity, deployment, and operator risk-acceptance gates below have evidence and named sign-off. The operator has chosen not to commission external audits; this is a conscious acceptance of additional residual risk, not evidence that the protocol or implementation is secure.
|
||||
|
||||
## Current starting point
|
||||
|
||||
- Mining, local encrypted wallets, collections, transfers, and atomic card-for-card trades are implemented for the experimental testnet.
|
||||
- Marketplace, custody, sale-settlement, and Monero payment source, UI, APIs, deployment profiles, active tests, and operator documentation have been removed from the supported repository. Direct on-chain card transfers/trades remain core functionality.
|
||||
- Existing runtime volumes and historical backup packages may contain local financial journals or external database bindings. Removing source code does not delete or resolve those records; preserve them separately and do not claim new ledger-only backups include them.
|
||||
- The current network has no public bootnodes or automatic peer discovery. Peers must be configured by operators; containers on one host do not provide independent network security.
|
||||
- The inherited initial proof-of-work target accepts one in sixteen hashes, and the ten-block retarget is not production-calibrated. Nodes retain the DAG in memory, rebuild state roots across the NFT set, and revalidate stored proofs at startup.
|
||||
- Browser-wallet encryption is implemented, but same-origin code can abuse an unlocked wallet; old plaintext copies and cross-browser recovery remain concerns.
|
||||
|
||||
See the [mainnet launch limitations](mainnet-launch.md), [consensus reference](testnet-consensus.md), [wallet limitations](wallet-security.md), and [security review](security-review.md). Existing passing tests and local rehearsals are useful evidence, not production certification.
|
||||
|
||||
## Ordered release gates
|
||||
|
||||
### Gate 0 — freeze the card-only scope · implemented
|
||||
|
||||
- Publish the scope above in the product and operator docs. Market/custody/payment source, UI, APIs, dependencies, tests, deployment files, and operator tasks are removed from the supported repository.
|
||||
- Preserve existing node and financial data during retirement. Do not remove Compose volumes, old journals, PostgreSQL schemas, or historical backups. Review/archive any existing market journal before stopping a market deployment; the card-only node will not reconcile or resolve it.
|
||||
- Version the node backup contract for ledger-only backups. Refuse to create a ledger-only package if legacy financial data or a PostgreSQL custody binding remains in the selected data directory. Keep old paired backup verification/restore available as a data-preservation path; restored legacy files are inert and are not reopened by the card-only application.
|
||||
- Update the production plan, operator launch checklist, security scope, support text, and release notes so they no longer imply that market, custody, or payment work is part of this release.
|
||||
- Choose and document the only supported launch target: testnet beta or a separately reviewed mainnet. Do not mix the two identities or reuse testnet data/backups as mainnet state.
|
||||
|
||||
**Exit evidence:** scope owner approval is still required. Source/deployment removals are complete; API regression checks cover removed routes while preserving card trades; backup v2 and legacy-data refusal are covered; old paired backups remain portable. No active product docs promise sales or payments.
|
||||
|
||||
### Gate 1 — internal protocol and application review · complete by operator decision
|
||||
|
||||
**Operator decision (2026-10-28):** no external audit or independent review will be commissioned for this release. The product will proceed using internal code review, regression tests, local adversarial exercises, and explicit operator risk acceptance. This does not certify the software or establish that undiscovered critical defects are absent.
|
||||
|
||||
Internal source-assisted review covered consensus serialization/validation, signatures, state commitments, fork choice, timestamps/retarget, peer URL/DNS/pagination/response handling, RandomX native boundary, wallet signing/recovery documentation and tests.
|
||||
|
||||
Internal findings and dispositions:
|
||||
|
||||
- **Clock rollback could strand accepted SQLite history.** Startup replay applied the live future-skew admission bound to every persisted block. A block accepted at the allowed future edge could fail replay if the clock later moved backward. Startup now replays previously accepted SQLite history without reapplying that live-time bound. New blocks imported from legacy JSON retain a pinned import-time clock and imported-block cutoff; their future timestamps are checked on import and on later replays, so an untrusted legacy file cannot seed arbitrarily future-dated history. Regression tests cover both rollback recovery and repeated rejection of future-dated legacy data.
|
||||
- **Invalid work reached full NFT-state materialization.** Block validation computed the state transition/root before checking the claimed and actual RandomX proof. Cheap commitment/signature/claimed-target checks now precede native proof verification, and the complete state transition/root is computed only after the native proof matches. A regression uses an instrumented state to assert that a wrong claimed proof is rejected before NFT-state enumeration.
|
||||
- Added a deterministic 30-block versus 16-block competing-fork regression: equal cumulative work keeps the current tip, and a strictly higher-work branch then causes a 30-block reorganization while preserving both DAG branches. This is a local FakePow consensus-state test, not a multi-host security rehearsal.
|
||||
|
||||
Current validation evidence: the Docker test image and TypeScript/Vite build succeeded; the complete offline suite passed **95/95** with the native RandomX HTTP integration; the packaged native engine's upstream known-vector self-test passed. Tests cover signatures/transaction replay, atomic trades, commitments, retarget/key boundaries, equal-work fork choice, reorg/requeue, malformed schemas, peer DNS/manifest/pagination/response rejection, mempool and RPC bounds, wallet backup crypto, and restart/revalidation. These checks are the selected assurance approach; they are not a security certification.
|
||||
|
||||
**Residual risks carried forward:** no external auditor or independent reviewer will sign off. The candidate is not frozen. Multi-host eclipse/partition and clock-skew rehearsals, hostile populated-state load/reorg tests, and broad browser-wallet/XSS/recovery exercises remain open engineering work for Gates 2–5. The operator accepts proceeding without external audit; do not describe the result as audited or independently certified.
|
||||
|
||||
**Exit evidence:** internal findings fixed with regression coverage; current build, offline suite and native known-vector results recorded; operator accepts the unaudited-risk boundary. Gate 1 is **complete under this explicitly reduced scope**. This completion is not external assurance, and its remaining multi-host/load/wallet exercises continue under the following gates.
|
||||
|
||||
### Gate 2 — establish a credible network · in progress
|
||||
|
||||
- **Mainnet candidate inspection (2026-10-28, read-only):** `wikideck-randomx-mainnet-1`, candidate chain ID `3ef36901f49d57127ebb0bf43625c7334e9b8ef817fd31953761723b5474ef6c`, genesis `72be7cdac8e625562bc8a49a82a406f41b96a6fde285c9961dceafdbaca8cd1d`, candidate genesis time 2027-01-01 00:00 UTC. The genesis time has not arrived; this is a candidate manifest, not an announced launch. No production node was started and no approval or data volume was created.
|
||||
- **Repeat benchmark (2026-10-28):** same executable and container limits, 32 hashes measured 25.11 H/s warm (p50 39.13 ms, p95 48.18 ms), 883 ms cold initialization, and 642 ms for a key/cache switch. These two short samples are not a confidence interval and do not establish normal host variability. Both are verification-path hashes, not miner throughput, dedicated-host measurements, aggregate network hashpower, or a security budget. Do not extrapolate them to choose consensus parameters.
|
||||
- The first bounded sample in the same container was 23.35 H/s warm (p50 41.09 ms, p95 55.81 ms), 796 ms cold initialization, and 594 ms for a key/cache switch. Together these two observations show run-to-run variation only; they are not intended-host miner measurements.
|
||||
- **Bootstrap policy for the first beta:** use a fixed, operator-curated HTTPS peer allowlist supplied as `WIKIDECK_PEERS`; do not add DHT, automatic discovery, or peers learned from untrusted network messages. Treat configured peers as trust/bootstrap contacts only; each node independently validates every block and transaction. The current protocol provides no peer identity or independent-operation proof beyond the configured URL and TLS connection.
|
||||
- **Local rehearsal status:** the complete offline suite's native RandomX HTTP integration syncs two separately started node processes over loopback, gossips a mined transfer, and verifies restart/replay. This is local functional evidence only. A disposable three-node Compose attempt on 2026-10-28 could not allocate a Docker bridge subnet because the configured address pools were exhausted; Compose failed before creating services or volumes. No multi-host/failure-domain rehearsal has been performed.
|
||||
- **Mainnet peer configuration remains empty/unverified:** the repository has no operator-supplied public HTTPS origins, ownership/failure-domain evidence, or exercised TLS endpoints for the two required mainnet peers. The compose profile only forwards operator-provided peers and origin; placeholders are not launch infrastructure.
|
||||
- For a multi-node rehearsal, use at least three separately administered nodes across distinct failure domains and network providers; record operator, host/region/provider, address/origin, chain ID, software digest, availability window, and which node supplies each bootstrap connection. Three containers or aliases on one host do not count as independent.
|
||||
- Measure expected and adversarial hashpower on intended hardware; quantify rewrite costs and concentration risk. Decide whether this experimental beta retains the current easy target or whether a future mainnet identity needs different initial difficulty, retarget, timestamp, and stall-recovery rules. Do not alter a launched chain's consensus.
|
||||
- Rehearse bootstrap with an empty node, peer loss/recovery, partition/rejoin, conflicting branches, stale/malicious configured peer, and independent mining. Record the observed tips, cumulative work, sync lag, and recovery time. Peer URL count alone is not evidence that peers are online or independent.
|
||||
- State the finality/reorganization limits honestly. There is no formal finality today; a confirmation count is not an absolute guarantee.
|
||||
|
||||
**Exit evidence:** explicit testnet-only beta decision (or separately approved mainnet candidate), documented bootstrap peer allowlist and ownership/failure domains, repeated intended-hardware hashrate data with variance, multi-host partition/reorg/stall rehearsal, a written risk/attack-cost estimate, and an operator-owned peer/upgrade/incident plan. Internal sign-off only; no external audit is planned.
|
||||
|
||||
### Gate 3 — demonstrate capacity and recovery limits
|
||||
|
||||
- Define the expected chain length, block rate, peer count, user/API load, disk budget, memory ceiling, startup time, and latency/error objectives.
|
||||
- Run repeated tests on populated long-chain fixtures and the intended hardware, with concurrent mining, peer sync, wallet/deck reads, transfers/trades, reorgs, and hostile traffic. Measure tail latency, memory, CPU, disk/WAL growth, and restart/revalidation time.
|
||||
- Test clean shutdown, process crash, disk pressure, corrupted/stale state, isolated restore, and replay using the exact release binary. Do not treat `/healthz` alone as readiness.
|
||||
- Define and test an archival, pruning, or capacity transition before resource growth can make nodes unable to sync or restart. Do not alter consensus history silently to reclaim storage.
|
||||
|
||||
**Exit evidence:** reproducible benchmark report with workload and limits, enforced resource budgets, failure/reorg results, and a successful isolated restore/replay drill.
|
||||
|
||||
### Gate 4 — wallet, trades, and user protection
|
||||
|
||||
- Test create, lock, unlock, backup, restore in a fresh browser/profile, and recovery after app/browser upgrade across the supported browser matrix. Test signed transfer/trade review, stale offers, pending state, and reorg outcomes.
|
||||
- Perform an internal threat review of same-origin script compromise, extensions, password entry, old plaintext-wallet migration, downloaded backup handling, and key-loss support. Decide whether the beta accepts browser-only signing; document residual risks rather than implying external wallet assurance.
|
||||
- Publish experimental/no-value disclosures, mining resource risks, irreversible-transfer warnings, privacy/data-retention terms, Wikipedia text/image attribution and license handling, support contact, abuse-report path, and stop conditions.
|
||||
- Select and publish an appropriate project software license before public distribution. A Wikideck license does not replace Wikipedia or dependency licenses.
|
||||
|
||||
**Exit evidence:** internal wallet threat review, verified recovery drill, tested trade flows, reviewed participant disclosures, public support/abuse contacts, and license decision.
|
||||
|
||||
### Gate 5 — operate and release safely
|
||||
|
||||
- Prefer a managed host unless the intended self-hosted site proves ISP permission, reachable ingress/CGNAT handling, DNS/TLS renewal, trusted-proxy correctness, no direct backend exposure, firewalling, restricted administration, patching, and power/network resilience.
|
||||
- Deploy independent monitoring and alert delivery for peer/tip freshness, reorgs, native miner failures, latency/queue saturation, disk/WAL growth, and service availability. Assign a real responder and incident/rollback procedure; do not imply HA or 24/7 response without it.
|
||||
- Encrypt backups off-host and rehearse cold restore. Define and meet recovery point/time objectives; protect wallet recovery separately from node data. Preserve database/WAL consistency and verify restored proofs/ownership before resuming service.
|
||||
- Freeze the release artifact: reviewed base-image digest, dependency/native versions, SBOM, vulnerability and native-code scans, build provenance/signature, configuration manifest, and rollback image. Re-run the complete suite and smoke test against that exact artifact.
|
||||
- Run a limited, non-monetary soak and record go/no-go, known risks, release hashes, operator, reviewer, and stop criteria. Do not convert a beta into mainnet by changing an environment variable or changing the chain identity after launch.
|
||||
|
||||
**Exit evidence:** intended-host deployment test, alert drill, off-host restore result with measured RPO/RTO, signed/frozen artifacts, exact-release test report, and recorded operator/reviewer approval for the beta's limited exposure.
|
||||
|
||||
## Release decisions
|
||||
|
||||
### Non-monetary public beta
|
||||
|
||||
May be considered only after all applicable gates pass, the node remains on the explicitly labeled experimental testnet, cards are not represented as valuable, and the operator accepts the single-host or stated availability limits. This is a production-hosted beta, not production chain security.
|
||||
|
||||
### Mainnet or valuable cards
|
||||
|
||||
Requires all gates plus measured and operator-accepted consensus/economic risks, calibrated and frozen consensus parameters, a credible peer/miner topology, reviewed wallet protections, sustained capacity and adversarial evidence, and explicit governance/upgrade and incident procedures. External audit is intentionally not a requirement under the operator's decision, so residual risk remains higher and must be explicitly accepted before any mainnet activation. Until then, retain **NO-GO**.
|
||||
|
||||
### Markets and real money
|
||||
|
||||
Out of scope for this product plan. No market/custody/payment milestone is a prerequisite to the card-only beta. Any later decision to add sales or funds requires a new product scope, threat model, legal review, settlement/custody design, and separately approved release plan; it must not be inferred from this document.
|
||||
|
||||
## Evidence record
|
||||
|
||||
For every gate, record an owner, exact release/manifest, test or rehearsal, measured result, artifact location/hash, reviewer, residual risk, and disposition. Missing evidence is **unverified**, not passed. A successful build, local container startup, peer count, test total, or environment flag is never launch approval by itself.
|
||||
@@ -0,0 +1,62 @@
|
||||
# Consensus calibration and adversarial analysis — stage 3
|
||||
|
||||
**Decision remains NO-GO.** This stage supplies reproducible offline tools and bounded measurements, not new launch parameters or an operational network. Consensus, initial target, genesis, and chain identity are unchanged.
|
||||
|
||||
## Tools and safety boundaries
|
||||
|
||||
- `analyze:consensus`: deterministic JSON report calling the **actual** `expectedTarget`, `medianTime` and `workFor` helpers. Six 60-record traces: steady 900-second spacing, rapid one-second spacing, slow 7,200-second spacing, a seven-day pause at a window boundary, minimum-median timestamps with normally advancing wall time, and timestamps at the allowed +120-second future edge.
|
||||
- Records contain only fields read by those mathematical helpers. They are **not valid blocks**, have no PoW/signatures/state commitments, are never submitted to a ledger and do not add a fake-PoW production option. Spacing is externally imposed rather than sampled from constant-hashrate mining. The comparison of cumulative work is not proof that a miner can actually produce those traces.
|
||||
- `benchmark:randomx`: requires `--consent`, uses the trusted local reference binary and accepts `--hashes` (4–256, default 32), optional `--fast` (explicit >2.3 GiB memory choice), and `--network-hps` (integer 1–10^12, default 1). Unknown/invalid arguments fail before starting native work. A 60-second wall-time deadline closes the engine; native requests also retain their own bounds. No endpoint, wallet, ledger, payout or launch option exists. CPU/energy consumption is explicit.
|
||||
- Benchmark output includes executable SHA-256, platform/Node version, mode, cold hash time, repeat hash, warm sequential IPC-inclusive rate, hash latency samples and one epoch/cache switch. The declared network hashrate is a **hypothesis**, never inferred by multiplying a local worker rate by an assumed number of machines. Output targets are illustrative strings only and are never written into consensus/configuration.
|
||||
|
||||
These tools can be invoked via the package scripts on Node 24. The Docker test target includes the trusted Linux-native engine; offline benchmark execution can use a network-disabled disposable container. Do not benchmark a production node or enable fast mode without an explicit memory/energy budget. Keep reports with the exact image/native digest and host/container constraints.
|
||||
|
||||
## Verified arithmetic and interpretation
|
||||
|
||||
Wikideck interprets the 256-bit RandomX output as a big-endian integer and accepts hash <= target. Assuming uniform hash output, success probability is `(target + 1) / 2^256`, expected trials are `2^256 / (target + 1)`, and expected seconds at H hashes/s are expected trials divided by H. These are expectations, not schedules or upper time bounds.
|
||||
|
||||
The current `0fff…ffff` maximum/initial target requires **16 expected hashes**. The 15-minute setting controls the retarget goal; it does not force miners to wait 15 minutes before submitting an initially easy block. For a specified integer network rate H and goal S seconds, the analysis computes `floor(2^256 / (H*S)) - 1`, bounded by the existing allowed target range. This formula assumes stable aggregate honest work and does not choose a safe launch rate, security budget, or rounding-independent exact interval.
|
||||
|
||||
The report also includes `(q/(1-q))^z` for q < 0.5 (1 for q >= 0.5), under an idealized fixed-difficulty Poisson race with attacker share q and a **known current deficit** of z blocks. This is the probability of ever catching up under those assumptions, **not** a guarantee that a block is final: attacker progress while a block accumulates confirmations is not modeled. There is no network latency, eclipse, selfish mining, timestamp manipulation, adaptive difficulty, economic cost or attack detection model.
|
||||
|
||||
## Local native measurement (2026-10-20)
|
||||
|
||||
One sample, offline Linux x64 Docker, **1 CPU quota / 1 GiB memory limit**, Node v24.22.0, light mode, 32 sequential warm hashes, existing pinned RandomX v1.2.1 implementation:
|
||||
|
||||
| Measurement | Result |
|
||||
| --- | --- |
|
||||
| Executable SHA-256 | 5e1b99ea9df075d75a676a4ea1090e62d7738d03ac6316c41f59dedfffac4318 |
|
||||
| Cold hash (including initialization/startup) | 7,379 ms |
|
||||
| Immediate repeated same-key hash | 1,520 ms |
|
||||
| Warm batch elapsed | 16,645 ms |
|
||||
| Warm sequential IPC-inclusive rate | **1.9225 H/s** |
|
||||
| Warm p50 / p95 individual request | 552 / 755 ms |
|
||||
| One epoch/cache switch hash | 4,226 ms |
|
||||
| Initial expected interval at this measured single-worker rate | **8.323 seconds** |
|
||||
|
||||
The host was **not a dedicated controlled benchmark machine**; co-tenancy, scheduling, container CPU throttling, virtualization and thermal conditions were not instrumented. The surprising repeat-vs-warm timings reinforce that one short sample cannot certify capacity. It is a `hash`/verification-path measurement with per-request IPC, not native miner batch throughput; it includes neither full block validation nor state-root/SQLite/network overhead. Cache initialization/switch measurements are single samples, not statistically characterized distributions. Fast mode was not measured. Node `process.memoryUsage` would omit the native subprocess, so no misleading whole-engine RSS claim is made.
|
||||
|
||||
For an **explicitly hypothetical** aggregate 100 H/s network and 900-second target, the tool produced illustrative target `0000ba69dbdd3ac13d7c4a74c8111cb7aecee4bd24e8d5b85d9222dc8bfdff5b` (90,000 expected hashes). This was **not applied** and is not a recommendation. Expected rewrite cost, miner diversity, rate variance, launch surge/decline and adversarial hashrate remain unmeasured.
|
||||
|
||||
## Deterministic scenario findings
|
||||
|
||||
1. **Steady/slow at maximum target:** stable 900-second spacing retains the initial target; 8× slower spacing cannot ease above maximum. There is no wall-clock emergency easing during a stall.
|
||||
2. **Rapid trace:** difficulty does not change before the ten-block boundary. After ten one-second-spaced records the target is quartered by the elapsed-time floor (`floor(8100/4) = 2025 seconds`). Further imposed rapid windows keep increasing required work; this does not mean the same hashrate could sustain those arrival times.
|
||||
3. **Seven-day boundary pause:** the pause is placed before the first block of the third ten-block window. The endpoint difference within that window excludes the inter-window gap. This illustrates a boundary blind spot, not a fully executed exploit: the choice of where a pause occurs matters and requires review of alternative retarget designs. The current maximum target also limits what this particular trace can reveal about recovery from already-high difficulty.
|
||||
4. **Median-minimum trace:** timestamps just above the actual prior median can satisfy timestamp bounds while lagging wall time substantially. Retarget uses timestamp differences, not independently verified elapsed mining time. Analyze time-warp/oscillation attacks with quantified hashpower and viable block production before selecting rules.
|
||||
5. **Constant future-edge offset:** +120 seconds is allowed by the current timestamp rule. A constant offset cancels out of interval differences; it is not by itself evidence of a difficulty exploit. Clock skew and shifting offsets still need adversarial analysis. Validator tests reject timestamps at/below median or beyond future allowance **before proof work** and exercise the exact allowed edge reaching subsequent commitment checks.
|
||||
6. **Partition work comparison:** synthetic steady and rapid branches have different accumulated work, and the existing strict-work rule favors the greater-work branch. Existing ledger/native integration tests cover real validated branch/reorg handling separately. The synthetic report is not a multi-host partition, adversarial mining or economic-security rehearsal.
|
||||
|
||||
## Validation and remaining launch evidence
|
||||
|
||||
Build and full regression suite passed **92 tests, 0 failed, 0 skipped**, including real RandomX HTTP integration and six new calibration/timestamp tests. Tests assert inclusive-target arithmetic, bounded inputs, exact window/clamp behavior, reproducibility, scenario timestamp bounds, probability assumptions, consent refusal before engine access and validator timestamp rejection. There is no claim of formal consensus correctness.
|
||||
|
||||
Before production calibration can be approved:
|
||||
|
||||
- Benchmark the exact final native/image build on multiple intended independent miner/validator hosts; record CPU model, operating mode, effective quotas, competing load, cold/warm/cache-switch distributions and batch-miner throughput. Use repeated runs and documented confidence/variance, not this single sample.
|
||||
- Establish credible aggregate honest hashrate, launch ramp/surge/drop ranges and attack/rewrite cost assumptions; independently review target choice and the inherited ten-block/clamped endpoint retarget, including gaps across windows and timestamp attacks.
|
||||
- Add stochastic mining/partition/clock/adaptive-hashpower models and sustained multi-host rehearsals with valid reference proofs, full state commitments, mempool/reorg persistence, networking and realistic resource pressure.
|
||||
- Freeze the selected rules and actual genesis date with a new identity where required. Publish the manifest/artifact hashes and record internal findings plus explicit operator risk acceptance. Do not patch an active chain's rules in place.
|
||||
- Document reorganization and confirmation limitations honestly; no finite confirmation count is absolute finality on this unbootstrapped PoW chain.
|
||||
|
||||
See [security review](security-review.md), [launch evidence register](operator-launch.md) and the read-only preflight. The calibration blocker remains open.
|
||||
@@ -0,0 +1,462 @@
|
||||
# WikiDeck: Edit War — balance report
|
||||
|
||||
Owner: sim-balance (claude/wikideck#4). Harness: `shared/bots/`, `scripts/sim/` (PR #14).
|
||||
|
||||
## Report v1: 2026-11-17 00:45 EST
|
||||
|
||||
**Engine:** `night/2026-11-16` @ 482de6c/4a4941c (engine #25 and #27, keywords and Portals; card data #28).
|
||||
**Bots:** view-only (`viewFor`); see Method.
|
||||
**Card pool:** `docs/game/card-sample.json` (236 cards), derived per §1 with percentiles from the sample.
|
||||
**Decks:** the 4 §2.1 starter decks, 4 "realistic owned" decks (12 random cards from the sample), and archetypes.
|
||||
**Runs:**
|
||||
- full field: 3,000 matches per ruleset (report mix, 4 workers; r350 is memory-limited tonight)
|
||||
- focused starters + owned round robin: 2,000 matches per ruleset
|
||||
- greedy lever sweeps: 2,000–3,000 per variant
|
||||
|
||||
## v1.1 re-run on the real engine hooks (00:31)
|
||||
|
||||
**Engine:** `night/engine/v1-1` @ 4a0dbd0, with `RULESET_V1_1` (DESIGN #32): `viral {base 1, cap 3}`, `encyclopedic {sides 1}`, `rising.powerDelta -1`, `cultureKeyword: home`, `costThresholds [26,39,51,63,78]`. It is the same focused run as above: the §2.1 starters plus 4 owned decks (cost thresholds and Culture keyword per v1.1), 2,000 matches per ruleset.
|
||||
|
||||
| | v1 | **v1.1 (#32, exact)** | v1.1 + item 6 |
|
||||
|---|---|---|---|
|
||||
| starter deck WR, overall (FG / Head / Pio / Star) | 65 / 40 / 57 / 54 | **52 / 52 / 52 / 53** ✅ | 50 / 56 / 50 / 52 |
|
||||
| starter pairings, min–max | 23–77% | 39–61% (only FG–Head 61%, n = 51, is outside 45–55) | 42–58% |
|
||||
| owned vs starters (FG / Head / Pio / Star) | 37 / 54 / 40 / 41 | 51 / 42 / 47 / 43 | 51 / 41 / 46 / 48 |
|
||||
| first player | 53.4% | **51.2% [48.8–53.6]** ✅ | 51.0% [48.6–53.5] |
|
||||
| decided in the first third | 4.1% | 3.3% | 4.1% |
|
||||
| greedy > maxpower, lookahead-lite > greedy | 62%, 60% | 63%, 65% | 51%, 70% |
|
||||
|
||||
Net keyword value per card under the exact v1.1 (counterfactual trigger value plus `powerDelta`):
|
||||
|
||||
| keyword | v1.1 net per card |
|
||||
|---|---|
|
||||
| translated | **+1.64** |
|
||||
| nostalgic | **+1.69** |
|
||||
| viral | +1.15 (base included) |
|
||||
| encyclopedic | +0.77 |
|
||||
| rising | 1.71 − 1 = +0.71 |
|
||||
| local | +0.69 |
|
||||
|
||||
My earlier flat-+1 stand-in for encyclopedic overstated it: the real hook is worth +0.77, not +1.23.
|
||||
|
||||
**Updated recommendation:**
|
||||
1. **Ship #32 (v1.1) as it is.** Every starter's overall WR is 52–53% and first player is 51.2%. The one out-of-band pairing (FG vs Headliners at 61%) is within this run's noise.
|
||||
2. **Item 6 is an optional v1.2 candidate.** `nostalgic` and `translated` at `powerDelta -1` would bring translated and nostalgic (about +1.65) in line with the others (0.7–1.15). It fixes FG vs Headliners (50%), but at n ≈ 55 per pairing it isn't clearly better overall (42–58% vs 39–61%). Decide it on a larger run.
|
||||
3. **Owned vs starters is 42–51%:** roughly the variety-not-power goal, slightly weak against Headliners and Stargazers.
|
||||
|
||||
Raw tables:
|
||||
|
||||
#### `v1.1`: 2000 matches, 10 draws, 0 engine errors
|
||||
|
||||
- First player (turn-1 initiative), symmetric games: **51.2% [48.8–53.6] (n=1641)**
|
||||
- Decided early: 3.3% of decisive games locked in during the first third, 12.1% by half-time
|
||||
- Skill: greedy>maxpower 63.3% (n=147), lookahead-lite>greedy 64.6% (n=99), greedy>random 83.5% (n=103)
|
||||
|
||||
| starters (row vs col) | field-guide | headliners | pioneers | stargazers | vs all decks |
|
||||
|---|---|---|---|---|---|
|
||||
| field-guide | – | 61% (n=51) | 49% (n=53) | 56% (n=55) | 51.8% |
|
||||
| headliners | 39% (n=51) | – | 44% (n=54) | 50% (n=54) | 52.1% |
|
||||
| pioneers | 51% (n=53) | 56% (n=54) | – | 48% (n=58) | 52.3% |
|
||||
| stargazers | 44% (n=55) | 50% (n=54) | 52% (n=58) | – | 53.2% |
|
||||
|
||||
| owned (random 12 from card-sample) vs | field-guide | headliners | pioneers | stargazers | all |
|
||||
|---|---|---|---|---|---|
|
||||
| owned-0 | 39% | 32% | 41% | 46% | 40.3% |
|
||||
| owned-1 | 50% | 43% | 42% | 38% | 45.1% |
|
||||
| owned-2 | 55% | 37% | 62% | 44% | 49.7% |
|
||||
| owned-3 | 62% | 55% | 43% | 45% | 55.0% |
|
||||
| **all owned** | **51%** (n=233) | **42%** (n=196) | **47%** (n=198) | **43%** (n=198) | |
|
||||
|
||||
|
||||
| keyword | power per card | games decided by it | cards played |
|
||||
|---|---|---|---|
|
||||
| rising | +1.71 | 13.3% | 1503 |
|
||||
| nostalgic | +1.69 | 13.4% | 1791 |
|
||||
| translated | +1.64 | 17.8% | 4976 |
|
||||
| viral | +1.15 | 7.3% | 1852 |
|
||||
| encyclopedic | +0.77 | 6.2% | 2349 |
|
||||
| local | +0.69 | 6.4% | 4052 |
|
||||
|
||||
#### `v1.1+item6`: 2000 matches, 9 draws, 0 engine errors
|
||||
|
||||
- First player (turn-1 initiative), symmetric games: **51.0% [48.6–53.5] (n=1640)**
|
||||
- Decided early: 4.1% of decisive games locked in during the first third, 12.6% by half-time
|
||||
- Skill: greedy>maxpower 51.0% (n=147), lookahead-lite>greedy 70.0% (n=100), greedy>random 82.7% (n=104)
|
||||
|
||||
| starters (row vs col) | field-guide | headliners | pioneers | stargazers | vs all decks |
|
||||
|---|---|---|---|---|---|
|
||||
| field-guide | – | 50% (n=52) | 50% (n=52) | 53% (n=55) | 49.7% |
|
||||
| headliners | 50% (n=52) | – | 58% (n=55) | 48% (n=54) | 56.1% |
|
||||
| pioneers | 50% (n=52) | 42% (n=55) | – | 42% (n=57) | 49.7% |
|
||||
| stargazers | 47% (n=55) | 52% (n=54) | 58% (n=57) | – | 51.9% |
|
||||
|
||||
| owned (random 12 from card-sample) vs | field-guide | headliners | pioneers | stargazers | all |
|
||||
|---|---|---|---|---|---|
|
||||
| owned-0 | 48% | 41% | 50% | 39% | 47.1% |
|
||||
| owned-1 | 41% | 44% | 47% | 52% | 47.2% |
|
||||
| owned-2 | 57% | 36% | 38% | 51% | 48.8% |
|
||||
| owned-3 | 60% | 41% | 49% | 49% | 49.4% |
|
||||
| **all owned** | **51%** (n=233) | **41%** (n=197) | **46%** (n=200) | **48%** (n=198) | |
|
||||
|
||||
|
||||
| keyword | power per card | games decided by it | cards played |
|
||||
|---|---|---|---|
|
||||
| rising | +1.72 | 14.2% | 1546 |
|
||||
| translated | +1.69 | 17.0% | 4787 |
|
||||
| nostalgic | +1.68 | 13.2% | 1709 |
|
||||
| viral | +1.15 | 8.8% | 1924 |
|
||||
| encyclopedic | +0.79 | 6.7% | 2403 |
|
||||
| local | +0.70 | 6.7% | 4127 |
|
||||
|
||||
|
||||
### TL;DR for the council (report v1, 00:25; see the v1.1 re-run above for the updated recommendation)
|
||||
1. **Seat and initiative are fine:** 51.5% [49.6–53.5] for the turn-1 initiative holder (n = 2,421 symmetric games), and seat 0 51.2%. Draws are 0.4%. The tie-break (total power) decides 4.7% of games. *This full-field run started before the bot-side queue-count fix (PR #14); the effect is at most a 0.02 nudge to the heuristic. The focused starters run, after the fix, gives a borderline 53.4% [51.0–55.8] under v1 and **51.0% [48.6–53.4]** under the recommended v1.1. Initiative only matters through reveal order, and v1.1 removes most of the order-sensitive power.*
|
||||
2. **Keyword values are lopsided, confirming the critic's figures within 0.2:**
|
||||
|
||||
| keyword | power per card |
|
||||
|---|---|
|
||||
| rising | +1.76 |
|
||||
| translated | +1.53 |
|
||||
| nostalgic | +1.45 |
|
||||
| local | +0.65 |
|
||||
| **viral** | **+0.19** |
|
||||
| **encyclopedic** | **+0.19** |
|
||||
|
||||
Values are counterfactual replays. viral and encyclopedic are dead: raising viral to amount 2 / cap 3 only reached +0.24, and encyclopedic amount 3 only +0.33. **Their conditions are the problem, not their numbers.**
|
||||
3. **The starter decks are not 45–55% in v1:** pairings run 23–77%. Field Guide (rising + nostalgic) wins 65% overall and Headliners (local + viral) 40%. **With v1.1 items 1–6, every pairing is 45–55%.**
|
||||
4. **Owned decks lose to the starters**, because they are about 51% viral and squashed into cost 2–4. That is the wrong way round for "NFTs give variety, not power".
|
||||
5. **`costThresholds` squash fame.** The owned cost mix is 3/23/37/22/10/5. `[26,39,51,63,78]` gives 13/20/22/20/15/10, which hits the target and confirms the critic and designer-a.
|
||||
6. **Pure extremes are dead under every lever:** heavy (cost 5–6 only) at 15%, swarm (cost ≤ 2) at 2%. Top-heavy (curve 1/1/2/2/3/3) is **57%**, so the §8 top-heavy retarget (≥ 40%) **passes**. Swarm and heavy aren't fixable without breaking curve decks: every lever that helps one hurts the other (sweep below). Treat them as non-decks.
|
||||
7. **Matches are always 6 turns.** Only 6.5% of decisive games are decided in the first third, and 19.9% by half-time, so most games stay live to the end.
|
||||
8. **Skill expression is healthy:**
|
||||
- greedy beats maxpower ("always play the biggest card") 59.5%. §8 wants the naive line under 55% against a smart bot; it is at 40.5%.
|
||||
- lookahead-lite beats greedy 63.7%.
|
||||
- greedy beats random 77.5%.
|
||||
|
||||
### Proposed v1.1 rule changes (concrete)
|
||||
|
||||
| # | Change | Evidence | Status |
|
||||
|---|---|---|---|
|
||||
| 1 | `costThresholds: [26, 39, 51, 63, 78]` (designer-a's quantile rule) | owned cost mix 3/23/37/22/10/5 → 13/20/22/20/15/10 | **adopt** |
|
||||
| 2 | `rising.powerDelta: -1` | rising +1.76 per card, the top keyword | **adopt** |
|
||||
| 3 | viral: "+1, plus +1 per earlier reveal this turn, max +3" (critic) | viral +0.19; buffing amount/cap alone gives +0.24 | **adopt.** It needs the base +1. |
|
||||
| 4 | encyclopedic: "+2 if *you* have no other cards here" (critic) | +0.19; amount 3 alone gives +0.33 | **adopt.** It needs the condition change. |
|
||||
| 5 | Culture takes its home-stat keyword (critic) | owned decks drop from 51% viral to 18% | see the v1.1 results |
|
||||
| 6 | `nostalgic.powerDelta -1`, `translated.powerDelta -1` | +1.45 / +1.53 per card, close to rising. Without them Field Guide beats Headliners 60% under 1–5 (approximated hooks). | **optional, v1.2**: see the v1.1 re-run above |
|
||||
| 7 | No change for heavy or swarm | no lever fixes both | – |
|
||||
| 8 | No change for seat or initiative | 48–52% target met | – |
|
||||
|
||||
### Starter round robin and owned vs starters (focused run: §2.1 starters plus 4 owned decks, 2,000 matches per ruleset)
|
||||
|
||||
| | v1 | v1.1 critic package (1–5) | **v1.1 critic + item 6** |
|
||||
|---|---|---|---|
|
||||
| starter pairings, min–max | **23–77%** | 40–60% | **45–55%** ✅ |
|
||||
| starter deck WR (FG / Head / Pio / Star) | 65 / 40 / 57 / 54 | 50 / 48 / 54 / 54 | 51 / 55 / 52 / 52 |
|
||||
| owned vs starters (FG / Head / Pio / Star) | 37 / 54 / 40 / 41 | 52 / 45 / 46 / 43 | 50 / 40 / 46 / 47 |
|
||||
| first player (turn-1 initiative) | 53.4% [51.0–55.8] | 52.5% [50.1–54.9] | **51.0% [48.6–53.4]** ✅ |
|
||||
| lookahead-lite > greedy | 60% | 70% | 66% |
|
||||
|
||||
Each starter pairing has about 50–58 symmetric games (±13 pp at 95%). Each owned-vs-starter cell has about 200 games (±7 pp).
|
||||
|
||||
**Net keyword value under v1.1** (counterfactual trigger value per card, plus `powerDelta`), from the 3,000-match critic-package full field:
|
||||
|
||||
| keyword | v1.1 net per card |
|
||||
|---|---|
|
||||
| rising | 1.74 − 1 = **+0.74** |
|
||||
| viral | 0.16 + 1 = **+1.16** |
|
||||
| encyclopedic | ≈ 0.23 + 1 = **+1.23** (approximated) |
|
||||
| translated | +1.59, or **+0.59** with item 6 |
|
||||
| nostalgic | +1.58, or **+0.58** with item 6 |
|
||||
| local | **+0.66** |
|
||||
|
||||
So every keyword lands within 0.6–1.2. This matches the critic's numbers (viral +1.15, encyclopedic +0.9, rising +0.9) to within 0.35.
|
||||
|
||||
**Recommendation: ship items 1–5 plus item 6** (`nostalgic.powerDelta -1`, `translated.powerDelta -1`). Without item 6, Field Guide still beats Headliners 60% and Headliners sits at 40–41% against every starter. With it, every pairing is inside 45–55. Owned decks then win 40–50% against the starters: the variety-not-power goal, slightly on the weak side. If v1.2 wants owned decks a bit stronger, the next lever is `local.amount 2` (Headliners and owned decks are about 25% local).
|
||||
|
||||
Raw tables:
|
||||
|
||||
#### `v1` (DEFAULT_RULESET), focused: 2000 matches, 9 draws, 0 engine errors
|
||||
|
||||
- First player (turn-1 initiative), symmetric games: **53.4% [51.0–55.8] (n=1641)**
|
||||
- Decided early: 4.1% of decisive games locked in during the first third, 15.5% by half-time
|
||||
- Skill: greedy>maxpower 61.6% (n=146), lookahead-lite>greedy 60.0% (n=100), greedy>random 81.7% (n=104)
|
||||
|
||||
| starters (row vs col) | field-guide | headliners | pioneers | stargazers | vs all decks |
|
||||
|---|---|---|---|---|---|
|
||||
| field-guide | – | 77% (n=52) | 57% (n=53) | 69% (n=54) | 64.8% |
|
||||
| headliners | 23% (n=52) | – | 36% (n=56) | 35% (n=54) | 39.6% |
|
||||
| pioneers | 43% (n=53) | 64% (n=56) | – | 52% (n=58) | 56.9% |
|
||||
| stargazers | 31% (n=54) | 65% (n=54) | 48% (n=58) | – | 54.3% |
|
||||
|
||||
| owned (random 12 from card-sample) vs | field-guide | headliners | pioneers | stargazers | all |
|
||||
|---|---|---|---|---|---|
|
||||
| owned-0 | 42% | 48% | 35% | 37% | 40.0% |
|
||||
| owned-1 | 26% | 62% | 40% | 45% | 47.4% |
|
||||
| owned-2 | 45% | 57% | 44% | 43% | 52.7% |
|
||||
| owned-3 | 35% | 47% | 40% | 37% | 42.3% |
|
||||
| **all owned** | **37%** (n=233) | **54%** (n=197) | **40%** (n=200) | **41%** (n=197) | |
|
||||
|
||||
|
||||
| keyword | power per card | games decided by it | cards played |
|
||||
|---|---|---|---|
|
||||
| rising | +1.75 | 12.0% | 1822 |
|
||||
| translated | +1.55 | 18.6% | 2263 |
|
||||
| nostalgic | +1.54 | 10.3% | 2197 |
|
||||
| local | +0.71 | 6.2% | 4300 |
|
||||
| viral | +0.22 | 3.3% | 6034 |
|
||||
| encyclopedic | +0.17 | 0.8% | 1042 |
|
||||
|
||||
#### `v1.1-critic`: 2000 matches, 4 draws, 0 engine errors
|
||||
|
||||
- First player (turn-1 initiative), symmetric games: **52.5% [50.1–54.9] (n=1646)**
|
||||
- Decided early: 3.5% of decisive games locked in during the first third, 11.4% by half-time
|
||||
- Skill: greedy>maxpower 59.6% (n=146), lookahead-lite>greedy 70.0% (n=100), greedy>random 80.8% (n=104)
|
||||
|
||||
| starters (row vs col) | field-guide | headliners | pioneers | stargazers | vs all decks |
|
||||
|---|---|---|---|---|---|
|
||||
| field-guide | – | 60% (n=52) | 51% (n=53) | 51% (n=55) | 50.1% |
|
||||
| headliners | 40% (n=52) | – | 41% (n=56) | 41% (n=54) | 48.3% |
|
||||
| pioneers | 49% (n=53) | 59% (n=56) | – | 55% (n=58) | 54.2% |
|
||||
| stargazers | 49% (n=55) | 59% (n=54) | 45% (n=58) | – | 54.1% |
|
||||
|
||||
| owned (random 12 from card-sample) vs | field-guide | headliners | pioneers | stargazers | all |
|
||||
|---|---|---|---|---|---|
|
||||
| owned-0 | 46% | 43% | 46% | 49% | 43.8% |
|
||||
| owned-1 | 50% | 43% | 40% | 34% | 44.1% |
|
||||
| owned-2 | 52% | 47% | 56% | 51% | 52.7% |
|
||||
| owned-3 | 63% | 49% | 43% | 42% | 52.4% |
|
||||
| **all owned** | **52%** (n=233) | **45%** (n=198) | **46%** (n=198) | **43%** (n=199) | |
|
||||
|
||||
|
||||
| keyword | power per card | games decided by it | cards played |
|
||||
|---|---|---|---|
|
||||
| rising | +1.71 | 12.8% | 1505 |
|
||||
| nostalgic | +1.68 | 13.6% | 1789 |
|
||||
| translated | +1.64 | 17.6% | 4491 |
|
||||
| local | +0.70 | 6.3% | 4081 |
|
||||
| encyclopedic | +0.21 | 1.7% | 2177 |
|
||||
| viral | +0.13 | 0.9% | 2524 |
|
||||
|
||||
#### `v1.1-critic-nerf`: 2000 matches, 14 draws, 0 engine errors
|
||||
|
||||
- First player (turn-1 initiative), symmetric games: **51.0% [48.6–53.4] (n=1636)**
|
||||
- Decided early: 4.0% of decisive games locked in during the first third, 12.7% by half-time
|
||||
- Skill: greedy>maxpower 58.2% (n=146), lookahead-lite>greedy 66.0% (n=100), greedy>random 79.8% (n=104)
|
||||
|
||||
| starters (row vs col) | field-guide | headliners | pioneers | stargazers | vs all decks |
|
||||
|---|---|---|---|---|---|
|
||||
| field-guide | – | 49% (n=51) | 50% (n=52) | 55% (n=55) | 50.6% |
|
||||
| headliners | 51% (n=51) | – | 50% (n=54) | 46% (n=54) | 55.3% |
|
||||
| pioneers | 50% (n=52) | 50% (n=54) | – | 47% (n=58) | 51.8% |
|
||||
| stargazers | 45% (n=55) | 54% (n=54) | 53% (n=58) | – | 51.9% |
|
||||
|
||||
| owned (random 12 from card-sample) vs | field-guide | headliners | pioneers | stargazers | all |
|
||||
|---|---|---|---|---|---|
|
||||
| owned-0 | 51% | 43% | 52% | 46% | 46.0% |
|
||||
| owned-1 | 40% | 35% | 47% | 33% | 43.1% |
|
||||
| owned-2 | 52% | 42% | 37% | 56% | 51.1% |
|
||||
| owned-3 | 58% | 38% | 47% | 55% | 50.1% |
|
||||
| **all owned** | **50%** (n=231) | **40%** (n=197) | **46%** (n=199) | **47%** (n=197) | |
|
||||
|
||||
|
||||
| keyword | power per card | games decided by it | cards played |
|
||||
|---|---|---|---|
|
||||
| rising | +1.72 | 15.6% | 1534 |
|
||||
| translated | +1.69 | 16.3% | 4315 |
|
||||
| nostalgic | +1.66 | 13.3% | 1686 |
|
||||
| local | +0.71 | 6.4% | 4113 |
|
||||
| encyclopedic | +0.21 | 1.8% | 2221 |
|
||||
| viral | +0.13 | 0.7% | 2571 |
|
||||
|
||||
|
||||
|
||||
#### Critic package, full field (3,000 matches)
|
||||
|
||||
#### `v1.1-critic`: 3000 matches, 14 draws, 0 engine errors
|
||||
|
||||
- First player (turn-1 initiative), symmetric games: **49.7% [47.7–51.7] (n=2418)**
|
||||
- Decided early: 8.0% of decisive games locked in during the first third, 17.9% by half-time
|
||||
- Skill: greedy>maxpower 54.6% (n=238), lookahead-lite>greedy 62.7% (n=161), greedy>random 84.0% (n=169)
|
||||
|
||||
| starters (row vs col) | field-guide | headliners | pioneers | stargazers | vs all decks |
|
||||
|---|---|---|---|---|---|
|
||||
| field-guide | – | 38% (n=8) | 50% (n=8) | 29% (n=7) | 60.6% |
|
||||
| headliners | 62% (n=8) | – | 36% (n=11) | 56% (n=9) | 46.8% |
|
||||
| pioneers | 50% (n=8) | 64% (n=11) | – | 50% (n=12) | 59.7% |
|
||||
| stargazers | 71% (n=7) | 44% (n=9) | 50% (n=12) | – | 64.8% |
|
||||
|
||||
| owned (random 12 from card-sample) vs | field-guide | headliners | pioneers | stargazers | all |
|
||||
|---|---|---|---|---|---|
|
||||
| owned-0 | 33% | 64% | 36% | 50% | 55.3% |
|
||||
| owned-1 | 50% | 50% | 33% | 43% | 54.9% |
|
||||
| owned-2 | 55% | 58% | 27% | 42% | 52.7% |
|
||||
| owned-3 | 11% | 42% | 9% | 50% | 52.8% |
|
||||
| **all owned** | **38%** (n=37) | **54%** (n=41) | **26%** (n=39) | **46%** (n=37) | |
|
||||
|
||||
| archetype | WR vs other decks |
|
||||
|---|---|
|
||||
| curve | 58.6% [51.7–65.2] (n=203) |
|
||||
| top-heavy | 52.2% [45.4–58.9] (n=205) |
|
||||
| heavy | 23.4% [18.1–29.7] (n=205) |
|
||||
| swarm | 0.9% [0.2–3.3] (n=220) |
|
||||
| mono-Culture | 55.4% [48.9–61.6] (n=233) |
|
||||
| mono-People | 47.5% [41.0–54.1] (n=221) |
|
||||
| mono-Nature | 40.3% [34.0–46.9] (n=216) |
|
||||
|
||||
| keyword | power per card | games decided by it | cards played |
|
||||
|---|---|---|---|
|
||||
| rising | +1.74 | 21.1% | 3184 |
|
||||
| translated | +1.59 | 15.8% | 3450 |
|
||||
| nostalgic | +1.58 | 19.7% | 2871 |
|
||||
| local | +0.66 | 7.5% | 4696 |
|
||||
| encyclopedic | +0.23 | 2.0% | 4548 |
|
||||
| viral | +0.16 | 1.5% | 4733 |
|
||||
|
||||
|
||||
|
||||
### v1 full-field detail
|
||||
|
||||
#### `v1` (DEFAULT_RULESET): 3000 matches, 13 draws, 0 engine errors
|
||||
|
||||
- First player (turn-1 initiative), symmetric games: **51.5% [49.6–53.5] (n=2421)**
|
||||
- Decided early: 6.5% of decisive games locked in during the first third, 19.9% by half-time
|
||||
- Skill: greedy>maxpower 59.5% (n=237), lookahead-lite>greedy 63.7% (n=160), greedy>random 77.5% (n=169)
|
||||
|
||||
| starters (row vs col) | field-guide | headliners | pioneers | stargazers | vs all decks |
|
||||
|---|---|---|---|---|---|
|
||||
| field-guide | – | 70% (n=10) | 57% (n=7) | 83% (n=6) | 67.4% |
|
||||
| headliners | 30% (n=10) | – | 33% (n=12) | 56% (n=9) | 51.7% |
|
||||
| pioneers | 43% (n=7) | 67% (n=12) | – | 64% (n=14) | 67.0% |
|
||||
| stargazers | 17% (n=6) | 44% (n=9) | 36% (n=14) | – | 53.3% |
|
||||
|
||||
| owned (random 12 from card-sample) vs | field-guide | headliners | pioneers | stargazers | all |
|
||||
|---|---|---|---|---|---|
|
||||
| owned-0 | 29% | 40% | 15% | 58% | 51.0% |
|
||||
| owned-1 | 33% | 33% | 67% | 56% | 51.6% |
|
||||
| owned-2 | 27% | 62% | 62% | 25% | 59.7% |
|
||||
| owned-3 | 43% | 50% | 56% | 70% | 57.7% |
|
||||
| **all owned** | **31%** (n=42) | **48%** (n=48) | **44%** (n=36) | **51%** (n=43) | |
|
||||
|
||||
| archetype | WR vs other decks |
|
||||
|---|---|
|
||||
| curve | 50.0% [43.5–56.5] (n=222) |
|
||||
| top-heavy | 56.8% [50.2–63.1] (n=222) |
|
||||
| heavy | 15.3% [11.0–20.9] (n=203) |
|
||||
| swarm | 2.0% [0.9–4.6] (n=250) |
|
||||
| mono-Culture | 42.2% [35.7–48.9] (n=211) |
|
||||
| mono-People | 51.7% [44.9–58.4] (n=207) |
|
||||
| mono-Nature | 56.0% [49.6–62.3] (n=232) |
|
||||
|
||||
| keyword | power per card | games decided by it | cards played |
|
||||
|---|---|---|---|
|
||||
| rising | +1.76 | 15.6% | 4027 |
|
||||
| translated | +1.53 | 17.5% | 1266 |
|
||||
| nostalgic | +1.45 | 16.4% | 3610 |
|
||||
| local | +0.65 | 6.1% | 6781 |
|
||||
| viral | +0.19 | 2.3% | 8030 |
|
||||
| encyclopedic | +0.19 | 1.4% | 1002 |
|
||||
|
||||
|
||||
*Starter-vs-starter cells here have small n; the focused round robin above has the real numbers. Keyword table: counterfactual trigger value per card (excluding any powerDelta).*
|
||||
|
||||
|
||||
### Lever sweeps (greedy mirrors, real pool)
|
||||
|
||||
Before keywords were implemented (engine core @ c938407), I swept these levers. Each row is 3,000 greedy-mirror games. Columns are win rate vs the other decks.
|
||||
|
||||
| variant | heavy | swarm | curve | first player |
|
||||
|---|---|---|---|---|
|
||||
| v1 | 11.9% | 0.9% | 64.5% | 50.5% |
|
||||
| `energyCarryMax 2` | 17.8% | 0.9% | 59.3% | 51.0% |
|
||||
| `energyByTurn [2..7]` | **42.4%** | 0.0% | 41.3% | 49.7% |
|
||||
| `powerByCost [0,2,3,4,6,8,10]` | 8.1% | 13.4% | 65.6% | 49.3% |
|
||||
| `powerByCost [0,2,4,5,7,8,10]` | 0.3% | **36.1%** | 62.1% | 49.7% |
|
||||
| `laneCapacity 4` | 10.3% | 0.6% | 63.6% | 50.7% |
|
||||
| `onTopicBonus [0,2,2,2,2,3,3]` | 10.2% | 6.8% | 62.2% | 49.7% |
|
||||
|
||||
**Reading:** energy 2→7 rescues heavy but kills swarm and curve, and flatter power rescues swarm but kills heavy. Neither helps the normal decks. Keep v1's curve.
|
||||
|
||||
### Caveats
|
||||
- Bots aren't people. Greedy doesn't plan energy carry and queues one card at a time; lookahead-lite is shallow.
|
||||
- Hidden cards in determinizations are sampled from the loaner pool, not from the opponent's real decklist.
|
||||
- Some critic-package items need engine hooks that don't exist yet, so this run approximates them:
|
||||
|
||||
| item | modelled as | exact? |
|
||||
|---|---|---|
|
||||
| viral base +1 | `powerDelta +1` | yes |
|
||||
| encyclopedic "your side only" | `powerDelta +1`, about the critic's measured +0.9 | no: an approximation until engine-b adds `encyclopedic {sides 1}` |
|
||||
|
||||
`powerDelta > 0` is a sim stand-in: the engine's derivation clamps `powerDelta` to [−3, 0].
|
||||
- Owned decks are 4 random 12-card draws, not curated. They have no curve fill, so some are lopsided.
|
||||
|
||||
|
||||
## Method
|
||||
|
||||
**Engine.** Every match runs on the real rules engine (`shared/game`, public `index.ts` API only), through
|
||||
`shared/bots/game-adapter.ts`. Nothing in the sim re-implements rules. The engine commit is named in each
|
||||
results section.
|
||||
|
||||
**Bots** (`shared/bots/index.ts`, each a pure `(state, player, rng) => action`):
|
||||
- `random`: a uniformly random legal play or commit.
|
||||
- `maxpower`: always queues the highest printed-power card it can afford, in a random legal lane. This is the
|
||||
DESIGN §8 "always play the highest-power card" line.
|
||||
- `greedy`: one-ply. It takes the action whose result scores best on a lane heuristic: a soft lead per Topic
|
||||
plus total power. The heuristic sees the bot's own queued plays and the opponent's *revealed* cards only.
|
||||
- `lookahead-lite` / `lookahead`: flat Monte Carlo over the top 3–4 greedy candidates, with 4–8 rollouts
|
||||
each. Before each rollout, the opponent's queued plays are taken back and its hand and deck reshuffled
|
||||
(determinization), so the bot never reads hidden information.
|
||||
|
||||
**Seats.** Plans are simultaneous: seat 0 queues and commits, then seat 1. Neither bot can see the other's
|
||||
queue, so the order leaks nothing. "First player" means the seat with **initiative on turn 1**.
|
||||
|
||||
**Schedule.** Per ruleset, matches are drawn from a fixed mix of bot pairings with random seats:
|
||||
|
||||
| pairing | share | used for |
|
||||
|---|---|---|
|
||||
| greedy vs greedy | 55% | balance (decks, cards, keywords, first player) |
|
||||
| lookahead-lite vs lookahead-lite | 12% | balance with a stronger player |
|
||||
| random vs random | 5% | baseline |
|
||||
| greedy vs lookahead-lite, maxpower vs lookahead-lite, maxpower vs greedy, random vs greedy | 28% | skill expression |
|
||||
|
||||
Deck, card and keyword statistics use only **bot-symmetric** games (the same bot on both seats). Deck pairs are
|
||||
drawn uniformly, mirrors included; the per-deck win rate excludes mirrors. `--mix fast` (greedy only) is used for
|
||||
quick lever sweeps.
|
||||
|
||||
**Decks.** These are built from a card pool by `defaultDecks()`:
|
||||
- 6 seeded starter decks (`starterDeck`)
|
||||
- `curve` (cost counts 2/3/3/2/1/1)
|
||||
- `top-heavy` (1/1/2/2/3/3)
|
||||
- `heavy` (cost 5–6 first: the §8 "all-famous" line)
|
||||
- `swarm` (cost ≤ 2 first)
|
||||
- `mono-<faction>` curve decks for factions with ≥ 6 cards
|
||||
- `kw-<keyword>` curve decks for keywords on ≥ 3 cards
|
||||
|
||||
The pool is the engine's preview pool, or council-data's `card-sample.json` derived per DESIGN §1
|
||||
(percentile → fame → cost, home stat, faction keyword). Loaner power always follows the ruleset's
|
||||
`powerByCost`.
|
||||
|
||||
**Metrics.**
|
||||
- Win rates with Wilson 95% intervals. **↑/↓** marks an interval that excludes 50%.
|
||||
- First-player WR: initiative holder on turn 1, symmetric games.
|
||||
- Match length in turns.
|
||||
- "Decided early": the turn from which the eventual winner led on the heuristic until the end, as a fraction of
|
||||
the match.
|
||||
- Per-card WR: the win rate of the side that played the card.
|
||||
- Per-stat correlations.
|
||||
- **Keyword value:** a counterfactual. Each finished match is replayed with the same actions and the keyword
|
||||
removed from one side. We report the side's lost total power per keyword card, and how often removing the
|
||||
keyword made the result worse for that side ("games decided by it"). DESIGN §10.1 asks for
|
||||
`keywordParams.<id>.powerDelta` when a keyword is worth more than about 1 power.
|
||||
|
||||
**Reproduce.**
|
||||
```
|
||||
SIM_POOL=docs/game/card-sample.json SIM_RULESETS=scripts/sim/variants/v1.json \
|
||||
npx tsx scripts/sim/run.ts --engine game --matches 5000 --workers 10 --out sim-out
|
||||
python3 scripts/sim/summary.py sim-out
|
||||
```
|
||||
|
||||
**Limits.**
|
||||
- Bots are not humans. Greedy undervalues saving energy and bluffing.
|
||||
- Lookahead rollouts are short.
|
||||
- Deck archetypes are built automatically, not tuned by hand.
|
||||
- The 100-card sample is skewed: Culture 53, People 30, Nature 9, History 5, Science 3, Space 0.
|
||||
@@ -0,0 +1,149 @@
|
||||
# Card data: real stat distributions (council-data)
|
||||
|
||||
Status: **final for tonight**, 236 fully enriched cards, generated 2026-11-16 23:20 EST. Sampling stopped early on night-lead's request because Wikimedia was rate-limiting (429) our shared egress IP. 330 cards were picked; the first 236 finished enrichment.
|
||||
|
||||
**Method:** `scripts/night/card_sample.py` draws random ns0 articles in batches of 20 and keeps those that pass the `server/wiki.ts` filter: a thumbnail from upload/thumb.wikimedia.org and an intro extract of at least 40 characters. About 44% of random pages pass. Each card is enriched with the same API parameters as `server/enrichment.ts`:
|
||||
- six completed months, Jun–Oct 2026; attention uses October
|
||||
- monthly views summed from the daily REST pageviews
|
||||
|
||||
On top of that it adds Wikidata P31 and a 30-day drift (views 10-17..11-15 vs 09-17..10-16).
|
||||
|
||||
**Politeness:** the sampler runs serially at 1 request a second or slower, honours Retry-After, and caches every response to disk. `scripts/night/card_analyze.py` produces everything below, plus the `percentiles` (99 cut points each, for DESIGN §1.1) in `card-sample.json`.
|
||||
|
||||
## Files
|
||||
- `card-sample.json`: `cards[]` with the `PageEnrichment` shape, plus `category` (legacy `category()`), `instanceOf` (P31), `faction` (the P31 rules below), `tiers` and `drift30`. Top level: `percentiles`, `tierBreakpoints`, `factionRules` and `note`.
|
||||
- `starter-cards.json`: the loaner **pool**, 20 real frozen snapshots (a `MintStatsSnapshot` in `snapshot`). It also holds `starterDeckPageIds`: the 48 DESIGN §2.1 starter titles with their real pageIds and `cardId`s.
|
||||
|
||||
## Headline findings (236 cards)
|
||||
1. **Raw scores are compressed.**
|
||||
|
||||
| score | median | p10–p90 | max |
|
||||
|---|---|---|---|
|
||||
| attention | 32 | 20–53 | 77 |
|
||||
| depth | 63 | 54–73 | 87 |
|
||||
| reach | 20 | 0–45 | 70 |
|
||||
|
||||
No honest card reaches 100. Use `percentiles` (§1.1) or the 1–10 tiers, never the raw 0–100 values.
|
||||
2. **Correlations (Spearman):**
|
||||
- attention and depth: 0.61, so these two double-count fame
|
||||
- reach is nearly independent of both (0.17 with attention, 0.02 with depth)
|
||||
3. **Reach has a hard floor:** 18% of cards (42) have 0 other languages, so reach is 0. Under the §1.1 counting, all of them get pct_reach of about 8.
|
||||
4. **Raw values are long-tailed:**
|
||||
|
||||
| value | median | p90 | max |
|
||||
|---|---|---|---|
|
||||
| monthly views | 82 | 1,576 | 42k |
|
||||
| pageBytes | 6.1 KB | 24 KB | |
|
||||
| languageCount | 3 | 22 | |
|
||||
5. **Trend is mostly down:**
|
||||
- 65% of cards have a negative trendPercent, 34% positive; median −9.5%
|
||||
- 16% swing by more than 50% either way
|
||||
- null: 1%
|
||||
6. **Live drift is small in score terms.** The 30-day median |pageview drift| is 22% (p90 60%). That moves attention by only **1.7 points** (p90 6.3), so at-mint and live values differ little unless someone inflates them.
|
||||
7. **The legacy `category()` split is very skewed:**
|
||||
|
||||
| category | share |
|
||||
|---|---|
|
||||
| Culture | 56% |
|
||||
| People | 26% |
|
||||
| Nature | 8% |
|
||||
| History | 8% |
|
||||
| Science | 1% |
|
||||
| Space | 0.4% |
|
||||
8. **Candidate factions from P31:**
|
||||
|
||||
| faction | share |
|
||||
|---|---|
|
||||
| People | 29% |
|
||||
| Places | 20% |
|
||||
| Nature | 8% |
|
||||
| Structures | 7% |
|
||||
| Works | 5% |
|
||||
| Events | 5% |
|
||||
| Organisations | 4% |
|
||||
| Ideas & Tech | 3% |
|
||||
| Sport | 3% |
|
||||
| unclassified | 14% |
|
||||
|
||||
Suggested 6 for v2: People, Places, Nature, Works & Culture (Works + Organisations + Sport), Structures, Events & Ideas, plus a neutral fallback.
|
||||
|
||||
## Full tables
|
||||
|
||||
Sample: **236 cards**; ~44% (149/340 logged during sampling) of random pages pass the illustrated filter. Pageviews available for 236.
|
||||
|
||||
| stat | n | min | p10 | p25 | median | p75 | p90 | max | mean | skew |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| attention | 236 | 13 | 20 | 25 | 32 | 41 | 53 | 77 | 35 | 0.78 |
|
||||
| depth | 236 | 48 | 54 | 58 | 63 | 68 | 73 | 87 | 64 | 0.42 |
|
||||
| reach | 236 | 0 | 0 | 10 | 20 | 33 | 45 | 70 | 23 | 0.36 |
|
||||
| pageBytes | 236 | 772 | 1847 | 3084 | 6110 | 12805 | 24412 | 168332 | 11691 | 4.61 |
|
||||
| languageCount | 236 | 0 | 0 | 1 | 3 | 9 | 22 | 124 | 8 | 4.14 |
|
||||
| monthlyViews | 236 | 5 | 16 | 30 | 82 | 300 | 1576 | 42025 | 812 | 9.82 |
|
||||
| dailyAverage | 236 | 0.2 | 0.5 | 1.0 | 2.6 | 9.7 | 50.8 | 1355.6 | 26.2 | 9.82 |
|
||||
| trendPercent | 234 | -86.6 | -49.3 | -26.3 | -9.5 | 5.3 | 31.2 | 388.9 | -3.6 | 4.11 |
|
||||
| drift30Percent | 235 | -94.7 | -58.2 | -33.8 | -12.9 | 1.0 | 27.7 | 2268.7 | -4.2 | 14.07 |
|
||||
|
||||
**Spearman rank correlations** (cards with pageviews):
|
||||
|
||||
| | attention | depth | reach | trendPercent | drift30Percent |
|
||||
|---|---|---|---|---|---|
|
||||
| attention | 1.00 | 0.61 | 0.17 | 0.35 | 0.33 |
|
||||
| depth | 0.61 | 1.00 | 0.02 | 0.15 | 0.14 |
|
||||
| reach | 0.17 | 0.02 | 1.00 | 0.00 | 0.09 |
|
||||
| trendPercent | 0.35 | 0.15 | 0.00 | 1.00 | 0.31 |
|
||||
| drift30Percent | 0.33 | 0.14 | 0.09 | 0.31 | 1.00 |
|
||||
|
||||
(n=234; attention~monthlyViews, depth~pageBytes, reach~languageCount are monotonic so their rank correlations are identical.)
|
||||
|
||||
**trendPercent sign:** positive 79 (34%), negative 153 (65%), zero 2; null (prior month 0 or no views) 2. |trend| > 50%: 38; > 100%: 7.
|
||||
|
||||
**30-day drift** (views 10-17..11-15 vs 09-17..10-16): median |drift| 22%, p90 |drift| 60%. Attention score change implied: median 1.7 points, p90 6.3 points.
|
||||
|
||||
**attention histogram (deciles 0-9,10-19..90-100):** 0 19 74 74 36 20 12 1 0 0
|
||||
**depth histogram (deciles 0-9,10-19..90-100):** 0 0 0 0 2 72 117 38 7 0
|
||||
**reach histogram (deciles 0-9,10-19..90-100):** 42 60 53 43 21 15 1 1 0 0
|
||||
|
||||
Reach = 0 (no other languages): 42; reach 100 (>=999 langs) impossible in practice, max langs 124. Attention null: 0; attention 0: 0.
|
||||
|
||||
**Sum of three stats:** min 73, p10 89, p25 102, median 116, p75 135, p90 156, max 222
|
||||
|
||||
**Legacy `category()` (server/wiki.ts):** Culture 133, People 62, Nature 19, History 18, Science 3, Space 1
|
||||
|
||||
**Top Wikidata P31 classes:** human 64, taxon 16, village 7, commune of France 6, river 5, human settlement 4, musical group 3, building 3, gene 3, village of Poland 2, civil parish 2, protest 2, legislative election 2, castle 2, events in a specific year or time period 2, township of Pennsylvania 2, film 2, company 2, island 2, rural municipality of Austria 1, municipality of Austria 1, municipality of Brazil 1, television film 1, nor'easter 1, rail company (Japan) 1, municipality 1, association football match 1, final 1, local government area of Victoria 1, plant disease 1, basketball team season 1, mosque 1, functional programming language 1, purely functional programming language 1, dependently typed programming language 1, programming language 1, free software 1, proof assistant 1, municipality of Croatia 1, municipality of Bangladesh 1
|
||||
|
||||
No Wikidata item: 0; no P31: 13
|
||||
|
||||
**Most frequent category words (cards containing):** stubs 81, births 55, people 50, from 50, century 46, living 33, geography 30, american 29, deaths 28, united 27, county 27, states 23, established 21, establishments 20, alumni 18, places 17, university 16, buildings 16, state 15, national 14, structures 14, male 13, players 12, district 11, villages 11, sportsmen 11, members 11, described 10, football 10, sports 10, city 10, film 10, british 9, companies 9, populated 9, sportspeople 9, biography 9, york 9, women 8, taxa 8, germany 8, politicians 8, television 7, writers 7, french 7, genera 7, based 7, communes 7, language 7, expatriate 7, named 7, olympics 7, completed 7, historic 7, register 7, faculty 6, pennsylvania 6, civil 6, history 6, california 6
|
||||
|
||||
|
||||
## Rank-normalised tiers (1–10)
|
||||
|
||||
Tier = 1 + number of breakpoints the score is **>=**. Breakpoints are the sample deciles p10..p90 of the 0–100 score. Ties make some tiers thin (scores are integers).
|
||||
|
||||
| stat | p10 | p20 | p30 | p40 | p50 | p60 | p70 | p80 | p90 |
|
||||
|---|---|---|---|---|---|---|---|---|---|
|
||||
| attention | 20 | 24 | 27 | 30 | 32 | 35 | 39 | 44 | 53 |
|
||||
| depth | 54 | 57 | 59 | 61 | 63 | 65 | 67 | 69 | 73 |
|
||||
| reach | 0 | 10 | 10 | 16 | 20 | 26 | 30 | 36 | 45 |
|
||||
|
||||
Resulting tier counts — attention: None:0 1:19 2:27 3:24 4:23 5:23 6:17 7:28 8:25 9:22 10:28
|
||||
; depth: 1:14 2:23 3:26 4:21 5:25 6:26 7:22 8:21 9:30 10:28
|
||||
; reach: 1:0 2:42 3:0 4:30 5:30 6:32 7:21 8:27 9:27 10:27
|
||||
|
||||
|
||||
## Candidate factions (Wikidata P31 rules)
|
||||
|
||||
| faction | n | share | median attention | median depth | median reach | example |
|
||||
|---|---|---|---|---|---|---|
|
||||
| People | 68 | 29% | 31 | 65 | 22 | Salahuddin of Aceh |
|
||||
| Places | 48 | 20% | 28 | 61 | 32 | St. Georgen am Längsee |
|
||||
| Other | 34 | 14% | 40 | 65 | 16 | Village (Pennsylvania) |
|
||||
| Nature | 20 | 8% | 30 | 56 | 29 | Dichromorpha viridis |
|
||||
| Structures | 17 | 7% | 26 | 57 | 10 | Pathrail Mosque |
|
||||
| Works | 12 | 5% | 36 | 63 | 13 | The Best of Men |
|
||||
| Events | 12 | 5% | 40 | 72 | 13 | April 2021 nor'easter |
|
||||
| Organisations | 10 | 4% | 48 | 68 | 10 | Hiroshima Electric Railway |
|
||||
| Ideas & Tech | 8 | 3% | 30 | 63 | 16 | Agda (programming language) |
|
||||
| Sport | 7 | 3% | 27 | 70 | 16 | 1912 Argentine Primera División final |
|
||||
|
||||
Unclassified P31 labels: typeface 1, annexation 1, position 1, family 1, historic site 1, automobile manufacturer 1, historical society 1, stock character 1, pigeon breed 1, shopping center 1, Wikimedia list article 1, clinical sign 1, tram route 1, rubber-tyred tram 1, oil refinery 1, waterfall 1, orisha 1, water deity 1, Loa 1, arch 1, award 1, sex scandal 1, military base 1, artillery battery 1
|
||||
@@ -0,0 +1,673 @@
|
||||
# WikiDeck: Edit War — game design v1 (draft)
|
||||
|
||||
**Status:** v1 DRAFT, freeze target 23:30 EST 2026-11-16.
|
||||
**Owners:** council-designer-a owns sections 0–9 (research, card derivation, rules). council-designer-b
|
||||
owns sections 10–12 (keywords, peer-hosted modes, worked example). council-critic reviews.
|
||||
Every number in **`code font`** is a rules-config key (see §9). Modes can override any of them.
|
||||
|
||||
A two-player lane game for 3–6 minute matches. Each player has a 12-card deck and there are 3
|
||||
**Topics** (lanes) with 3 slots per side. There are 6 turns, both players plan at the same time, and
|
||||
energy ramps from 1 to 6, with 1 unspent energy carried over. Reveals interleave one card at a time.
|
||||
Win 2 of the 3 Topics. Each Topic is judged on one Wikipedia stat (**Attention**, **Depth** or
|
||||
**Reach**), and a card is stronger in a Topic that matches its best stat. Fame (how high a card's
|
||||
stats are overall) sets its **cost**, not its efficiency, so famous cards are sidegrades. They are
|
||||
not upgrades.
|
||||
|
||||
---
|
||||
|
||||
## 0. Research summary (what we took, what we left)
|
||||
|
||||
| Game | Why it's fun | Taken | Left |
|
||||
|---|---|---|---|
|
||||
| Marvel Snap | 3-minute matches; simultaneous turns; 3 lanes, so the decision is *where*, not just *what* | lanes, about 6 turns, simultaneous planning, small deck | stakes betting (modes only); we deliberately diverge in lane size (3), energy carry-over, interleaved alternating reveals, stats visible from turn 1 with hidden Portals, and on-topic tie-breaks |
|
||||
| Hearthstone | mana curve; readable cards; tempo | energy = turn number, curve-shaped costs | 30-card decks and 15-minute matches; hero powers |
|
||||
| Magic: The Gathering | factions (colours) with distinct identities; deckbuilding depth | 6 factions with their own keyword flavour | land screw (resource variance); the stack; long text |
|
||||
| Balatro | huge "moment" when a combo goes off; simple base rules plus modifiers | lane modifiers (Portals) as the run-to-run variety | single-player scoring |
|
||||
| Slay the Spire | readable intents; every card is a choice | open information about lane state and power | roguelike runs (could be a mode) |
|
||||
| Gwent | rows; best 2 of 3; passing and bluffing | best 2 of 3 Topics; hidden commitments | multi-round card advantage (too long) |
|
||||
| Pokémon TCG | type advantage | on-topic bonus (card stat matches lane stat) | energy attachment; coin flips |
|
||||
| Top Trumps | instantly understood: "my number beats yours" | lanes judged on one stat | picking the stat is solved play (always pick your best) |
|
||||
| Dominion | deck building as play | — (too long for 3–6 min) | — |
|
||||
|
||||
**What is ours, not borrowed:**
|
||||
- (a) each Topic is judged on one Wikipedia stat (the Top Trumps twist)
|
||||
- (b) cost comes from an article's fame instead of being printed
|
||||
- (c) a trend arrow driven by live pageviews
|
||||
- (d) a total-power and consensus tie-break instead of stakes betting
|
||||
- smaller choices: 3 slots per lane, 1 carried-over energy, interleaved reveals, and stats visible
|
||||
from turn 1 with hidden Portals
|
||||
|
||||
The core loop is a lanes game in the style of Snap. The Top Trumps twist is that each lane asks for
|
||||
one Wikipedia stat. That makes every stat matter and gives each turn its main decision: play the card
|
||||
on-topic for the bonus, or put it where the fight is.
|
||||
|
||||
---
|
||||
|
||||
## 1. Card derivation (card data → game card)
|
||||
|
||||
The engine never reads raw 0–100 stats as power. Every game card is derived **deterministically** from a
|
||||
`CardInput` that the match host freezes at match start:
|
||||
|
||||
```
|
||||
CardInput = { cardId, pageId, title, category, rarity,
|
||||
snapshot: MintStatsSnapshot, // at mint, immutable
|
||||
live: { trendPercent: number | null, dailyAverage: number | null }, // frozen at match start
|
||||
check: 'verified' | 'unverified' | 'unchecked' | 'loaner', // set by the host (§1.10)
|
||||
pinned?: { cost, home, faction } } // loaners only (§2.1): replaces §1.1–1.5
|
||||
```
|
||||
|
||||
### 1.1 Percentiles (rank-normalisation)
|
||||
For each stat `s` in {attention, depth, reach}, `pct_s` = the percentile (0–100, integer) of the card's
|
||||
snapshot score in the reference table `percentiles.<s>`. That table holds 99 ascending cut points from
|
||||
council-data's `docs/game/card-sample.json`.
|
||||
`pct_s` = the number of cut points strictly below the score, plus half the number equal to it, rounded
|
||||
down. A `null` attention gives `pct_attention = null`.
|
||||
|
||||
### 1.2 Fame → Cost
|
||||
`fame` = the integer mean (rounded half up) of the non-null percentiles.
|
||||
`cost` = 1 + the number of thresholds in `costThresholds` (5 ascending values, default
|
||||
`[26, 39, 51, 63, 78]` in v1.1) that are ≤ `fame`. So cost runs 1–6.
|
||||
**Thresholds are data, not guesses (v1.1).** `fame` is a *mean* of up to 3 percentiles, so it clusters
|
||||
around 50 even though each percentile is uniform. The v1.0 values `[15, 35, 55, 75, 90]` treated fame as
|
||||
uniform, so 82% of the pool landed on cost 2–4 (3/23/37/22/10/5 %). `costThresholds` is therefore set to
|
||||
the fame values at the **15/35/55/75/90 % points of the reference sample** (the same `card-sample.json`
|
||||
whose `percentiles` table §1.1 uses). That's the integer set that brings the sample's cost spread closest
|
||||
to the target 15/20/20/20/15/10 %. The v1.1 defaults come from the 236-card sample (fame 8–98) and
|
||||
give 13/20/22/20/15/10 %. Whenever council-data refreshes the sample, the percentile table and
|
||||
`costThresholds` are regenerated together and ship as one change. Pinned loaners (§2.1) are unaffected.
|
||||
|
||||
### 1.3 Power
|
||||
`power` = `powerByCost[cost]`, default `[_, 1, 2, 4, 6, 8, 10]` (cost 1 → 1 … cost 6 → 10). The
|
||||
critic's sim showed that heavy decks were too weak with `[…5,7,9]`.
|
||||
Power depends **only on cost**. Two cards of the same cost have the same base power, whatever their
|
||||
fame. Inflating stats (forged snapshots, template shopping) only moves a card up the curve. It never
|
||||
makes a card more efficient.
|
||||
|
||||
### 1.4 Home stat
|
||||
`home` = the stat with the highest `pct_s`. Ties are broken in this order: depth, reach, attention.
|
||||
Depth and reach are the hardest to inflate. A `null` stat can never be home.
|
||||
When a card is in a Topic whose stat equals its `home`, it gets **+`onTopicBonus[cost]`** power
|
||||
(default `[0, 1, 1, 2, 2, 3, 3]`, i.e. ⌈cost/2⌉).
|
||||
On-topic efficiency is then about 2 power per energy at every cost (2.0 / 1.5 / 2.0 / 1.75 / 2.0 / 2.0).
|
||||
Off-topic, cheap cards are weaker (1.0) than expensive ones (1.5). Cheap cards want their Topic, and
|
||||
big cards are flexible.
|
||||
|
||||
### 1.5 Faction
|
||||
`faction` = the card's `category` (Space, Nature, People, Science, History, Culture), from
|
||||
`server/wiki.ts`. Culture is about half the pool, so faction keywords are written so that a
|
||||
mono-faction deck gains no consistency edge (§10: no v1 keyword scales with faction count).
|
||||
|
||||
### 1.6 Trend (live, small, capped)
|
||||
`trend` = +1 if `live.trendPercent ≥ trendUp` (default 25), −1 if `≤ trendDown` (default **−200**,
|
||||
which means there is **no down arrow in v1**: 69% of cards trend negative, so a ▼ would mostly land as
|
||||
a quiet penalty on famous owned cards; modes can turn it back on), otherwise 0. A `null` value gives 0. Trend also needs `live.dailyAverage ≥ trendMinDaily` (default
|
||||
**20**), because percentages on tiny articles are noise; otherwise trend is 0. The host computes it **once at match start**, and it is frozen for
|
||||
the match. It shows as an arrow (▲), not a number. It adds to power in every Topic. *Why no ▼ by default:* 69% of the sample has a
|
||||
negative `trendPercent`, and only busy (mostly owned, famous) cards pass `trendMinDaily`, so a ▼ would quietly penalise collectors.
|
||||
Modes may turn it back on with e.g. `trendDown: -25`.
|
||||
|
||||
### 1.7 Rarity
|
||||
The hash-derived `rarity` (`shared/protocol.ts:38`) is **cosmetic in v1** (frame colour only). Mining luck must not
|
||||
become power or keyword choice.
|
||||
|
||||
### 1.8 Keyword
|
||||
Each card has at most **one** keyword: cost-1 cards are vanilla, and the others get their faction's keyword (§10.1).
|
||||
|
||||
### 1.9 Card face (phone)
|
||||
The card face shows **cost** (top-left), **power** (big, centre; the bonus shows as a "+N" badge on the home icon when the card is on-topic), a **home-stat icon**
|
||||
(📣 attention / 📚 depth / 🌐 reach), an optional trend arrow, and one keyword word. That is two
|
||||
numbers, plus the live lane power when the card is on the board.
|
||||
|
||||
### 1.10 Plausibility (anti-forgery, off-chain)
|
||||
When `verifyStats` is true (the default for hosted matches), the match host checks each owned card's
|
||||
snapshot before the match:
|
||||
`pageBytes` against that revision's byte size, `languageCount` ≤ the live count + 5, and views for the
|
||||
snapshot month within ±10 % of the pageviews API.
|
||||
A card that fails is played with its live values. The **host replaces `snapshot`** with a snapshot
|
||||
built from the live values (`deriveStats` on the live bytes, languages and views) **before** it builds
|
||||
the `CardInput`. The match log marks the card `unverified`.
|
||||
The engine does no I/O and only ever sees one version of each card.
|
||||
- **Caching:** results are cached per `(pageId, revisionId, snapshotMonth)`. They are immutable, so a
|
||||
cached pass or fail never expires. Live values for a failed card are cached for 24 h.
|
||||
- **Card can't be verified** (the pageId or revision doesn't exist, or the title or category doesn't
|
||||
match): the card is **rejected at deck validation**, and the player is asked to swap in a loaner.
|
||||
- **API failure:** if Wikipedia can't be reached and nothing is cached, the card plays from its snapshot
|
||||
with `check: 'unchecked'`. The engine then caps its cost at `uncheckedCostCap` (default **4**), and
|
||||
power follows the capped cost. Matches are never blocked.
|
||||
- The engine's only use of `check` is that cost cap. Loaner cards are `check: 'loaner'`.
|
||||
|
||||
---
|
||||
|
||||
## 2. Decks
|
||||
|
||||
- **Deck size:** exactly `deckSize` cards (default **12**).
|
||||
- **Copies:** at most `maxCopiesPerPage` cards with the same `pageId` (default **2**). Owned and loaner
|
||||
copies count **together**. Each copy keeps its own snapshot, so the two copies may differ in cost.
|
||||
- **Deck validation** (engine): the size is right, the copy limit holds, every card's `check` is
|
||||
valid, and there are no more loaners than `maxLoaners`. An invalid deck can't start a match.
|
||||
- **Owned cards:** any card the player's wallet owns at match start. Ownership is read off-chain. The
|
||||
match never moves, locks or burns a card.
|
||||
- **Loaner cards:** off-chain preview cards with a fixed `CardInput`, shipped with the game data
|
||||
(`docs/game/starter-cards.json`, picked by council-data: about 24 pageIds across all 6 categories,
|
||||
with frozen, hand-checked snapshot stats, including the 4 cards in `shared/catalog.ts`).
|
||||
Loaners follow the same curve (§2.1 pins their cost, home and faction), so they are no weaker or stronger than owned cards.
|
||||
- **Starter decks:** `starterDecks` (default: 4 fixed 12-card loaner decks). Each one has two leading
|
||||
factions and an average cost of 3.0–3.3, and is **curve-shaped**: at least 3 cards of cost 4 or more,
|
||||
and at most 4 of cost 1. A new player picks one and can play at once.
|
||||
- **Mixed decks:** an owned deck may fill any slots with loaners, up to `maxLoaners` (default 12, which
|
||||
means no limit). Owning NFTs gives **variety**, not power: owned and loaner cards follow the same
|
||||
curve.
|
||||
|
||||
### 2.1 Starter decks v1 *(owner: council-designer-b)*
|
||||
|
||||
These are the default `starterDecks`: four 12-card loaner decks.
|
||||
- **Every deck has the same curve:** costs `1,1,2,2,3,3,3,4,4,5,5,6`. That's an average of 3.25, with 5 cards of cost 4 or more and 2 of cost 1.
|
||||
- **Every deck has the same shape:** 6 cards from each of two factions, and 4 cards for each home stat. So every deck can play on-topic in every lane.
|
||||
- **Loaner values are pinned.** Cost, home and faction are hand-set (not derived from `starter-cards.json`), so a loaner carries
|
||||
`pinned: { cost, home, faction }`. For `check: 'loaner'` the engine takes these instead of §1.1–1.5.
|
||||
Everything after them still applies: `powerByCost`, `onTopicBonus`, `vanillaBonus`, the §10.1 keyword choice and `keywordParams`.
|
||||
A mode that changes those numbers changes loaners exactly as it changes owned cards.
|
||||
- **Pinned cost isn't fame.** Cost was set by hand to fit the curve, not from the article's fame. Rarity is `Common` (frame only) and trend is 0.
|
||||
- **Loaner ids:** `cardId` = `loaner:<kebab-title>`, and `pageId` = the article's real pageId (v1 pins the 4 `shared/catalog.ts` ones: Moon 19331, Periodic table 23053, Octopus 22780,
|
||||
Albert Einstein 736; the rest are filled in from one batched API call in v1.1, `null` until then). The copy limit counts per `pageId`
|
||||
together with owned copies (§2); a loaner with `pageId: null` counts per `cardId`.
|
||||
- **Relation to `docs/game/starter-cards.json`** (council-data, real frozen snapshots of random articles): that file is the
|
||||
**loaner pool** for the sim and for "fill a slot with a loaner" in the deck builder. It is **not** the default starter decks.
|
||||
The decks below pin their values on purpose, for two reasons. Famous, recognisable articles would all derive to cost 5–6.
|
||||
And the random sample has no Space cards (CARD_DATA.md finding 6).
|
||||
- **v1.1 note (factions):** CARD_DATA.md finding 6 shows the legacy `category()` split as Culture 53%, People 30%, Nature 9%,
|
||||
History 5%, Science 3%, Space 0%. In v1, owned decks were therefore about 50% viral and 30% local. Viral was the weakest keyword, so a typical owned deck
|
||||
may be *weaker* than the starter decks. That's the wrong way round for "NFTs give variety, not power". v1 ships as is.
|
||||
For v1.1, sim-balance runs a **realistic owned deck** (12 cards drawn from `card-sample.json` with its real category mix)
|
||||
against each starter. **v1.1 fix:** viral gets a base of +1, and Culture cards take a keyword by home stat (§10.1), so owned decks
|
||||
now have all six keywords in the mix. **BALANCE.md v1.1:** starters 52–53% overall, and owned vs starters 42–51%
|
||||
(weakest vs Headliners and Stargazers; v1.2 candidates: `nostalgic`/`translated` `powerDelta -1`, `local.amount 2`). The P31-based factions council-data proposes (People, Places, Nature, Works & Culture,
|
||||
Structures, Events & Ideas) are the v2 fix, and would need the host to fetch P31 (it isn't in `PageEnrichment`).
|
||||
|
||||
Keywords follow from §10.1: cost 1 → vanilla, otherwise the faction keyword (shown in brackets).
|
||||
|
||||
**A. Stargazers: Space (translated) + Science (encyclopedic)**
|
||||
| Cost | Card | Faction | Home |
|
||||
|---|---|---|---|
|
||||
| 1 | Moon | Space | reach |
|
||||
| 1 | Electron | Science | depth |
|
||||
| 2 | Mars | Space | attention |
|
||||
| 2 | Periodic table | Science | depth |
|
||||
| 3 | Saturn | Space | reach |
|
||||
| 3 | Photosynthesis | Science | attention |
|
||||
| 3 | Black hole | Space | depth |
|
||||
| 4 | Quantum mechanics | Science | reach |
|
||||
| 4 | Milky Way | Space | attention |
|
||||
| 5 | DNA | Science | attention |
|
||||
| 5 | Sun | Space | reach |
|
||||
| 6 | Theory of relativity | Science | depth |
|
||||
|
||||
**B. Field Guide: Nature (rising) + History (nostalgic)**
|
||||
| Cost | Card | Faction | Home |
|
||||
|---|---|---|---|
|
||||
| 1 | Octopus | Nature | depth |
|
||||
| 1 | Stonehenge | History | attention |
|
||||
| 2 | Axolotl | Nature | attention |
|
||||
| 2 | Rosetta Stone | History | reach |
|
||||
| 3 | Coral reef | Nature | depth |
|
||||
| 3 | Roman Empire | History | reach |
|
||||
| 3 | Honey bee | Nature | attention |
|
||||
| 4 | Ancient Egypt | History | depth |
|
||||
| 4 | Amazon rainforest | Nature | reach |
|
||||
| 5 | Blue whale | Nature | attention |
|
||||
| 5 | Great Wall of China | History | reach |
|
||||
| 6 | World War II | History | depth |
|
||||
|
||||
**C. Headliners: People (local) + Culture (by home stat: attention → viral, depth → encyclopedic, reach → translated)**
|
||||
| Cost | Card | Faction | Home |
|
||||
|---|---|---|---|
|
||||
| 1 | Haiku | Culture | attention |
|
||||
| 1 | Ada Lovelace | People | depth |
|
||||
| 2 | Jazz | Culture | attention |
|
||||
| 2 | Marie Curie | People | reach |
|
||||
| 3 | Mona Lisa | Culture | reach |
|
||||
| 3 | Frida Kahlo | People | attention |
|
||||
| 3 | Chess | Culture | depth |
|
||||
| 4 | Leonardo da Vinci | People | reach |
|
||||
| 4 | The Beatles | Culture | attention |
|
||||
| 5 | William Shakespeare | People | depth |
|
||||
| 5 | Olympic Games | Culture | reach |
|
||||
| 6 | Wolfgang Amadeus Mozart | People | depth |
|
||||
|
||||
**D. Pioneers: People (local) + Space (translated)**
|
||||
| Cost | Card | Faction | Home |
|
||||
|---|---|---|---|
|
||||
| 1 | Sputnik 1 | Space | reach |
|
||||
| 1 | Nikola Tesla | People | attention |
|
||||
| 2 | Hubble Space Telescope | Space | depth |
|
||||
| 2 | Isaac Newton | People | reach |
|
||||
| 3 | Neil Armstrong | People | attention |
|
||||
| 3 | Jupiter | Space | reach |
|
||||
| 3 | Galileo Galilei | People | depth |
|
||||
| 4 | Albert Einstein | People | attention |
|
||||
| 4 | International Space Station | Space | depth |
|
||||
| 5 | Apollo 11 | Space | attention |
|
||||
| 5 | Charles Darwin | People | reach |
|
||||
| 6 | Solar System | Space | depth |
|
||||
|
||||
- **Coverage:** all 6 factions appear, and all 4 `shared/catalog.ts` cards are included (Moon, Periodic table, Octopus, Albert Einstein).
|
||||
- **Tutorial:** Field Guide vs Stargazers, seed 1, against the easy bot.
|
||||
- **sim-balance:** please run the 4 decks round robin first. The target is every pairing at 45–55%. If a pairing misses, retune by
|
||||
swapping home stats within a deck, never by changing the curve.
|
||||
|
||||
---
|
||||
|
||||
## 3. Board
|
||||
|
||||
- 3 **Topics** (lanes), numbered 1–3 from left to right (top to bottom in portrait).
|
||||
- Each Topic has a **stat** (attention, depth or reach) and an optional **Portal** modifier (§10.3).
|
||||
Topics have **no faction**. No v1 keyword counts factions: faction only picks the keyword.
|
||||
- Each player has at most `laneCapacity` cards per Topic (default **3**). That gives 9 slots per side,
|
||||
which caps cheap-card flooding and fits 3 cards across a 360 px phone.
|
||||
- **Topic pool:** `topicPool` is a list of Topics, each `{ id, name, stat, portal | null }`. The default
|
||||
pool has 9 Topics: 3 per stat, one plain and two with Portals. `pool_s` is the sub-list with stat
|
||||
`s`, in file order.
|
||||
- **Topic draw (exact):**
|
||||
- If `distinctStats` is true (the default): for each stat in the fixed order
|
||||
`[attention, depth, reach]`, pick `pool_s[floor(next() × len(pool_s))]`. That uses 3 `next()`
|
||||
calls. Then Fisher–Yates the 3 picks into lanes 1–3 (i = 2, 1; j = floor(next() × (i+1))), which
|
||||
uses 2 calls.
|
||||
- If `distinctStats` is false: Fisher–Yates the whole pool (i from n−1 down to 1) and take the first
|
||||
`topicCount` entries as lanes 1–3.
|
||||
- **Stats visible, Portals hidden:** every Topic's **stat** is face-up from turn 1. Its **Portal**
|
||||
modifier is face-down until the start of turn `portalReveal[i]` (default `[2, 3, 4]`). You always
|
||||
know where your card is on-topic, but not what twist a lane will get.
|
||||
|
||||
---
|
||||
|
||||
## 4. Match setup (deterministic)
|
||||
|
||||
1. The input is `{ seed: uint32, rules, players: [p0, p1] }`, and each player's input is
|
||||
`{ id, deck: CardInput[12] }`. Seat order is input order.
|
||||
2. RNG: **mulberry32(seed)**. Every random choice draws `next()` in this fixed order:
|
||||
1. shuffle p0's deck (Fisher–Yates, i from n−1 down to 1, j = floor(next() × (i+1)))
|
||||
2. shuffle p1's deck the same way
|
||||
3. draw and shuffle the Topics
|
||||
4. the initiative coin: p0 has initiative on odd turns if next() < 0.5, otherwise p1
|
||||
5. later random events (keywords only), in resolution order
|
||||
3. Each player draws `openingHand` cards (default **3**). There are no mulligans in v1
|
||||
(`mulligan: false`).
|
||||
4. **Seed fairness (hosted PvP):** commit–reveal. Each party *i* (host, p0, p1) sends
|
||||
`sha256(r_i)` for a random 32-byte `r_i`, then reveals `r_i` once all commits are in.
|
||||
`seed` = the first 4 bytes (big-endian uint32) of `sha256(r_host ‖ r_p0 ‖ r_p1)`.
|
||||
The host still relays the hidden plans, so hosted PvP trusts the host not to leak them.
|
||||
Local and bot matches use any seed.
|
||||
|
||||
---
|
||||
|
||||
## 5. Turn structure
|
||||
|
||||
The match lasts `turns` turns (default **6**, hard cap). Each turn has these phases:
|
||||
|
||||
1. **Start**
|
||||
- Reveal any Portal scheduled for turn *t* (resolve its "on reveal").
|
||||
- Each player's energy = `energyByTurn[t-1]` + carry + `bonusEnergy`. Carry is
|
||||
min(`energyCarryMax`, unspent energy from last turn), default max **1**. Saving one energy on
|
||||
turn 2 makes a turn-3 four-drop possible: a real tempo choice.
|
||||
- Each player draws 1 card if their deck isn't empty and their hand holds fewer than `handLimit`
|
||||
(default **7**) cards. Otherwise they don't draw. This includes turn 1, so the turn-1 hand is
|
||||
3 + 1 = 4 cards.
|
||||
- Order within Start: Portal reveal, then energy, then draw. The Underdog check (step 2) comes after
|
||||
all three.
|
||||
2. **Underdog check** (mode option, `underdog: false` by default, because it can be sandbagged). When
|
||||
it's on, from turn 2, a player who leads in 0 Topics while the opponent leads in ≥ 2 gets
|
||||
**+1 energy** this turn.
|
||||
3. **Plan** (simultaneous, hidden)
|
||||
- Each player queues an ordered list of plays `(handIndex, topic)`.
|
||||
- Total cost must be ≤ their energy, and each Topic needs room on that player's side.
|
||||
- Plays can be undone freely until **Commit**. Passing is an empty commit.
|
||||
- **Hidden means nothing leaks.** While you plan, the opponent's hand count and energy don't change
|
||||
visibly. Only the bare fact "opponent is ready" (`committed`) is shown. No queue count, no spent energy.
|
||||
- The turn timer is `turnSeconds` (default **25**). On timeout, whatever is queued is committed.
|
||||
4. **Reveal (interleaved)**
|
||||
- Plays reveal **one at a time, alternating**: the initiative player's 1st, the other player's
|
||||
1st, the initiative player's 2nd, and so on. When one player runs out, the rest of the other's
|
||||
reveal in order.
|
||||
- Each card enters its Topic and its "on reveal" effect resolves at once.
|
||||
- So the order in which you queue cards matters: lead with the card you want resolved first.
|
||||
- Energy is reserved when a card is queued. A queued play that is no longer legal at reveal (the
|
||||
lane is full, or a Portal rejects it) **fizzles**: the card stays in hand and its energy is lost.
|
||||
5. **End**
|
||||
- Recompute all Topic powers (§6).
|
||||
- End-of-turn effects resolve, the initiative player's first.
|
||||
- Initiative strictly **alternates** each turn (set by the coin in §4).
|
||||
- Plans are locked before anything reveals, so initiative gives away no information. It only
|
||||
decides the order of on-reveal effects. §10 includes keywords where that order matters.
|
||||
|
||||
A typical turn is: look at the lanes, tap a card, tap a Topic (×1–3), tap Commit. That is under 10
|
||||
seconds, done with one thumb, with no dragging.
|
||||
|
||||
---
|
||||
|
||||
## 6. Power and Topic control
|
||||
|
||||
- A card's **lane power** = `power` + (`onTopicBonus[cost]` if its home stat is the Topic's stat) + `trend`
|
||||
+ keyword and Portal modifiers. It is never below 0.
|
||||
- A player's **Topic power** = the sum of their cards' lane power in that Topic.
|
||||
- A player **leads** a Topic if their Topic power is strictly greater than the opponent's.
|
||||
- **Consensus tie-break:** if the powers are equal and > 0, the player with more **on-topic** cards
|
||||
there leads. If that is also equal, nobody leads. 0–0 has no leader.
|
||||
|
||||
---
|
||||
|
||||
## 7. Win conditions and tie-breaks
|
||||
|
||||
**Scoring** happens after the last turn's End phase (§5.5): every end-of-turn effect, including
|
||||
the last turn's, and every "at scoring" Portal resolves **before** Topics are judged. Then:
|
||||
1. The player who leads **more Topics** wins (2–1, 2–0, 1–0 and 3–0 all count).
|
||||
2. If they lead the same number of Topics: the higher **total power across all Topics** wins.
|
||||
3. If that is also equal: the match is a **draw**.
|
||||
|
||||
**Concede:** a player can concede at any time, and the opponent wins at once. A player who misses
|
||||
`afkTurns` timeouts in a row (default **2**) with nothing queued concedes.
|
||||
|
||||
---
|
||||
|
||||
## 8. Degenerate lines and why they fail (for the critic)
|
||||
|
||||
| Line | Why it isn't dominant |
|
||||
|---|---|
|
||||
| All-famous (all max-stat) deck | It becomes an all-cost-5/6 deck with four dead early turns. Cheap cards are more efficient **per energy**, expensive cards **per card**, and only 9 cards are seen per match (3 + 6 draws). So a pure cost-5/6 deck is **weak by design**: **BALANCE.md v1: 15%**, and no lever (power curve, energy ramp) fixes it without breaking curve or swarm decks. There is no hard deck rule; the deck builder warns below 4 cards of cost ≤ 2, and every starter is curve-shaped (§2.1). **Target met:** a **top-heavy curve** (half the deck at cost 4 or more) wins **57%** (target ≥ 40%). `energyByTurn [2..7]` was rejected for v1.1: it lifts heavy decks but kills swarm (20%). |
|
||||
| All-cheap flood (cost 1–2) | Weak by design: only 9 slots and 9 cards seen. **BALANCE.md v1: 2%** (critic's sim 7–11%). Every lever that revives it breaks curve decks (sweep in BALANCE.md). viral (base +1, v1.1) is its consolation, not its fix. |
|
||||
| All one faction | No v1 keyword scales with faction count. `factionSynergyCap` is reserved for modes. Culture, the largest pool, splits over three keywords by home stat (§10.1), so it has no single keyword to stack. |
|
||||
| Owning NFTs buys power (pay-to-win) | Power depends only on cost (§1.3), and cost follows a fixed curve. **BALANCE.md v1.1 re-run (real `RULESET_V1_1`):** each starter deck averages **52–53%** overall. A realistic owned deck from `card-sample.json` wins **42–51%** against the starters (n ≈ 55 per pairing, ±13 pp). So owning cards buys variety, not power. v1.2 levers if owned decks should be a little stronger: `local.amount 2`, and `nostalgic`/`translated` `powerDelta -1` (the two strongest keywords, about +1.65 net per card). |
|
||||
| "Always play the highest-power card" | It ignores the on-topic bonus, lane capacity and the hidden Portals. **BALANCE.md v1:** the naive max-power line wins **40%** against greedy, and lookahead-lite beats greedy **60–70%**, so skill shows (target < 55%). Critic's sim: 18–21% against a smart bot. |
|
||||
| Stall or pass | Passing leaves lanes to any 1-power card. Two passing players draw. |
|
||||
| Mirror the AI | Hidden simultaneous commits: you only see the opponent's cards after you commit. |
|
||||
| Seat or initiative | Planning is simultaneous and initiative strictly alternates (each seat has it for 3 of the 6 turns). **BALANCE.md v1.1 re-run (real `RULESET_V1_1`): first player 51.2% [48.8–53.6]** (target 48–52%; v1 was 53.4%). |
|
||||
| Forged or shopped stats | They only raise cost (§1.3), the host check falls back to live stats (§1.10), and trend is capped at ±1. |
|
||||
| Inflated live pageviews | Worth at most +1, frozen at match start, and only counts for articles with ≥ 20 views a day. |
|
||||
| Swinginess | No effect may change a lane by more than 6 power or move cards between lanes in v1 (a keyword-design rule for §10). |
|
||||
|
||||
---
|
||||
|
||||
## 9. Rules config (all defaults)
|
||||
|
||||
The engine takes a `RulesConfig` object. Peer-hosted modes override it (§11). Defaults:
|
||||
|
||||
```json
|
||||
{
|
||||
"version": "1.1",
|
||||
"deckSize": 12, "maxCopiesPerPage": 2, "maxLoaners": 12,
|
||||
"openingHand": 3, "handLimit": 7, "mulligan": false,
|
||||
"turns": 6, "turnSeconds": 25, "afkTurns": 2,
|
||||
"energyByTurn": [1, 2, 3, 4, 5, 6], "energyCarryMax": 1, "bonusEnergy": 0, "underdog": false,
|
||||
"topicCount": 3, "distinctStats": true, "portalReveal": [2, 3, 4], "laneCapacity": 3,
|
||||
"topicPool": [ /* inline Topic objects {id, name, stat, portal}; default = the 9 in §10.3 */ ],
|
||||
"keywordParams": { /* per-keyword numbers, keyed by keyword id (§10) */ },
|
||||
"portalParams": { /* per-Portal numbers, keyed by Topic id (§10.3) */ },
|
||||
"costThresholds": [26, 39, 51, 63, 78],
|
||||
"powerByCost": [0, 1, 2, 4, 6, 8, 10],
|
||||
"onTopicBonus": [0, 1, 1, 2, 2, 3, 3], "vanillaBonus": 1,
|
||||
"keywordsEnabled": ["viral","rising","local","encyclopedic","nostalgic","translated"], "cultureKeyword": "home", "ownedCards": true,
|
||||
"trendUp": 25, "trendDown": -200, "trendMinDaily": 20, "uncheckedCostCap": 4,
|
||||
"factionSynergyCap": 3,
|
||||
"verifyStats": true,
|
||||
"percentiles": "card-sample-2026-11-16",
|
||||
"starterDecks": "default"
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
**What modes may vary:** every key above, plus `topicPool` contents and the starter-deck lists.
|
||||
**Fixed for all modes:** matches are off-chain and never move or burn NFTs; the RNG and its draw order
|
||||
(§4); the shape of the derivation (§1: percentile → fame → cost → power); at most one keyword per card;
|
||||
the phases of a turn (§5).
|
||||
A mode must keep `turns × turnSeconds ≤ 240` so that matches stay within 3–6 minutes.
|
||||
|
||||
---
|
||||
|
||||
## 10. Keywords *(owner: council-designer-b)*
|
||||
|
||||
**The v1 keyword set is these six, one per faction.** The ids are the ones engine-b already uses on `night/engine/keywords`.
|
||||
Topics carry only a **stat**, never a faction. Every keyword below that mentions a Topic keys off stats or board state.
|
||||
|
||||
### 10.1 Which keyword a card gets
|
||||
First rule that matches:
|
||||
1. `cost == 1` → **no keyword** (vanilla). The card gets +`vanillaBonus` power (default **1**), so a cost-1 card is 2.
|
||||
2. `"edition"` is in `keywordsEnabled` (off by default) and the deck holds another card with the same `pageId` → **edition**.
|
||||
3. If the faction is **Culture** and `cultureKeyword` is `"home"` (v1.1 default) → the keyword for its **home stat**:
|
||||
attention → **viral**, depth → **encyclopedic**, reach → **translated**. (`"faction"` gives v1 behaviour: every Culture card is viral.)
|
||||
4. Otherwise → the card's **faction keyword** from 10.2.
|
||||
|
||||
In steps 3–4, if the chosen keyword isn't in `keywordsEnabled`, the card is vanilla, *without* `vanillaBonus`.
|
||||
*Why step 3:* Culture is about half of all owned cards. Without it, owned decks are half viral and see only 2 of the 6 keywords.
|
||||
|
||||
Rarity plays no part here (it's cosmetic, §1.7). Keywords don't lower power, and v1 has no per-keyword power deltas.
|
||||
If sim shows that a keyword is worth more than about 1 power on average, sim-balance sets `keywordParams.<id>.powerDelta` (default 0, range −3 to 0).
|
||||
|
||||
### 10.2 Keyword list (v1)
|
||||
|
||||
| Faction | id (card word) | Trigger | Reminder text | Cap | Order-sensitive? |
|
||||
|---|---|---|---|---|---|
|
||||
| Culture | **viral** | On reveal | +1 power, plus +1 for each other card you revealed earlier this turn. | +3 | yes: your queue order |
|
||||
| Nature | **rising** | End of turn | +1 power. | +2 total | no |
|
||||
| People | **local** | Ongoing | +1 power while on-topic (the Topic's stat is its home stat). | +1 | no |
|
||||
| Science | **encyclopedic** | On reveal | +2 power if you have no other cards here. | +2 | **yes: interleaving** |
|
||||
| History | **nostalgic** | On reveal | +2 power if you are losing here. | +2 | **yes: interleaving** |
|
||||
| Space | **translated** | On reveal | +1 power to your most recently revealed card in each *other* Topic. | +2 | yes |
|
||||
|
||||
Why this set: every keyword is one line and one trigger, and only adds power. The largest swing is +2 on one card,
|
||||
so no lane moves by more than 3 from a keyword (viral at its cap). Nothing scales with faction count, so a mono-Culture deck gets no
|
||||
consistency edge (`factionSynergyCap` is unused). Viral rewards wide turns, and Culture cards are spread over three keywords (§10.1 step 3).
|
||||
Three keywords (encyclopedic, nostalgic, translated) react to the interleaved reveal (§5.4), so initiative and queue order matter.
|
||||
|
||||
Precise rules (for engine-b):
|
||||
- **On reveal** resolves the moment the card enters its Topic, and sees every card revealed before it (both players,
|
||||
including earlier reveals this turn). The bonuses it grants are permanent counters.
|
||||
- **Ongoing** is a condition, recalculated whenever power is read.
|
||||
- **End of turn** resolves in §5.5 order: the initiative player's cards first, then Topic 1→3, then reveal order.
|
||||
- **viral:** gain = min(`base` + `amount` × N, `cap`), where N = the owner's cards revealed earlier in *this* turn's Reveal phase, in any Topic.
|
||||
Cards that went back to hand don't count. v1.1: base 1, amount 1, cap 3 (v1 was base 0, cap 2).
|
||||
- **rising:** stops after it has gained +2 in total.
|
||||
- **local:** "on-topic" is exactly the §1.4/§6 condition. It's simply an extra +1 on top of `onTopicBonus`.
|
||||
- **encyclopedic:** with `sides: 1` (v1.1 default), "no other cards here" means **your** side of this Topic is empty, apart from this card,
|
||||
when it reveals; the opponent's cards don't matter. `sides: 2` is v1 (both sides empty).
|
||||
- **nostalgic:** "losing here" means the opponent's Topic power here is strictly greater than yours, counted just *before* this card is added.
|
||||
The consensus tie-break doesn't count: a tie is not losing.
|
||||
- **translated:** "most recently revealed" means the highest global reveal sequence number among your cards in that Topic. Topics where you have no card are skipped.
|
||||
- No v1 keyword uses the RNG. §4's "later random events" slot stays empty in v1.
|
||||
|
||||
**Already in code, disabled by default (`keywordsEnabled` excludes them; for modes only):**
|
||||
- **edition:** +2 for each other copy of this `pageId` on your side.
|
||||
- **obscure:** the opponent sees it face down until the end of the match.
|
||||
- **wildcard:** its home stat becomes the Topic's stat on reveal.
|
||||
|
||||
These are engine-b's existing implementations. The faction-based versions of `local` and `wildcard`, and the token version of `viral`, are
|
||||
**replaced** by the definitions above.
|
||||
|
||||
**`keywordParams` defaults** (keyed by keyword id; modes may change them within the §11 ranges):
|
||||
```json
|
||||
{ "viral": {"base": 1, "amount": 1, "cap": 3, "powerDelta": 0}, "rising": {"amount": 1, "cap": 2, "powerDelta": -1},
|
||||
"local": {"amount": 1, "powerDelta": 0}, "encyclopedic": {"amount": 2, "sides": 1, "powerDelta": 0},
|
||||
"nostalgic": {"amount": 2, "powerDelta": 0}, "translated": {"amount": 1, "powerDelta": 0},
|
||||
"edition": {"amount": 2, "powerDelta": 0}, "obscure": {"powerDelta": 0}, "wildcard": {"powerDelta": 0} }
|
||||
```
|
||||
End-of-turn effects on the last turn resolve **before** scoring (§7).
|
||||
|
||||
**v1.2 candidates** (not in v1.1; decide on a larger run, per BALANCE.md's v1.1 re-run): the keyword values are still uneven:
|
||||
translated +1.64 and nostalgic +1.69 per card vs local +0.69 (critic's target was ±0.3). The starter decks stay even only because each one
|
||||
pairs a strong keyword with a weak one. The first levers are `nostalgic.powerDelta -1` and `translated.powerDelta -1`, plus `local.amount 2`
|
||||
if owned decks stay under 45% against Headliners. Both are config only.
|
||||
|
||||
### 10.3 Portals (Topic modifiers) and the default Topic pool
|
||||
Each Topic has `{ id, name, stat, portal | null }`. The default `topicPool` has 9 Topics, one plain and two with
|
||||
Portals for each stat. A Portal applies from the moment its Topic is revealed (§3), except where it says otherwise.
|
||||
|
||||
| Topic | Stat | Portal rule |
|
||||
|---|---|---|
|
||||
| Current Events | attention | – |
|
||||
| Main Page | attention | At scoring, each card here gets +1 power. |
|
||||
| Trending | attention | Trend arrows (§1.6) count double here (±2). |
|
||||
| Archive | depth | – |
|
||||
| Featured Article | depth | At end of the match, the player with the single highest-power card here gets +2 Topic power here. If the highest card power here is tied (between the two players), nobody gets the bonus. |
|
||||
| Stub | depth | Lane capacity here is 2 per player. |
|
||||
| Translations | reach | – |
|
||||
| Interwiki | reach | +1 Topic power here for a player who has at least one card in all 3 Topics. |
|
||||
| Disambiguation | reach | Every card here counts as on-topic, whatever its home stat. |
|
||||
|
||||
As data: `portal = { kind: "scoringCardBonus", amount: 1 } | { kind: "trendMultiplier", factor: 2 } |
|
||||
{ kind: "highestCardBonus", amount: 2 } | { kind: "laneCapacity", value: 2 } | { kind: "spreadBonus", amount: 1 } |
|
||||
{ kind: "allOnTopic" }`. Modes may add Topics with these kinds, using new numbers, but not new kinds (engine code).
|
||||
|
||||
**`portalParams` defaults** (keyed by Topic id): `{ "main-page": {"amount": 1}, "trending": {"factor": 2},
|
||||
"featured-article": {"amount": 2}, "stub": {"value": 2}, "interwiki": {"amount": 1} }`. Disambiguation has no numbers.
|
||||
Topic ids are the names in kebab-case: `current-events, main-page, trending, archive, featured-article, stub,
|
||||
translations, interwiki, disambiguation`. The UI shows each Portal's one-line rule **on the lane itself**, not behind a tap.
|
||||
|
||||
---
|
||||
|
||||
## 11. Peer-hosted modes *(owner: council-designer-b)*
|
||||
|
||||
A **mode** is data, published by a node operator and run by the match host:
|
||||
```json
|
||||
{
|
||||
"id": "blitz", // [a-z0-9-]{3,32}, unique per host
|
||||
"name": "Blitz", "description": "Four quick turns.", // ≤ 40 and ≤ 280 chars, plain text
|
||||
"rules": { "turns": 4, "energyByTurn": [2, 3, 4, 5], "portalReveal": [1, 1, 2], "deckSize": 10 },
|
||||
"topicPool": [ /* optional: Topic objects (10.3); default if omitted */ ],
|
||||
"starterDecks": [ /* optional: lists of loaner pageIds */ ]
|
||||
}
|
||||
```
|
||||
- `rules` is a **partial** `RulesConfig` (§9) merged over the defaults. Unknown keys are rejected.
|
||||
- **Validation** (modes owns the code; these are the limits). If any check fails, the mode is refused:
|
||||
|
||||
| Key | Allowed |
|
||||
|---|---|
|
||||
| `turns` | 3–8, and `turns × turnSeconds ≤ 240` |
|
||||
| `energyByTurn` | length = `turns`, each 0–10 |
|
||||
| `bonusEnergy` | 0–3 |
|
||||
| `portalReveal` | length = `topicCount`, each 1..`turns`, non-decreasing |
|
||||
| `topicCount` | 1–5; `distinctStats` only if ≤ 3 |
|
||||
| `laneCapacity` | 1–6 |
|
||||
| `deckSize` | 6–20; `maxCopiesPerPage` 1–4; `maxLoaners` 0..`deckSize` |
|
||||
| `openingHand` | 0–6; `handLimit` 1–10 |
|
||||
| `turnSeconds` | 10–60; `afkTurns` 1–5 |
|
||||
| `costThresholds` | 5 strictly ascending integers in 0–100 |
|
||||
| `powerByCost` | 7 integers in 0–20, non-decreasing from index 1 |
|
||||
| `onTopicBonus` (7 entries), `vanillaBonus` | 0–5 each |
|
||||
| `trendUp` / `trendDown` | 0–200 / −200–0 |
|
||||
| `factionSynergyCap` | 0–6 |
|
||||
| `keywordsEnabled` | any subset of the 9 implemented ids (the 6 v1 defaults + edition, obscure, wildcard); a card whose keyword is disabled is vanilla, *without* `vanillaBonus` |
|
||||
| `keywordParams`, `portalParams` | only the keys listed in §10 / §10.3; amounts and caps 0–6, `viral.base` 0–3, `encyclopedic.sides` 1–2, `powerDelta` −3–0 |
|
||||
| `cultureKeyword` | `"home"` or `"faction"` |
|
||||
| `verifyStats` | the host may only turn this off for modes that use only loaners (`maxLoaners == deckSize` and owned cards banned) |
|
||||
| `topicPool` | 3–20 Topics, Portal kinds only from 10.3 |
|
||||
|
||||
- **Identity:** `modeHash` = SHA-256 of the canonical JSON (sorted keys, no whitespace) of the *merged* rules
|
||||
plus the topicPool. A match record holds `{ modeHash, seed, both decks' CardInputs, both players' commit lists }`,
|
||||
and that is enough to replay it exactly.
|
||||
- **What modes can't change** is the "Fixed for all modes" list in §9. Modes also can't add keywords or Portal kinds, or
|
||||
stake, move or burn NFTs.
|
||||
|
||||
Example modes (good defaults for operators to publish):
|
||||
| Mode | Overrides | Feel |
|
||||
|---|---|---|
|
||||
| **Blitz** | `turns 4`, `energyByTurn [2,3,4,5]`, `portalReveal [1,1,2]`, `deckSize 10`, `turnSeconds 20` | about 2 minutes |
|
||||
| **Deep Cuts** | `topicPool`: only the 3 depth Topics, `distinctStats false` | rewards long, obscure articles |
|
||||
| **Loaner League** | `maxLoaners 12` and owned cards banned (`"ownedCards": false`, a new boolean key, default true) | fully level, for tournaments |
|
||||
| **Big Board** | `topicCount 5`, `distinctStats false`, `portalReveal [1,2,3,4,5]`, `laneCapacity 3` | win 3 of 5; **tablet/desktop only** (5 × 3 slots won't fit a 360 px phone) |
|
||||
| **No Keywords** | `keywordsEnabled []`, `onTopicBonus [0,3,3,3,3,3,3]` | Top Trumps–style tutorial mode |
|
||||
|
||||
---
|
||||
|
||||
## 12. Worked example match *(owner: council-designer-b)*
|
||||
|
||||
**Ruleset for this example: v1.0** (the golden test pins it): `cultureKeyword "faction"`, `viral {base 0, cap 2}`,
|
||||
`encyclopedic {sides 2}`, `rising.powerDelta 0`; everything else as §9. *(The v1.1 numbers are in §12.1.)*
|
||||
|
||||
These are the §1–9 rules as of this PR:
|
||||
- `powerByCost [0,1,2,4,6,8,10]`, `onTopicBonus [0,1,1,2,2,3,3]`, `vanillaBonus 1`
|
||||
- `laneCapacity 3`, `energyCarryMax 1`, interleaved reveals, alternating initiative, `portalReveal [2,3,4]`
|
||||
- `underdog false`, no trend arrows
|
||||
|
||||
The derived cards are given directly (the §1 output), so the test needs no percentile table.
|
||||
Topics: **T1 Archive (depth, plain)**, **T2 Main Page (attention; Portal revealed turn 3; at scoring, each card here gets +1)**,
|
||||
**T3 Translations (reach, plain; revealed turn 4)**. Ana (p0) has initiative on odd turns and Bo (p1) on even turns.
|
||||
|
||||
| Player | Card | Faction | Cost | Base | Home | Keyword |
|
||||
|---|---|---|---|---|---|---|
|
||||
| Ana | Octopus | Nature | 1 | 2 | depth | – (vanilla) |
|
||||
| Ana | Moon | Space | 2 | 2 | reach | translated |
|
||||
| Ana | Coral reef | Nature | 2 | 2 | depth | rising |
|
||||
| Ana | Albert Einstein | People | 4 | 6 | attention | local |
|
||||
| Ana | Ancient Rome | History | 5 | 8 | depth | nostalgic |
|
||||
| Ana | Library of Alexandria | History | 4 | 6 | depth | nostalgic |
|
||||
| Ana | Periodic table | Science | 3 | 4 | depth | encyclopedic |
|
||||
| Bo | Haiku | Culture | 1 | 2 | attention | – (vanilla) |
|
||||
| Bo | Mars | Space | 2 | 2 | reach | translated |
|
||||
| Bo | Jazz | Culture | 2 | 2 | attention | viral |
|
||||
| Bo | Pop music | Culture | 4 | 6 | attention | viral |
|
||||
| Bo | Jupiter | Space | 5 | 8 | reach | translated |
|
||||
| Bo | Fern | Nature | 3 | 4 | depth | rising |
|
||||
| Bo | Mona Lisa | Culture | 3 | 4 | attention | viral |
|
||||
|
||||
Topic power is written as **Ana–Bo** after End of turn. Energy is "available / spent".
|
||||
|
||||
| Turn | Init | Energy Ana / Bo | Reveals, in interleaved order | T1 | T2 | T3 |
|
||||
|---|---|---|---|---|---|---|
|
||||
| 1 | Ana | 1/1, 1/1 | Ana Octopus → T1: 2 +1 on-topic = **3**. Bo Haiku → T2: 2+1 = **3** | 3–0 | 0–3 | 0–0 |
|
||||
| 2 | Bo | 2/2, 2/0 | Bo passes (to carry 1). Ana Moon → T3: 2+1 = 3. translated: Octopus +1 → 4 | 4–0 | 0–3 | 3–0 |
|
||||
| 3 | Ana | 3/2, **4**/4 | Main Page Portal revealed. Ana Coral reef → T1: 2+1 = 3. Bo Mars → T3: 2+1 = 3, translated: Haiku +1 → 4. Bo Jazz → T2: 2+1 = 3, viral (Mars earlier) +1 → 4. End: rising Coral reef → 4 | 8–0 | 0–8 | 3–3 (tie; on-topic 1–1, so no leader) |
|
||||
| 4 | Bo | **5**/4, 4/4 | Bo Pop music → T3: 6 (off-topic), viral +0. Ana Einstein → T2: 6+2 on-topic, local +1 = **9**. End: rising Coral reef → 5 (cap reached) | 9–0 | 9–8 | 3–9 |
|
||||
| 5 | Ana | **6**/5, 5/5 | Ana Ancient Rome → T3: 8 (off-topic). nostalgic: losing 3–9, so +2 → **10**. Bo Jupiter → T1: 8 (off-topic). translated: Jazz → 5 (T2), Pop music → 7 (T3) | 9–8 | 9–9: **Bo leads** (consensus: on-topic 1 vs 2) | 13–10 |
|
||||
| 6 (last) | Bo | **7**/7, 6/6 | Bo Fern → T1: 4+2 = 6. Ana Library → T1: 6+2 = 8. nostalgic: losing 9–14, so +2 → **10**. Bo Mona Lisa → T2: 4+2 = 6, viral (Fern earlier) +1 → 7. Ana Periodic table → T2: 4 (off-topic), encyclopedic: no (cards here). End: rising Fern → 7. Scoring: Main Page +1 per card in T2 | **19–15** | **15–19** | **13–10** |
|
||||
|
||||
Final card values:
|
||||
- **T1:**
|
||||
- Ana: Octopus 4 + Coral reef 5 + Library 10 = 19.
|
||||
- Bo: Jupiter 8 + Fern 7 = 15.
|
||||
- **T2:** each card +1 from Main Page.
|
||||
- Ana: Einstein 10 + Periodic table 5 = 15.
|
||||
- Bo: Haiku 5 + Jazz 6 + Mona Lisa 8 = 19.
|
||||
- **T3:**
|
||||
- Ana: Moon 3 + Ancient Rome 10 = 13.
|
||||
- Bo: Mars 3 + Pop music 7 = 10.
|
||||
|
||||
**Ana wins 2–1.** Three moments show the v1 mechanics:
|
||||
- **Carry-over:** Bo passed on turn 2 to afford two plays on turn 3 (4 energy).
|
||||
- **Consensus:** T2 at 9–9 after turn 5 went to Bo, who had two on-topic attention cards to Ana's one.
|
||||
- **Interleaving decides the match:** on turn 6 Bo had initiative, so Fern revealed before Library. Ana was then losing T1 (9 vs 14) and nostalgic fired (+2).
|
||||
If Ana had revealed first, she'd have been ahead 9–8, nostalgic would not have fired, and T1 would have been 17–15. Ana still wins that lane, but by 2 instead of 4.
|
||||
|
||||
**Golden test for engine-b:**
|
||||
- **Inject:** the Topic order, the opening hands and the draw order directly, with each player's commit list per turn as in the table. The queue order within a turn is as listed.
|
||||
- **Expected final Topic powers:** `T1 19–15, T2 15–19, T3 13–10`. Winner: p0, by 2 Topics to 1.
|
||||
- **Also assert:**
|
||||
- after turn 5, T2 is a 9–9 tie with Bo leading by consensus
|
||||
- Ana's carried energy is 1 at the start of turns 4, 5 and 6
|
||||
- Bo's carried energy is 1 at the start of turn 3
|
||||
|
||||
### 12.1 The same match under the v1.1 ruleset
|
||||
Same cards, Topics, hands and commit lists; ruleset = §9 defaults (v1.1: `viral {base 1, cap 3}`, `encyclopedic {sides 1}`,
|
||||
`rising.powerDelta -1`, `cultureKeyword "home"`). The example's Culture cards (Jazz, Pop music, Mona Lisa) are attention-home, so they stay viral.
|
||||
Energy and carry are unchanged.
|
||||
|
||||
What changes:
|
||||
- **rising −1:** Coral reef is 1 base and ends at 1+1+2 = **4**; Fern is 3 base and ends at 3+2+1 = **6**.
|
||||
- **viral base 1:** Jazz +2 (Mars earlier), Pop music +1 (base only), Mona Lisa +2 (Fern earlier).
|
||||
- **nostalgic still fires** for Library (Ana is losing T1 8–13 just before it). **encyclopedic still doesn't** (Einstein is already on Ana's side of T2).
|
||||
|
||||
| After turn | T1 | T2 | T3 |
|
||||
|---|---|---|---|
|
||||
| 1 | 3–0 | 0–3 | 0–0 |
|
||||
| 2 | 4–0 | 0–3 | 3–0 |
|
||||
| 3 | 7–0 | 0–9 | 3–3 |
|
||||
| 4 | 8–0 | 9–9 | 3–10 |
|
||||
| 5 | 8–8: **Ana leads** (consensus: on-topic 2 vs 0) | 9–10 | 13–11 |
|
||||
| 6, before scoring | 18–14 | 13–18 | 13–11 |
|
||||
| **final** (Main Page +1 per card in T2) | **18–14** | **15–21** | **13–11** |
|
||||
|
||||
**Ana still wins 2–1.** The moments in v1.1:
|
||||
- **Carry-over:** unchanged.
|
||||
- **Consensus:** moves to **T1 after turn 5** (8–8). Ana has two on-topic depth cards there (Octopus, Coral reef) and Bo has only the off-topic Jupiter.
|
||||
- **Interleaving:** unchanged in kind. If Ana had revealed Library before Fern, T1 would have been 8–8 at that moment, a tie is not losing,
|
||||
so nostalgic would not fire and T1 would end 16–14.
|
||||
|
||||
**v1.1 golden test:** expected `lanePower [[18,14],[15,21],[13,11]]`, winner p0. Also assert the T1 8–8 consensus lead for p0 after turn 5.
|
||||
(Cross-checked by council-critic with the #27 engine, `tower-plus:scratchpad/critic/golden11.ts`, and by hand by designer-b.)
|
||||
@@ -0,0 +1,232 @@
|
||||
# WikiDeck game engine API (v1)
|
||||
|
||||
**Owner:** engine-a (core and API) and engine-b (keywords, card derivation, tests). Issue: claude/wikideck#3.
|
||||
**Rules:** `docs/game/DESIGN.md` v1 ("Edit War", as frozen in PR #17 @ cf2fceb). Where this file and DESIGN.md disagree, raise it on #3.
|
||||
**Stability:** UI, simulation and modes build against this file. Any change to a name or shape below is
|
||||
announced on #3 before it merges.
|
||||
|
||||
The engine is a pure TypeScript library in `shared/game/`:
|
||||
- It does no I/O and has no clocks: no `Date.now()`, no `Math.random()`.
|
||||
- It imports nothing from `server/` or `src/`.
|
||||
- It runs entirely **off-chain**. A match never reads, moves, locks or burns an NFT.
|
||||
- It is deterministic: the same `(ruleset, decks, seed, actions)` always gives the same state, byte for byte.
|
||||
|
||||
**Import only from `shared/game/index.ts`.**
|
||||
|
||||
```ts
|
||||
import { createMatch, legalActions, applyAction, isOver, result, viewFor,
|
||||
serialize, deserialize, replay, DEFAULT_RULESET, parseRuleset, validateDeck,
|
||||
starterDeck, previewPool, type MatchState, type Action, type GameCard } from '../shared/game/index.ts';
|
||||
```
|
||||
|
||||
## 1. Lifecycle
|
||||
|
||||
```ts
|
||||
let state = createMatch(DEFAULT_RULESET, [deck0, deck1], seed); // turn 1, planning
|
||||
while (!isOver(state)) {
|
||||
// Each seat (in any order, any interleaving) queues plays, then commits.
|
||||
const actions = legalActions(state, seat); // play / undo / commit
|
||||
state = applyAction(state, chosen); // returns a NEW state
|
||||
// When both seats have committed, the turn resolves inside applyAction.
|
||||
}
|
||||
const r = result(state); // { winner: 0 | 1 | null, reason, topicsLed, lanePower, totalPower, turns }
|
||||
```
|
||||
|
||||
| Function | Description |
|
||||
|---|---|
|
||||
| `createMatch(ruleset, [deck0, deck1], seed: number \| string): MatchState` | Validates the ruleset (`parseRuleset`) and both decks (`validateDeck`), then performs DESIGN §4 setup and turn-1 start. A `seed` is a uint32. A string is hashed with FNV-1a (`seedFromString`). Throws `ZodError` for a bad ruleset and `IllegalActionError` for a bad deck. |
|
||||
| `legalActions(state, seat): Action[]` | Lists every `play` (each card × each lane it can legally go into), every `undo`, and `commit`. Returns `[]` once the seat has committed or the match is over. It never lists `concede` (always legal while the match is running) or `timeout` (host only). |
|
||||
| `applyAction(state, action): MatchState` | Pure: the input is never mutated. Throws `IllegalActionError` if the action is illegal. |
|
||||
| `actionProblem(state, action): string \| null` | Explains why an action is illegal, without throwing. Use it for UI hints and for validating client input on a host. |
|
||||
| `isOver(state)` / `result(state)` | `result` is `null` while the match is running. |
|
||||
| `viewFor(state, seat): PlayerView` | The **hidden-information view**. Send only this to clients and AIs, never `MatchState`, because a `MatchState` contains both deck orders and the RNG state. |
|
||||
| `serialize(state): string` / `deserialize(json): MatchState` | Lossless JSON. `MatchState` is plain data. |
|
||||
| `replay(ruleset, decks, seed, actions): MatchState` | Rebuilds a match from its inputs. `state.actions` records every action applied, so a host can store `(ruleset, decks, seed, actions)` and verify a result later. |
|
||||
| `validateDeck(ruleset, cards): string[]` | Returns the list of problems; empty means the deck is legal. |
|
||||
| `cardPower(state, cardInPlay)`, `lanePower(state, lane)`, `laneLeader(state, lane)`, `topicsLed(state)` | Power queries (DESIGN §6). `laneLeader` and `topicsLed` apply the consensus tie-break. |
|
||||
| `scoringPower(state, lane)` | Lane power plus revealed "at scoring" Portals (§7). `result().lanePower` uses this. |
|
||||
| `laneCapacity(state, lane)` | Per-seat capacity of a lane. A Portal such as Stub may override it. |
|
||||
| `isOnTopic(state, cardInPlay)` | §1.4/§6 on-topic test, including Disambiguation. |
|
||||
| `STARTER_DECKS`, `starterDeckById(id, rules?)` | The 4 DESIGN §2.1 starter decks (`stargazers`, `field-guide`, `headliners`, `pioneers`), derived through `deriveCard` with the given rules (a `Ruleset` works). **Use these for new players.** |
|
||||
| `starterDeck(seed)` | Older placeholder loaner deck (seeded, 2 per cost from `STARTER_POOL`). Kept for tests and tools; not a §2.1 starter deck. |
|
||||
| `previewPool(rules?)` | The 20 frozen `docs/game/starter-cards.json` loaners (council-data), derived via §1 against the `card-sample-2026-11-16` percentile table. For loaner slots and draft modes. |
|
||||
| `deriveCard(input, table, rules?)`, `deriveDeck(inputs, table, rules?)` | DESIGN §1 + §10.1: `CardInput` → `GameCard`. **Hosts only**: run on host-frozen, plausibility-checked inputs, never on client JSON. A `Ruleset` can be passed as `rules`. |
|
||||
| `placeCard(state, seat, lane, card)`, `revealPortal(state, lane)` | Test helpers for building boards by hand. |
|
||||
|
||||
## 2. Actions
|
||||
|
||||
```ts
|
||||
type Action =
|
||||
| { type: 'play'; player: 0 | 1; cardId: string; lane: number } // queue a card from hand (hidden)
|
||||
| { type: 'undo'; player: 0 | 1; cardId: string } // un-queue it (refunds energy)
|
||||
| { type: 'commit'; player: 0 | 1 } // lock in this turn (empty = pass)
|
||||
| { type: 'timeout'; player: 0 | 1 } // HOST ONLY: turn timer expired
|
||||
| { type: 'concede'; player: 0 | 1 };
|
||||
```
|
||||
|
||||
**Queuing a play**
|
||||
- `play` reserves the card's cost from this turn's energy. It checks the energy, the lane's room (cards already in the lane plus queued plays must stay under `laneCapacity(state, lane)`), and, once the Portal is revealed, whether it accepts the card (`canPlay`).
|
||||
- Your plays reveal in **your queue order**, interleaved with the opponent's (see below).
|
||||
- `undo` and new plays are allowed until the seat sends `commit`.
|
||||
|
||||
**Resolving a turn**
|
||||
- When both seats have committed, `applyAction` resolves the turn (DESIGN §5.4–5.5):
|
||||
1. Carry is set: min(`energyCarryMax`, energy not reserved by queued plays). Energy spent on a play that later fizzles is still spent.
|
||||
2. **Interleaved reveal:** the initiative seat's 1st play, then the other seat's 1st, then the initiative seat's 2nd, and so on. When one seat runs out, the other's remaining plays reveal in order. Each card gets the next global `seq` number, and its on-reveal effects (keyword, then Portal) run at once.
|
||||
3. End-of-turn effects run: the initiative seat's cards first, then lanes left→right, then `seq` order.
|
||||
4. On the last turn, scoring follows (§7). Otherwise the next turn starts:
|
||||
- initiative **alternates**
|
||||
- any Portal scheduled by `portalReveal` is revealed
|
||||
- energy = `energyByTurn[t-1]` + carry + `bonusEnergy`
|
||||
- each seat draws
|
||||
- the underdog bonus applies (only if `underdog` is on)
|
||||
- **A play that is illegal at reveal** (the lane filled up, or a Portal rejects the card) fizzles. The card stays in hand and its energy is lost. A `fizzle` log event records it.
|
||||
|
||||
**Timeouts.** `timeout` is how a host enforces `turnSeconds`. It commits whatever is queued. A timeout with an empty queue counts toward `afkTurns`. When that count is reached, the seat concedes and the result has `reason: 'afk'`. An ordinary `commit` resets the count.
|
||||
|
||||
**Seat ownership.** The engine does not authenticate anyone. The host must check that the seat in `action.player` is the caller's.
|
||||
|
||||
## 3. Cards
|
||||
|
||||
```ts
|
||||
interface GameCard {
|
||||
cardId: string; // unique within a deck: the NFT card hash, or `loaner:<pageId>:<n>`
|
||||
pageId: number | null; // at most maxCopiesPerPage cards share a pageId; null (unpinned loaners) → counted per cardId
|
||||
title: string;
|
||||
faction: 'Space' | 'Nature' | 'People' | 'Science' | 'History' | 'Culture';
|
||||
rarity: 'Common' | 'Rare' | 'Epic' | 'Legendary'; // cosmetic in v1
|
||||
cost: number; // 0–6 (uncheckedCostCap already applied by derivation)
|
||||
power: number; // 0–30, base power
|
||||
home: 'attention' | 'depth' | 'reach';
|
||||
trend: -1 | 0 | 1; // frozen at match start
|
||||
keyword: string | null; // an id in KEYWORDS
|
||||
source: 'owned' | 'loaner';
|
||||
check?: 'verified' | 'unverified' | 'unchecked' | 'loaner'; // host plausibility result (§1.10), for logs
|
||||
}
|
||||
```
|
||||
|
||||
- **The engine takes already-derived cards and never reads raw stats.** The council asked for this, because snapshot stats are self-reported (#1, critic brief A.1).
|
||||
- Derivation (DESIGN §1 and §10.1: percentile → fame → cost → power, home, trend, keyword and vanillaBonus) lives in `shared/game/derive.ts`, which engine-b owns. Hosts run it on host-frozen, plausibility-checked inputs before calling `createMatch`.
|
||||
- `CardInput = { cardId, pageId | null, title, category, rarity, snapshot: { stats }, live: { trendPercent, dailyAverage }, check, pinned? }`. `pinned: { cost, home, faction }` replaces §1.1–1.5 **only** when `check === 'loaner'`. `check === 'unchecked'` caps cost at `uncheckedCostCap` (home and fame are kept).
|
||||
- **Never build `GameCard`s from client JSON.** `validateDeck` only checks shapes and ranges; a client could send cost 1 / power 30. Constructed modes must re-derive on the host.
|
||||
- Both seats can hold the same loaner `cardId`. The engine keys per seat, so UIs should key cards by `owner + cardId`.
|
||||
- Modes may adjust `GameCard` fields such as `power` before `createMatch`. The engine does not re-derive them.
|
||||
- **`check` and `pinned` are host decisions, not player input.** Build loaner inputs only from shipped data (`STARTER_DECKS`,
|
||||
`previewPool()`, `LOANER_SNAPSHOTS`), and set `check` for owned cards from the host's own §1.10 check. Otherwise a client could
|
||||
send `check: 'loaner', pinned: {cost: 1, …}` for any card.
|
||||
- **`obscure` leaks in v1.** `viewFor` does not mask Obscure cards yet. Modes must not put `obscure` in `keywordsEnabled` until it does.
|
||||
- A keyword that isn't in `ruleset.keywordsEnabled` never runs. Derivation is responsible for not giving that card `vanillaBonus`.
|
||||
- Lane power = `power` + `bonus` + `trend` + `onTopicBonus[cost]` if on-topic + ongoing keyword and Portal effects, floored at 0.
|
||||
|
||||
## 4. Ruleset
|
||||
|
||||
`Ruleset` holds the DESIGN §9 keys, **flat** (nothing deeper than one level, apart from `topicPool` entries and the param tables).
|
||||
- `parseRuleset(unknown)` is a **strict** zod parse: unknown keys are rejected and every number is bounded, so any ruleset that passes terminates within `turns` turns.
|
||||
- Modes merge overrides onto `DEFAULT_RULESET` and then call `parseRuleset`.
|
||||
|
||||
Notes on the §9 keys:
|
||||
- `topicPool` is inline `TopicDef[] = { id, name, stat, portal: PortalId | null }[]`. `DEFAULT_TOPIC_POOL` is the 9 Topics of §10.3. A Portal id is one of `PORTAL_IDS` (`main-page, trending, featured-article, stub, interwiki, disambiguation`).
|
||||
- `keywordParams[keywordId]` holds keyword numbers; keys must be in `KEYWORD_IDS`. `portalParams[topicId]` holds Portal numbers, and falls back to `portalParams[portalId]`, so a mode can add a Topic that reuses a Portal kind with new numbers.
|
||||
- `keywordsEnabled` ⊆ `KEYWORD_IDS` (the 6 v1 ids plus `edition`, `obscure` and `wildcard`).
|
||||
- `mulligan` must be `false`. Mulligans are not implemented in v1.
|
||||
- `percentiles`, `starterDecks`, `trendUp/Down`, `trendMinDaily`, `uncheckedCostCap`, `vanillaBonus`, `costThresholds`, `powerByCost`, `verifyStats` and `factionSynergyCap` are for derivation and the host. The core loop doesn't read them.
|
||||
|
||||
Validation also enforces:
|
||||
- `turns × turnSeconds ≤ 240`
|
||||
- `energyByTurn.length ≥ turns`
|
||||
- `portalReveal.length = topicCount`
|
||||
- `openingHand ≤ handLimit`
|
||||
- `costThresholds` in ascending order
|
||||
- with `distinctStats`, `topicCount == 3` and the pool has all 3 stats
|
||||
- the ranges in DESIGN §11 are **stricter** and are enforced by modes (`shared/game/modes.ts`). The engine's bounds only guarantee safety and termination.
|
||||
|
||||
## 5. Determinism and the RNG
|
||||
|
||||
- The RNG is **mulberry32(seed: uint32)**, as in DESIGN §4. Its state is a single uint32 in `state.rng`.
|
||||
- Draw order:
|
||||
1. p0's deck is shuffled.
|
||||
2. p1's deck is shuffled.
|
||||
3. **The Topics are drawn.** With `distinctStats`: for each stat in the order `attention, depth, reach`, take `group[floor(next() × group.length)]`, where `group` is that stat's Topics in `topicPool` order. Then the picks are shuffled, and that is the lane order. Without `distinctStats`: the whole pool is shuffled and the first `topicCount` are taken.
|
||||
4. The initiative coin is flipped: p0 has initiative on turn 1 (and every odd turn) if `next() < 0.5`; otherwise p1 does. After that, initiative strictly alternates.
|
||||
5. Keyword and Portal hooks draw in resolution order.
|
||||
- Shuffles are Fisher–Yates with `i` from n−1 down to 1 and `j = floor(next() × (i+1))`.
|
||||
- `ongoing` power hooks get a throwaway RNG copy, so computing power never changes the match RNG.
|
||||
|
||||
## 6. State and views
|
||||
|
||||
The full `MatchState` (plain JSON) is for the **host only**:
|
||||
|
||||
```ts
|
||||
interface MatchState {
|
||||
schema: 'wikideck-match/1'; engineVersion: number; ruleset: Ruleset; seed: number; rng: number;
|
||||
turn: number /* 1-based */; phase: 'planning' | 'over'; initiative: 0 | 1;
|
||||
players: [PlayerState, PlayerState]; // deck, hand, energy, queue, committed, afk
|
||||
lanes: { topic: TopicDef; portalRevealed: boolean; cards: [CardInPlay[], CardInPlay[]] }[];
|
||||
revealSeq: number; log: LogEvent[]; actions: Action[]; result: MatchResult | null;
|
||||
}
|
||||
interface PlayerState { deck; hand; energy; queue: { cardId; lane }[]; committed; afk; carry }
|
||||
interface CardInPlay { card: GameCard; owner: 0 | 1; lane: number; turn: number; seq: number; bonus: number }
|
||||
```
|
||||
|
||||
`PlayerView`, returned by `viewFor(state, seat)`, is what a seat may see. In it, "you" is always index 0 and the opponent is index 1:
|
||||
|
||||
```ts
|
||||
interface PlayerView {
|
||||
you: 0 | 1; ruleset; turn; phase; initiative;
|
||||
energy: number; energyLeft: number; hand: GameCard[]; queue: { cardId; lane }[]; committed; deckCount;
|
||||
opponent: { handCount; deckCount; committed }; // §5.3: nothing about their queue (cards, count or energy) until reveal
|
||||
lanes: { topic: TopicDef /* stat always; id/name/portal masked until portalRevealed */, portalRevealed, cards: [mine, theirs],
|
||||
cardPower: [number[], number[]], power: [mine, theirs], leader: 'you' | 'opponent' | null }[];
|
||||
result: MatchResult | null;
|
||||
}
|
||||
```
|
||||
|
||||
`state.log` is an append-only event list for animation and replays. Event types: `turnStart`, `portalRevealed`, `underdog`, `draw`, `reveal`, `fizzle`, `effect`, `concede` and `matchOver`. It contains both seats' draws, so a host must filter it per seat before sending it.
|
||||
|
||||
## 7. Results
|
||||
|
||||
```ts
|
||||
interface MatchResult {
|
||||
winner: 0 | 1 | null; // null = draw
|
||||
reason: 'topics' | 'totalPower' | 'draw' | 'concede' | 'afk';
|
||||
topicsLed: [number, number]; lanePower: [number, number][]; totalPower: [number, number]; turns: number;
|
||||
}
|
||||
```
|
||||
|
||||
Scoring runs after the last turn's End phase. Lane powers include revealed "at scoring" Portals, and each lane's leader uses the consensus tie-break (§6). Winner, per DESIGN §7:
|
||||
1. The seat that leads more Topics.
|
||||
2. If tied on Topics, the seat with more total power.
|
||||
3. If that is also tied, a draw.
|
||||
|
||||
## 8. Keywords and Portals (extension contract)
|
||||
|
||||
`KEYWORDS` and `PORTALS` in `shared/game/keywords.ts` (engine-b) are registries of hook objects. v1 keywords (`V1_KEYWORDS`, one per faction via `FACTION_KEYWORD`): viral, rising, local, encyclopedic, nostalgic, translated; optional (`OPTIONAL_KEYWORDS`, off by default): edition, obscure, wildcard. Portals: the 6 kinds of §10.3. The header of that file is normative. Every hook gets `ctx = { state, rng, params, lane, log, power(card) }`.
|
||||
|
||||
**Keywords**
|
||||
- `onReveal(ctx, self)` and `endOfTurn(ctx, self)` may change `bonus` on cards in `ctx.state`.
|
||||
- `ongoing(ctx, self, target) → number` must be **pure**, and must not call `ctx.power`.
|
||||
- Keyword hooks run only if the keyword is in `keywordsEnabled`.
|
||||
|
||||
**Portals** have the same hooks, plus:
|
||||
- `onPortalReveal(ctx)`
|
||||
- `canPlay(ctx, card, seat) → boolean`, checked when a play is queued and again at reveal
|
||||
- `capacity(ctx) → number`
|
||||
- `allOnTopic: true`
|
||||
- `atScoring(ctx) → [delta0, delta1]`
|
||||
|
||||
Portal hooks act only once the Portal is revealed.
|
||||
|
||||
**Rules for all hooks**
|
||||
- Hooks must not move or remove cards (DESIGN §10).
|
||||
- Any randomness must come from `ctx.rng`. No v1 keyword uses it.
|
||||
|
||||
## 9. Testing
|
||||
|
||||
- `tests/game-core.test.ts` (engine-a) covers the core loop:
|
||||
- the RNG reference value, ruleset bounds and setup
|
||||
- hidden information and hidden Portals
|
||||
- energy carry, interleaved reveal and alternating initiative
|
||||
- on-topic power, the consensus tie-break, and Portal capacity, fizzle and at-scoring hooks
|
||||
- disabled keywords, AFK and concede, and draws
|
||||
- the random-play property: matches terminate, replay exactly, and serialise after every action
|
||||
- `tests/game-keywords`, `game-derive`, `game-starter`, `game-property`, `game-golden` (engine-b): every keyword and Portal, derivation, starter decks, properties (termination, determinism, round-trip, no input mutation, legality, power ≥ 0, capacity, no hand leak) and the DESIGN §12 golden match (19–15 / 15–19 / 13–10, p0 wins).
|
||||
@@ -0,0 +1,272 @@
|
||||
# Hosting WikiDeck game modes
|
||||
|
||||
Anyone running a WikiDeck node can host their own **game modes**: their own twist on the
|
||||
rules, played with WikiDeck cards on their node, with visible credit for hosting them.
|
||||
Hosting a popular mode is the night-1 incentive to run a peer.
|
||||
|
||||
- Schema and validator: `shared/game/modes.ts`
|
||||
- Node API: `server/game/` (mounted at `/api/game` by `server/testnet/http.ts`)
|
||||
- Example modes: `server/game/modes/*.json` (shipped in the node image)
|
||||
- Tests: `tests/modes-*.test.ts`
|
||||
|
||||
Everything here is **off-chain**. Hosting a mode never touches blocks, transfers, trades,
|
||||
validation or NFT ownership. A match never moves or burns a card.
|
||||
|
||||
## 1. Modes are data, never code
|
||||
|
||||
A mode is a JSON document, at most 8 KiB:
|
||||
|
||||
```json
|
||||
{
|
||||
"schema": "wikideck.mode/1",
|
||||
"id": "trending",
|
||||
"version": 1,
|
||||
"name": "Trending",
|
||||
"description": "Live Wikipedia pageview trends power cards up or down.",
|
||||
"tags": ["live-data"],
|
||||
"rules": { "trendUp": 25, "trendDown": -25 },
|
||||
"cards": { "preset": "trending", "percentPerPoint": 25, "maxBonus": 3, "penalise": true },
|
||||
"decks": { "kind": "starter" },
|
||||
"limits": { "maxConcurrentMatches": 32, "turnSeconds": 90, "lobbyMinutes": 15 }
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Meaning |
|
||||
|---|---|
|
||||
| `id`, `version` | Lowercase slug and a version integer. Bump `version` whenever the rules change, so old match records and leaderboards stay attributable (`<origin>#<id>@<version>`). |
|
||||
| `name`, `description`, `tags` | Plain text only: no control characters or `<` `>`. |
|
||||
| `rules` | **Overrides** on top of the engine's `DEFAULT_RULESET` (see `docs/game/ENGINE_API.md`). Objects merge one level deep; arrays and numbers replace. The merged result then goes through the engine's strict `parseRuleset`, so the engine alone decides what's legal (bounded turns, Topics, deck sizes, known keywords and portals only; see DESIGN.md §9 for the keys). |
|
||||
| `cards` | A card-mapping **preset** from a fixed list. `standard` leaves cards as dealt. `live` freezes each card's live trend arrow (DESIGN §1.6, using the ruleset's `trendUp`/`trendDown`) at match start. `trending` does the same and also adds a bounded power bonus from the live pageview trend. The mode only picks a preset and tunes its bounded numbers. |
|
||||
| `decks` | `starter` (everyone gets a seeded starter deck), `draft` (snake draft from a host-seeded pool of preview cards) or `constructed` (bring your own; see "Not yet" below). |
|
||||
| `limits` | Concurrency and lobby expiry for this mode on this host. `turnSeconds` only applies to engines without their own turn timer; with tonight's engine, the ruleset's `turnSeconds` (plus 5 s network grace) is the timer. |
|
||||
|
||||
The schema is strict: unknown fields are rejected, as are prototype keys
|
||||
(`__proto__`, `constructor`, `prototype`) anywhere in the document, nesting deeper than two
|
||||
levels inside `rules`, more than 48 rule keys, and oversized strings and arrays. A peer
|
||||
**never** evaluates, imports or runs anything another peer sends. Nothing in a mode can name
|
||||
a file, a URL, a script or a function.
|
||||
|
||||
## 2. Running your own modes
|
||||
|
||||
Configure modes with environment variables on your node:
|
||||
|
||||
| Variable | Default | Meaning |
|
||||
|---|---|---|
|
||||
| `WIKIDECK_MODES` | `classic` | Comma list of built-in ids (`classic`, `trending`, `draft`) and/or paths to `.json` files. `none` hosts nothing (the node still lists its peers' modes). |
|
||||
| `WIKIDECK_MODES_DIR` | unset | A directory: every `*.json` in it is loaded as a mode. |
|
||||
| `WIKIDECK_GAME_OPERATOR` | your origin's host | The name shown as **"Hosted by …"**. |
|
||||
| `WIKIDECK_GAME_NOTE` | unset | A short note shown next to your name, e.g. "EU, best effort". |
|
||||
| `WIKIDECK_GAME_PEERS` | `WIKIDECK_PEERS` | Peer origins whose modes to list. Use the peers' **public** origins, because players open the peer's own site to play there. |
|
||||
| `WIKIDECK_GAME_TREND_INTERVAL_MS` | `20000` | Background trend warm-up pace for `trending` modes (minimum 15000). |
|
||||
| `PUBLIC_ORIGIN` | `http://127.0.0.1:$PORT` | Your node's identity as a host. |
|
||||
|
||||
At most 16 modes per node. A bad mode file stops the node at startup with a readable error,
|
||||
because rules are validated once with the engine's parser when the node starts.
|
||||
|
||||
Example for the night-1 testnet (three nodes, different modes):
|
||||
|
||||
```yaml
|
||||
# node-a: the base rules plus Trending
|
||||
WIKIDECK_MODES: classic,trending
|
||||
WIKIDECK_GAME_OPERATOR: Testnet A
|
||||
WIKIDECK_GAME_PEERS: http://192.168.1.32:3102,http://192.168.1.32:3103
|
||||
# node-b: the draft
|
||||
WIKIDECK_MODES: draft
|
||||
WIKIDECK_GAME_OPERATOR: Testnet B
|
||||
# node-c: everything, including a custom file
|
||||
WIKIDECK_MODES: classic,trending,draft,/app/data/modes/blitz.json
|
||||
```
|
||||
|
||||
### Writing a new mode
|
||||
|
||||
Start from `server/game/modes/classic.json`, change `id`, `name` and `description`, then
|
||||
override rules. Some ideas within tonight's rules:
|
||||
|
||||
- **Blitz:** `"rules": { "turns": 4, "energyByTurn": [3, 4, 5, 6] }`
|
||||
- **On-topic:** `"rules": { "onTopicBonus": [0, 2, 2, 3, 3, 4, 4], "trendUp": 10, "trendDown": -10 }`
|
||||
- **Slow play:** `"rules": { "turns": 6, "turnSeconds": 40 }` (the engine caps turns × turnSeconds at 240)
|
||||
- **Big decks:** `"rules": { "deckSize": 16, "maxLoaners": 16 }` with `"decks": { "kind": "draft", "poolSize": 40 }`.
|
||||
Starter decks are 12 cards, so a non-draft mode with another deck size is rejected at startup.
|
||||
|
||||
Check that a mode parses with `npm test` (the built-in modes are tested), or load it on a
|
||||
local node: it fails at startup if the engine rejects it.
|
||||
|
||||
## 3. The node API
|
||||
|
||||
Everything is under `/api/game`, behind the node's existing `/api` admission budget and
|
||||
global rate limit, plus stricter per-route limits.
|
||||
|
||||
| Method | Path | What it does |
|
||||
|---|---|---|
|
||||
| GET | `/modes` | **Publish:** this node's host identity, total matches hosted, and each mode with live stats (players online, open lobbies, live matches, matches played, distinct players). |
|
||||
| GET | `/network/modes` | **Discover:** this node's list plus each configured peer's list, fetched as data. |
|
||||
| GET | `/hosts/leaderboard` | Hosts ranked by matches hosted (this node plus peers). |
|
||||
| GET | `/modes/:id/leaderboard` | Per-mode player leaderboard (wins, losses, draws). |
|
||||
| GET | `/modes/:id/lobbies` | Open lobbies waiting for an opponent. |
|
||||
| POST | `/modes/:id/lobbies` | Create a lobby: `{ name, secret }` → `{ lobbyId, seat: 0, token }`. |
|
||||
| POST | `/lobbies/:lobby/join` | Join: `{ name, secret }` → `{ lobbyId, seat: 1, token }`. The match (or draft) starts. |
|
||||
| GET | `/lobbies/:lobby` | Status. With `Authorization: Bearer <token>`: your `PlayerView` and your `legalActions`. |
|
||||
| POST | `/lobbies/:lobby/pick` | Draft pick: `{ index }`. |
|
||||
| POST | `/lobbies/:lobby/actions` | Play: `{ action }`, which must equal one of your `legalActions`. |
|
||||
| POST | `/lobbies/:lobby/resign` | Resign (or cancel a waiting lobby). |
|
||||
| GET | `/matches/:matchId` | A finished match record: seed, both decks, the full action log and the result. |
|
||||
|
||||
**Players.** The browser generates a random `secret` once and keeps it in local storage. The
|
||||
host only ever stores and shows `sha256("wikideck-player:" + secret)` as the player id, so a
|
||||
leaderboard name can't be claimed by someone else who uses the same display name. Each seat
|
||||
also gets a fresh bearer token per lobby; only its hash is kept. When eom.dev accounts land
|
||||
(#7), the player id can come from the account instead.
|
||||
|
||||
**Playing on a peer's mode.** The browser's CSP keeps API calls same-origin, so the lobby
|
||||
shows peer modes with "Hosted by …" and links to the peer's own site to play there. No node
|
||||
proxies another node's matches.
|
||||
|
||||
### Restarts
|
||||
|
||||
Live lobbies, drafts and matches survive a node restart. The node saves them to
|
||||
`$WIKIDECK_DATA_DIR/game/live.json` every 15 s and on SIGTERM/SIGINT, and restores them on start.
|
||||
Player tokens keep working, and turn and draft timers restart from the moment the node is back.
|
||||
A lobby is dropped instead of restored if its mode is no longer hosted with the same `version`
|
||||
and rules, so a match never continues under different rules. A hard crash can lose up to 15 s
|
||||
of moves.
|
||||
|
||||
## 4. Credit for hosts
|
||||
|
||||
Every mode shows **"Hosted by <operator>"** (with the node's origin), its player counts,
|
||||
its own leaderboard, and the node's total matches hosted. `/hosts/leaderboard` ranks nodes by
|
||||
matches hosted.
|
||||
|
||||
Tonight these numbers are **informational**: each node reports its own counts. See section 6
|
||||
for how they could become rewards without trusting the host's word.
|
||||
|
||||
## 5. Security notes
|
||||
|
||||
### Limits
|
||||
|
||||
| Limit | Value |
|
||||
|---|---|
|
||||
| Mode document | 8 KiB; 48 rule keys; rule nesting depth 2; strings ≤ 64 chars inside rules |
|
||||
| Modes per node / per peer response | 16 |
|
||||
| Peer `/api/game/modes` response | 192 KiB, read with a streaming byte cap; 3 s timeout; no redirects; cached 30 s; at most one refresh in flight |
|
||||
| Peers | at most 16, operator-configured origins only (HTTPS, or HTTP with `WIKIDECK_ALLOW_PRIVATE_PEERS=1`) |
|
||||
| Lobbies + matches in memory | 512 per node; `maxConcurrentMatches` per mode; 3 per player |
|
||||
| Match length | engine bounds (`turns` ≤ 12, turns × turnSeconds ≤ 240 s) plus a hard 2,000-action cap |
|
||||
| Rate limits per IP | 240/min reads and plays, 60/min lobby create/join/resign, 30/min peer-discovery routes (on top of the node-wide 300/min `/api` limit and the RPC admission budget) |
|
||||
| Request body | the node's 68 KB JSON limit |
|
||||
| Wikipedia lookups (`trending`) | background only: one page per 20 s by default (`WIKIDECK_GAME_TREND_INTERVAL_MS`, minimum 15 s), at most 256 queued, never per request |
|
||||
|
||||
### Mode validation
|
||||
|
||||
A mode is rejected at node startup, never handed to the engine half-checked, if:
|
||||
- it fails the mode schema (section 1), or
|
||||
- the merged ruleset fails the engine's strict `parseRuleset`, or
|
||||
- it fails the host-side checks in `server/game/engine-binding.ts`: `distinctStats` requires
|
||||
`topicCount` 3; every `portalReveal` turn ≤ `turns`; `energyByTurn` has an entry per turn;
|
||||
`turns × turnSeconds ≤ 240`; `powerByCost` has 7 entries; no keyword whose hidden information
|
||||
`viewFor` doesn't mask yet (`obscure`) is enabled; or
|
||||
- its deck policy can't produce legal decks (starter decks illegal under its rules, or a draft
|
||||
pool smaller than 2 × `deckSize`).
|
||||
|
||||
### Wikipedia load (`verifyStats`)
|
||||
|
||||
Our Wikipedia egress is shared and rate-limited, so tonight the host makes **no Wikipedia
|
||||
requests in any request or match path**:
|
||||
- Hosted decks are loaners (starter or drafted), so there are no owned-card stats to verify,
|
||||
and `verifyStats` never triggers a fetch.
|
||||
- When owned decks arrive, verification must use the DESIGN §1.10 immutable cache keyed by
|
||||
`(pageId, revisionId, snapshotMonth)`, with `check: 'unchecked'` and `uncheckedCostCap` as the
|
||||
normal path when the cache is cold, not a per-card fetch.
|
||||
- `trending` reads only the background-warmed trend cache (see "Not yet").
|
||||
|
||||
### Cheating
|
||||
|
||||
- **The client is never trusted.** Each action must deep-equal one of the engine's
|
||||
`legalActions` for the token's seat, so you can't act for the other seat, play cards you
|
||||
don't hold, overspend energy or act after the match ends.
|
||||
- **Hidden information stays on the host.** Each seat only ever receives `viewFor(state, seat)`;
|
||||
the opponent's hand and staged plays never leave the server. Spectators see status only.
|
||||
- **Seeds are the host's.** The host picks a random seed when the lobby opens, so players can't
|
||||
grind for a favourable shuffle. The engine hashes it to 32 bits: fine against players, but
|
||||
not a secret worth relying on against a host.
|
||||
- **Stalling:** when a seat runs out of turn time, the host applies the engine's `timeout`
|
||||
action (auto-commit). After `afkTurns` idle timeouts the engine forfeits that seat. Timeouts
|
||||
are in the action log, so they replay. A stalled draft pick is made automatically.
|
||||
- **Sybils and win-trading:** anyone can make a new player id, and two ids controlled by the same
|
||||
person can feed each other wins. Tonight's leaderboards are for fun. Accounts (#7) or
|
||||
wallet-signed identities would raise the cost.
|
||||
- **Card input.** The host builds every deck from shipped engine data (starter decks and the
|
||||
loaner pool). It never accepts cards, `check` values or pinned stats from client JSON.
|
||||
- **Card stats.** Card numbers come from the engine's card mapping. Minted stats are self-reported
|
||||
by the minter (see council-critic in #3); a mode can only pick a mapping preset, not supply numbers.
|
||||
|
||||
### What a malicious host can and can't do
|
||||
|
||||
**Hosted PvP trusts the host.** The host holds both players' hidden plans (hands and queued plays)
|
||||
and relays them; it decides the seed; and it would be the one to mark card stats as checked or
|
||||
unchecked (DESIGN §1.10). Nothing tonight lets players verify a match *while* it's being played.
|
||||
So a host is **trusted for the matches it hosts**, and only those. Play on hosts you trust, and
|
||||
treat leaderboards on any other host as that host's claims.
|
||||
|
||||
A malicious host **can**:
|
||||
- lie about its stats, its matches hosted and its leaderboards;
|
||||
- rig its own matches: pick seeds, peek at hands, or ignore the rules;
|
||||
- drop or stall your match, or record a false result.
|
||||
|
||||
A malicious host **can't**:
|
||||
- touch your cards: matches are off-chain, and the host never receives a key or signature;
|
||||
- run code on other nodes: its modes are inert data, validated with hard limits;
|
||||
- make other nodes fetch anything except its own `/api/game/modes`, or make them fetch it
|
||||
in a way that slows them down (byte cap, timeout, cache, single flight);
|
||||
- publish modes under another node's origin: discovery pins the origin it actually fetched;
|
||||
- see your player secret: it only receives it once, over its own origin, and stores the hash.
|
||||
**Use a different secret per host** if you don't trust a host (the UI can derive one per origin).
|
||||
|
||||
**Audit trail.** Every finished match record publishes the seed, both decks and the full action
|
||||
log, so anyone can re-run it with the engine's `replay(ruleset, decks, seed, actions)` and check
|
||||
the result. A host that lies about a result can be caught; a host that peeked at hands can't.
|
||||
|
||||
## 6. Proposal: on-chain host rewards (not tonight)
|
||||
|
||||
Rewarding hosts on-chain is a **protocol change**, so it's out of scope for night 1. This is a
|
||||
proposal for later, to be reviewed like any consensus change.
|
||||
|
||||
**Goal:** pay hosts for matches real players actually played, without trusting the host's count.
|
||||
|
||||
1. **Signed match results.** Both players sign the final result
|
||||
(`matchId`, `<origin>#<id>@<version>`, seed hash, action-log hash, winner) with their wallet
|
||||
keys. The host signs too. A result needs all three signatures, so a host can't invent matches
|
||||
or results alone, and players can't deny a match they played.
|
||||
2. **Replayable evidence.** The record keeps the seed, decks and action log. Anyone can replay it
|
||||
with the pinned engine version to check the result. Disputes are settled by replay, not by vote.
|
||||
3. **Batched claims.** Once per epoch, a host submits one transaction committing a Merkle root of
|
||||
its signed results. A new `hostClaim` transaction type would carry the root and a count. This is
|
||||
the protocol change: a new transaction type, its validation and its reward rule.
|
||||
4. **Rewards that resist farming.** A host's reward per epoch grows with the number of **distinct
|
||||
paired wallets** (not matches), each wallet counts toward at most one host per epoch, wallets
|
||||
must hold at least one minted card older than N blocks, and the total is a small, capped
|
||||
share of block rewards. That makes sybil farms cost real mining work.
|
||||
5. **Challenges.** For a window after a claim, anyone can post a replay that contradicts a
|
||||
committed result, or proof that a wallet was double-counted. A successful challenge voids
|
||||
the host's claim for that epoch.
|
||||
|
||||
Open questions: who pays (a share of block rewards versus a fee from players), how to stop
|
||||
colluding players and hosts from farming one another, and whether the engine version must
|
||||
be pinned in consensus.
|
||||
|
||||
## Not yet
|
||||
|
||||
- `constructed` decks of **owned NFTs**: the policy exists, but tonight the host deals
|
||||
starter decks for it. Playing with your own cards needs a wallet-signed ownership proof
|
||||
for the lobby (and then the engine's `cardFromStats`). That's a follow-up once accounts and
|
||||
wallet linking (#7) settle.
|
||||
- `trending` never calls Wikipedia when a match starts. The node warms a cache-only trend
|
||||
store in the background, one page every 20 s (configurable, never faster than 15 s), through its existing enrichment cache (6 h TTL),
|
||||
starting with the preview-card pages. A card whose page isn't warm yet gets no bonus. This
|
||||
keeps load on the shared, rate-limited Wikipedia egress tiny: a few dozen pages per 6 hours per node.
|
||||
- Spectating and rematches.
|
||||
- **Separate game RPC budget.** `/api/game` sits behind the node's global `/api` admission
|
||||
budget (`WIKIDECK_RPC_REQUESTS_PER_SECOND`, 10 writes/s node-wide), so a flood of game
|
||||
traffic can delay chain RPC (and the reverse). At human speed this is fine. The fix is to give
|
||||
game routes their own `RpcBudget`, which means mounting them ahead of the shared budget in
|
||||
`server/testnet/http.ts`: a change to that shared file, so it's proposed in #6 rather than made
|
||||
tonight.
|
||||
@@ -0,0 +1,57 @@
|
||||
# Mainnet-first, gated candidate
|
||||
|
||||
The repository defaults to a **mainnet candidate**, not an audited or launched production network. Shipping code does not establish independent miners, economic security, or an operational public network. Market and payment features have been removed from the card-only product.
|
||||
|
||||
**Current production decision: NO-GO.** See the [2026-10-20 security review](security-review.md) and [operator evidence register and launch procedure](operator-launch.md). The read-only `launch:preflight` package script (or node entry-point `--launch-preflight`) reports local gates and unresolved blockers without starting a node or setting approvals. It deliberately exits nonzero while production readiness is blocked.
|
||||
|
||||
## What is implemented
|
||||
|
||||
| Property | Mainnet-first default | Explicit development fixture |
|
||||
| --- | --- | --- |
|
||||
| Selection | `WIKIDECK_NETWORK=mainnet` (or unset) | `WIKIDECK_NETWORK=testnet` |
|
||||
| Network ID | `wikideck-randomx-mainnet-1` | `wikideck-randomx-testnet-6` |
|
||||
| Protocol | Version 6 | Existing fixed local testnet version 6 |
|
||||
| Genesis timestamp | Fixed launch default: 2026-11-01 00:00 UTC (`1793491200`); ready to start now | Fixed at 2026-10-19 00:00 UTC |
|
||||
| Ledger directory | mainnet | testnet |
|
||||
| Browser wallet | IndexedDB name derived from exact chain ID | Separate chain identity |
|
||||
| New backup | v2 header authenticates exact chain ID | Same v2 format; legacy v1 is accepted only on the original testnet |
|
||||
|
||||
Both profiles use real RandomX validation, cumulative-work branch selection, the 15-minute target, mint maturity, signed NFT transfers, atomic card trades, and SQLite persistence. The mainnet candidate has no premine, token migration, hidden checkpoint, or fake-PoW option. Changing the network identifier and candidate genesis derives distinct chain/genesis IDs, RandomX initial keys, signature domains, and consensus manifest checks. Existing testnet values and data remain unchanged.
|
||||
|
||||
**Cards and backups do not migrate across chain identities.** Browser storage and backup headers are bound to the exact chain ID; peers reject mismatched manifests, and transactions are checked against the active chain. The selected profile and genesis are pinned at startup/browser build, never silently adopted from an RPC response. The original fixed-testnet v1 backups remain supported only on that testnet.
|
||||
|
||||
## Inspect without launching
|
||||
|
||||
The node entry point accepts `--network-manifest`. With `WIKIDECK_NETWORK=mainnet` set in the process environment, this prints the candidate network/chain/genesis/timestamp and exits **before** opening databases, starting a RandomX engine, listening, or contacting peers. It does not require activation credentials or approval and does not launch anything.
|
||||
|
||||
Browser builds select `VITE_WIKIDECK_NETWORK=mainnet`; server/miner processes select `WIKIDECK_NETWORK=mainnet`. These must match. `WIKIDECK_GENESIS_TIME` is also part of the chain identity. Docker's network/genesis **build arguments** pin the browser and immutable image manifest; a runtime variable cannot alter an already compiled UI. To choose another genesis, set it for the image build and runtime together, publish the resulting manifest, then use that immutable image and exact timestamp for every node and browser. A runtime-only genesis override fails closed. A mismatched UI rejects the node rather than signing for it.
|
||||
|
||||
## Explicit launch gates
|
||||
|
||||
[compose.yaml](../compose.yaml) and [compose.mainnet.yaml](../compose.mainnet.yaml) are mainnet-first definitions, use separate named volumes, bind only loopback for an external HTTPS reverse proxy, and do **not** auto-restart a failed candidate. They have no default peers, approval, or public origin. The default service therefore exits until the operator supplies real deployment values. The testnet Docker fixture is separate and explicit. **This code change does not establish or certify a public mainnet.**
|
||||
|
||||
Starting the candidate node or native miner requires all of:
|
||||
|
||||
1. `WIKIDECK_MAINNET_LAUNCH` equals the exact candidate chain ID printed by the manifest command.
|
||||
2. `WIKIDECK_MAINNET_RISK_ACK=operator-accepts-unaudited-risk` records the operator's explicit acceptance that no external audit is planned and residual risks remain. This is not a safety certification; the manifest honestly reports `audited: false`.
|
||||
3. The candidate genesis timestamp has arrived. If the operator changes the timestamp or consensus manifest before launch, the chain ID also changes and the old approval is invalidated. Freeze and publish the final manifest before launch.
|
||||
4. An HTTPS `PUBLIC_ORIGIN` and at least two distinct configured peer origins. Public deployments require public HTTPS peers by default. An operator-controlled private candidate cluster may explicitly set `WIKIDECK_ALLOW_PRIVATE_PEERS=1` to permit private/HTTP peer RPC; this does not relax browser HTTPS, chain approval, risk acknowledgment, or genesis-time gates. Configuration count cannot prove the peers are online, independent, or sufficiently distributed; verify that operationally. Existing public peer DNS/origin controls still apply when the private opt-in is off, and HTTPS certificate verification is never disabled.
|
||||
|
||||
For Kubernetes public peering, give every node a stable, unique public HTTPS endpoint. For an explicitly private candidate, separate single-replica Deployments, Services and exclusive PVCs may use distinct ClusterIP DNS origins with the private opt-in. Each validator lists the other two internal Services, never itself. The browser-facing node needs a TLS ingress/reverse proxy; internal-only validators may share that HTTPS browser origin without their own ingress. NetworkPolicy must restrict peer RPC to the selected validator pods on target TCP port 3001. Private HTTP RPC is unauthenticated and unencrypted unless protected by an independently configured mesh; do not use it across untrusted networks. Three validators in one cluster/storage failure domain are not independent operators or proof of production readiness.
|
||||
|
||||
See the [Kubernetes mainnet preparation checklist](../deploy/kubernetes/README.md) for the deployment contract and the values needed before manifests can be finalized.
|
||||
Unknown profile names fail closed. A direct import of the HTTP entry point is also guarded. Library-level manifest/consensus/storage inspection remains possible for tests and review; activation gates are accident prevention and operator risk acceptance, not a security boundary against someone who edits the source.
|
||||
|
||||
## Required before an actual production launch
|
||||
|
||||
- **Internal readiness review:** track code findings and regression evidence in-repository. No external audit is planned; the operator accepts the additional risk and must not describe the candidate as audited or certified.
|
||||
- **Security model:** quantify hashpower, chain-rewrite cost and majority attacks. The inherited easy initial target and ten-block retarget are **not production-calibrated**. Choose reviewed launch difficulty/retarget behavior and test start-up/stall/recovery scenarios. Independent mining participation and sufficient hashpower are not provided by running multiple containers on one host.
|
||||
- **Adversarial rehearsal:** sustained multi-host simulations, partitions/eclipses, competing branches, deep reorganizations, clock skew, bad peers, load/mempool saturation, corrupted state and restart recovery. Test the candidate rules with no valuable assets.
|
||||
- **Operations:** independently administered public HTTPS nodes and miners across failure domains, pinned release artifacts and dependencies, firewall/reverse proxy/rate-limit policies, bounded storage and sync strategy, metrics, alerts, rotation and emergency-response procedures.
|
||||
- **Recovery:** verified offline wallet recovery, consistent ledger snapshots, full replay/revalidation, documented incident and fork handling. No silent ledger reset or reuse of testnet data.
|
||||
- **Launch governance:** select the actual genesis date, freeze the identity/configuration, publish binaries and configuration hashes, agree peer/miner readiness and upgrade policy, and explicitly record the operator's risk acceptance. Do not treat the flag as proof of safety or peer readiness.
|
||||
- **User and legal review:** no monetary value or security is promised. NFT rights do not imply article/image copyright ownership. Publish experimental-use, privacy, support, and abuse-report terms appropriate to the release.
|
||||
|
||||
## Still not production-ready
|
||||
|
||||
This remains experimental software. Nodes retain the DAG and overlays in memory, rebuild state roots over the full NFT set, and revalidate proofs at startup. The HTTP UI trusts its connected node rather than independently validating the chain. There is no automatic peer discovery, established bootstrap infrastructure, formal finality, independent audit, or production abuse system. Mainnet selection does not remove any of these limitations. See the [card-only production plan](card-only-production-plan.md) for the current readiness gates.
|
||||
@@ -0,0 +1,40 @@
|
||||
# WikiDeck Android app (Night 1)
|
||||
|
||||
A Capacitor 7 shell (`dev.eom.wikideck`) around the React UI. It talks to a WikiDeck node over native HTTP.
|
||||
|
||||

|
||||
|
||||
## Build a debug APK
|
||||
You need JDK 21 (a full JDK with `javac`), the Android SDK (platform 35 and build-tools 35) and `ANDROID_HOME`.
|
||||
```
|
||||
android/build-debug.sh # testnet build: VITE_WIKIDECK_NETWORK=testnet, genesis 1792411200, node http://192.168.1.32:3101
|
||||
adb install -r android/app/build/outputs/apk/debug/app-debug.apk
|
||||
```
|
||||
- **Settings:** override any of them with env vars, for example `VITE_NODE_URL=http://192.168.1.32:3102 android/build-debug.sh`.
|
||||
- **Network:** without `VITE_WIKIDECK_NETWORK=testnet`, the bundle is a **mainnet** build.
|
||||
- **Signing:** debug signing only. Nothing is published.
|
||||
|
||||
## How it works (`src/native.ts`, imported first in `main.tsx`; does nothing on the web)
|
||||
- **Node URL:** relative `fetch('/api/…')` and `fetch('/auth/…')` calls go to `VITE_NODE_URL`. The default is the Night-1 testnet node. A runtime override is available through `setNodeUrl()`, stored in localStorage.
|
||||
- **Native HTTP (`CapacitorHttp`):** fetches go through Android's HTTP stack. There's no CORS, and no WebView `Origin` header, so the node's POST origin check passes without any server change.
|
||||
- Verified: a POST from the app returns 400 (validation), while the same POST with `Origin: https://localhost` returns 403.
|
||||
- The interceptor merges headers (`content-length: 0, 384`). `native.ts` drops that header so `StateClient`'s size check works, and byte limits are still enforced while streaming.
|
||||
- **Mining:** RandomX is desktop-only. `isNativeApp()` hides the mining panel, and `html.native-app` lets CSS target the app.
|
||||
- **SSO:** "Log in with eom.dev" opens Dex in a Custom Tab (`setNativeBrowser(Browser)`). Dex redirects to `dev.eom.wikideck:/oauth/callback` (intent filter, `singleTask`), and `completeLogin()` has the node exchange the code.
|
||||
- **Android behaviour:**
|
||||
- The **back button** closes an open dialog first, then goes back in history, then minimizes the app.
|
||||
- The **keyboard** uses `adjustResize`.
|
||||
- **Edge-to-edge** margins are on, with a dark window behind the system bars.
|
||||
|
||||
## Emulator (inspiron-3670, user space)
|
||||
The SDK, AVD and JDK are under `~/worker/jobs/night/mobile-android/{sdk,avd,jdk}`, and `env.sh` sets the paths.
|
||||
```
|
||||
emulator -avd wikideck -no-window -no-audio -gpu swiftshader_indirect # headless, KVM
|
||||
adb exec-out screencap -p > shot.png
|
||||
```
|
||||
To inspect the WebView, forward DevTools with `adb forward tcp:9222 localabstract:webview_devtools_remote_$(adb shell pidof dev.eom.wikideck)`.
|
||||
|
||||
## Known gaps
|
||||
- **Real SSO login:** needs an eom.dev account and wasn't done tonight. The deep-link round trip was verified up to Dex's `invalid_grant` for a dummy code.
|
||||
- **Touch targets in the Play UI:** the dashed "Play here" lane zone doesn't respond to taps; only the lane plate does (reported on #5).
|
||||
- **Mining copy on the home hero:** "Explore mining" still shows in the app.
|
||||
@@ -0,0 +1,53 @@
|
||||
# Night 1: module boundaries
|
||||
|
||||
Owner: `night-lead`. This file is the rule when two PRs touch the same path. If you need to edit a path you don't own, comment on the owner's issue (`[from <you>]`) or keep your change to the "shared hook" listed below.
|
||||
|
||||
## Who owns what
|
||||
|
||||
| Path | Owner | Issue |
|
||||
|---|---|---|
|
||||
| `docs/game/DESIGN.md` | council (designer-a, designer-b, critic) | #1 |
|
||||
| `docs/game/CARD_DATA.md`, `docs/game/card-sample.json` | council-data | #2 |
|
||||
| `shared/game/` (types, RNG, state machine, rules, keywords, `Ruleset`, `starterDeck`) | engine-a (core, API), engine-b (keywords, effects) | #3 |
|
||||
| `docs/game/ENGINE_API.md` | engine-a | #3 |
|
||||
| `shared/game/modes.ts` | modes | #6 |
|
||||
| `server/game*` (e.g. `server/game/`, `server/game-*.ts`) | modes | #6 |
|
||||
| `docs/game/HOSTING.md` | modes | #6 |
|
||||
| `src/game/` (screens, lobby, deck builder, match, tutorial) | ui-a | #5 |
|
||||
| `src/game/ai/` (browser bots, easy and normal) | ui-b | #5 |
|
||||
| beta-fix files outside `src/game/` (landing page, `Card.tsx`, etc.) | ui-b, one PR per upstream issue | #5 |
|
||||
| `shared/bots/`, `scripts/sim/` (bots and the simulation runner) | sim-balance | #4 |
|
||||
| `docs/game/BALANCE.md` | sim-balance | #4 |
|
||||
| `compose.testnet.yaml` overrides, `deploy/night/` (testnet config, per-node mode files) | sim-testnet | #4 |
|
||||
| `server/account*` (e.g. `server/account/`), `src/auth/` | sso | #7 |
|
||||
| `android/`, `capacitor.config.ts` | mobile-android | #8 |
|
||||
| `ios/`, `docs/night/IOS.md` | mobile-ios, macos-fetch | #9 |
|
||||
| `docs/night/` (except `IOS.md`), this file, `REPORT.md` | night-lead | #10 |
|
||||
|
||||
## Tests
|
||||
|
||||
`scripts/run-tests.mjs` only picks up **top-level** `tests/*.test.ts`. Name your files with your team as a prefix so they never collide:
|
||||
`tests/game-*.test.ts` (engine), `tests/modes-*.test.ts`, `tests/ui-*.test.ts`, `tests/bots-*.test.ts`, `tests/account-*.test.ts`.
|
||||
|
||||
## Shared hooks (the only places two teams touch the same file)
|
||||
|
||||
1. **`server/testnet/http.ts`**: modes and sso each export an Express `Router` from their own files and add **exactly one** `app.use(...)` mount line just **above** the `/api` 404 handler (`app.use(['/api','/p2p'],(_req,res)=>{res.status(404)...`). Nothing else in this file. If SSO needs a CSP change (`connect-src` for `https://dex.eom.dev`), keep it to the `helmet` directive and say so in the PR.
|
||||
2. **`src/App.tsx`**: ui-a owns it. Others get one import and one element each (sso: a login button or provider; mobile: hide the mining controls behind a `isNativeApp()` check from `src/game/` or `src/auth/`, never by deleting code).
|
||||
3. **`package.json` and `package-lock.json`**: additive changes only (new dependencies or scripts). Don't reformat or bump existing versions. Lockfile conflicts are resolved by night-lead regenerating the lockfile.
|
||||
4. **`shared/enrichment.ts`**: read-only for everyone tonight. Map card data into game stats inside `shared/game/`.
|
||||
|
||||
## Off limits (consensus and protocol; PRs touching these are rejected)
|
||||
|
||||
`server/chain.ts`, `shared/protocol.ts`, `shared/trade-offer.ts`, `shared/chain-identity.ts`, `shared/network.ts`, `server/testnet/consensus.ts`, `server/testnet/ledger.ts`, `server/testnet/canonical-index.ts`, `server/testnet/randomx.ts`, `server/testnet/miner.ts`, `server/testnet/peers.ts`, `native/`.
|
||||
|
||||
If you think you need a change there, write it up in your issue instead.
|
||||
|
||||
## Dependency direction
|
||||
|
||||
`shared/game/` imports nothing from `server/` or `src/` and does no I/O. `shared/game/modes.ts`, `shared/bots/`, `server/game*`, `src/game/` import from `shared/game/` through the API in `ENGINE_API.md`, not from its internals.
|
||||
|
||||
## Merging
|
||||
|
||||
- Branch `night/<team>/<topic>`, PR into `night/2026-11-16`, squash-merged by night-lead after night-review approves and `npm test` and `npm run build` pass.
|
||||
- Small PRs merge faster. Rebase on the integration branch before asking for review if it moved under you.
|
||||
- After 01:10 (code freeze), only fixes merge.
|
||||
@@ -0,0 +1,99 @@
|
||||
# WikiDeck Night 1: team handbook
|
||||
|
||||
Read this whole file before doing anything. It's the contract between about 17 agents on 4 machines.
|
||||
|
||||
**Coordinator:** the Claude session on tower-plus (Eric's interactive session).
|
||||
**Lead/integrator:** `night-lead` on tower-plus.
|
||||
**Window:** 2026-11-16 22:45 until **01:30 EST, hard stop**.
|
||||
**Milestone:** https://gitea.eom.dev/claude/wikideck/milestone/63
|
||||
|
||||
## Goal
|
||||
Turn WikiDeck into a game:
|
||||
1. A **fun, robust, balance-tested card game**, playable in the browser against a private testnet.
|
||||
2. **eom.dev accounts:** log in through Dex SSO, and link a self-custodial wallet to your account.
|
||||
3. **Peer-hosted game modes:** node operators publish their own modes as an incentive to run a peer.
|
||||
4. **An Android app**, built and running in an emulator, and an **iOS app** (macOS VM; Xcode sign-in waits for Eric).
|
||||
|
||||
## Hard rules (no exceptions)
|
||||
- **Where to push:** only to `git@gitea.eom.dev:claude/wikideck.git`. Never push to `WikiDeck/wikideck` (upstream) or to `main` on this fork.
|
||||
- **Branches:** every change goes on a branch named `night/<team>/<topic>`, through a PR into **`night/2026-11-16`**. Only `night-lead` merges.
|
||||
- **Live services:** don't touch the live wikideck deployment (k8s namespace `wikideck`) or mainnet. The testnet is private, on poweredge-r350.
|
||||
- **No consensus or protocol changes:**
|
||||
- no block, transfer or trade format changes
|
||||
- nothing that changes validation in `server/chain.ts` or `shared/protocol.ts`
|
||||
- the game runs **off-chain**
|
||||
- if you think you need a protocol change, write it up in your issue instead
|
||||
- **Production SSO:** don't change Dex or any other production service yourself. The SSO team prepares the Dex change, and the coordinator reviews and applies it.
|
||||
- **Nothing public:** only `night-lead` and the scheduled standup post on Discourse (planning topic only). No other public posts, no purchases or sign-ups, and no secrets in git.
|
||||
- **The printer and CNC:** inspiron-3670 drives a 3D printer and a CNC router. Never start, resume or send a print or cut.
|
||||
- **Git identity** in every clone:
|
||||
```
|
||||
git config user.name Claude
|
||||
git config user.email claude@eom.dev
|
||||
git config commit.gpgsign false
|
||||
```
|
||||
End commit messages with `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`.
|
||||
- **Before opening a PR:** `npm test` and `npm run build` must pass. If something can't pass yet, say so in the PR.
|
||||
|
||||
## How we coordinate
|
||||
**Gitea is the shared brain.** The machines don't share a filesystem, and workers can't message each other.
|
||||
- **Your issue is your inbox.**
|
||||
- Prefix every comment with your agent name, e.g. `[engine-a]`.
|
||||
- Check your issue and your PRs for new comments **at least every 15 minutes** and whenever you finish a step.
|
||||
- **Status labels on your issue:**
|
||||
- `status/in-progress` while you're working
|
||||
- `status/needs-review` when a PR is up
|
||||
- `status/blocked` with a comment explaining why
|
||||
- `status/done` when finished
|
||||
- **Need another team?** Comment on *their* issue, starting with `[from <you>]`.
|
||||
- **Contracts beat conversations.** Interfaces live in files on the integration branch (`docs/game/*.md`, TypeScript types). Read them before asking.
|
||||
- **When the lead (or the coordinator) messages you directly** through herdr, the message is a peer request within this plan. Act on it.
|
||||
- **Stuck for more than 10 minutes?** Label `status/blocked` and comment. Don't spin.
|
||||
|
||||
## Resources (be a good neighbour)
|
||||
- **inspiron-3670** (6 cores, 60 GB RAM) has 7 agents, the Android emulator and a macOS VM. Wrap heavy commands in a shared lock:
|
||||
```
|
||||
flock /tmp/night-heavy.lock <npm ci | npm run build | gradle ...>
|
||||
```
|
||||
- **imac** (8 threads, about 4 GB free) and **poweredge-r350** (16 threads, about 6 GB free): keep builds to one at a time.
|
||||
- **Avoid permission prompts.** Nobody answers them, and they auto-deny after about a minute. Don't chain `cd <dir> && <command that writes files>`; use absolute paths or `git -C <dir>` instead. Keep each shell command to one clear purpose.
|
||||
- **LocalAI** (`https://localai.eom.dev`) is shared production with slow single-GPU inference. Don't use it in loops.
|
||||
|
||||
## Timeline (EST)
|
||||
|
||||
| Time | Milestone |
|
||||
|---|---|
|
||||
| 22:45 | Kickoff. The design council researches. Infra teams set up (testnet, Android SDK, macOS, SSO scaffolding, UI shell, beta fixes). |
|
||||
| **23:30** | **Design v1 frozen** (`docs/game/DESIGN.md`). The engine team implements it. |
|
||||
| 23:45 | **Engine API contract** (`docs/game/ENGINE_API.md` plus TypeScript types) on the integration branch, so UI, simulation and modes can build against it. |
|
||||
| 00:15 | Engine alpha. Simulation starts bot matches. The UI wires up real matches. |
|
||||
| 00:45 | Balance report v1. The council tunes the rules (v1.1). |
|
||||
| **01:10** | **Code freeze:** fixes only. The lead integrates. QA plays end to end. |
|
||||
| 01:25 | Final reports in each issue. The lead writes `docs/night/REPORT.md`. |
|
||||
| **01:30** | **Stop.** |
|
||||
|
||||
## Teams
|
||||
|
||||
| Agent | Machine | Issue |
|
||||
|---|---|---|
|
||||
| council-designer-a, council-designer-b, council-data | imac | Game design council, card data analysis |
|
||||
| council-critic, night-lead, night-review, macos-fetch | tower-plus | Design council (critic), integration and QA, iOS (download) |
|
||||
| engine-a, engine-b | inspiron-3670 | Game engine |
|
||||
| ui-a, ui-b | inspiron-3670 | Game UI and AI opponent, beta fixes |
|
||||
| modes | inspiron-3670 | Peer-hosted game modes |
|
||||
| mobile-android, mobile-ios | inspiron-3670 | Android app, iOS app and macOS VM |
|
||||
| sim-testnet, sim-balance, sso | poweredge-r350 | Testnet and simulation, eom.dev accounts |
|
||||
|
||||
## What the cards hold (game design input)
|
||||
Each card's data comes from `shared/enrichment.ts`: `PageEnrichment` and `MintStatsSnapshot`.
|
||||
- **Identity:** `title`, `description`, `wikidataId` (structured facts: instance-of, dates, coordinates...) and `categories[]`
|
||||
- **Size and history:** `pageBytes` and `revisionId`
|
||||
- **Reach:** `languageCount`, the number of language editions
|
||||
- **Pageviews:** monthly views, `total`, `dailyAverage` and `trendPercent`
|
||||
- **Derived 0–100-ish scores:** `stats.attention`, `stats.depth` and `stats.reach`
|
||||
- **Two values for everything:** an immutable **at-mint snapshot** and **live current values** that change over time
|
||||
- **Duplicates:** the same article can be minted more than once, each copy with its own snapshot
|
||||
|
||||
Two facts to design around:
|
||||
- **New players own no cards.** The design must give them a way to play immediately, for example starter decks of preview or loaner cards that don't touch NFTs.
|
||||
- **Cards are NFTs.** A match must never move or burn cards on-chain tonight.
|
||||
@@ -0,0 +1,92 @@
|
||||
# iOS app and macOS VM (Night 1, mobile-ios, issue #9)
|
||||
|
||||
## Status at a glance
|
||||
- **macOS VM:** QEMU/KVM on inspiron-3670, OSX-KVM style. Sequoia (15) recovery booted, disk erased (APFS volume `machd`),
|
||||
licence accepted, and **"Reinstall macOS Sequoia" was downloading the full OS from Apple** over inspiron's Wi-Fi
|
||||
(installer estimate ~2 h 50 min from 23:33). Per the coordinator, the VM is **shut down cleanly before 01:30**
|
||||
with the disk kept. See "Progress at shutdown" below for exactly where it got to.
|
||||
- **No Apple ID** was created or used. Nothing signed in to Apple.
|
||||
- **iOS Capacitor project:** `ios/` (Capacitor **7.6.x**, Swift Package Manager, no CocoaPods), app id
|
||||
`dev.eom.wikideck`, URL scheme `dev.eom.wikideck` registered for the SSO redirect.
|
||||
- **Build script:** `scripts/ios/build-sim.sh` (run inside the VM once Xcode is installed). Not yet run: needs Xcode.
|
||||
|
||||
## Where things are (inspiron-3670, outside git)
|
||||
| Path | What |
|
||||
|---|---|
|
||||
| `~/worker/jobs/macos/boot-macos.sh` | Starts the VM: 8 GB RAM, 4 vCPU, q35, OpenCore, VNC 127.0.0.1:5911, SSH fwd 127.0.0.1:10022 |
|
||||
| `~/worker/jobs/macos/mac_hdd_ng.qcow2` | 80 GB macOS system disk (keep this) |
|
||||
| `~/worker/jobs/macos/BaseSystem.img` | Sequoia recovery (3,221,110,784 bytes), converted from macos-fetch's verified `BaseSystem.dmg` |
|
||||
| `~/worker/jobs/macos/OpenCore-osxkvm.qcow2` | OpenCore bootloader from kholia/OSX-KVM |
|
||||
| `~/worker/jobs/macos/OVMF_CODE_4M.fd`, `OVMF_VARS.fd` | UEFI firmware and this VM's NVRAM |
|
||||
| `~/worker/jobs/macos/vnc.sh` | `vncdotool` wrapper (`./vnc.sh capture x.png`, `./vnc.sh type ...`) |
|
||||
| `~/worker/jobs/macos/guest/provision.sh` | Runs **inside** macOS: Command Line Tools + Node 24 (no Apple ID) |
|
||||
| `~/worker/jobs/macos/CREDENTIALS.txt` | Local macOS user + password (mode 600, never in git), once the account exists |
|
||||
|
||||
## Start the VM again (resume)
|
||||
On inspiron-3670:
|
||||
```
|
||||
cd ~/worker/jobs/macos
|
||||
setsid ./boot-macos.sh > qemu.log 2>&1 < /dev/null & # installer image still attached
|
||||
# after macOS is fully installed you can detach it: NO_INSTALLER=1 setsid ./boot-macos.sh ...
|
||||
```
|
||||
- In the OpenCore picker pick **`macOS Installer`** / **`machd`** (whichever is offered after the interrupted install;
|
||||
if only "macOS Base System" shows, the download restarts: pick it → **Reinstall macOS Sequoia** → disk `machd`).
|
||||
- Clean shutdown from outside: `echo system_powerdown | socat - UNIX-CONNECT:$HOME/worker/jobs/macos/qemu-monitor.sock`
|
||||
(or `kill $(cat ~/worker/jobs/macos/qemu.pid)` if the guest is hung).
|
||||
|
||||
### See it (VNC through an SSH tunnel from tower-plus)
|
||||
```
|
||||
ssh -N -L 5911:127.0.0.1:5911 eric@inspiron-3670 # on tower-plus
|
||||
# then open a VNC viewer on tower-plus at localhost:5911 (no VNC password; it is bound to localhost only)
|
||||
```
|
||||
SSH into macOS (after Remote Login is on): `ssh -p 10022 <user>@127.0.0.1` on inspiron, or tunnel `-L 10022:127.0.0.1:10022`.
|
||||
|
||||
Note: the VNC keyboard via `vncdotool` drops Shift (everything types lowercase, `|` becomes `\`). A normal VNC viewer is fine.
|
||||
|
||||
## Eric's checklist from here (~10 min of attention, plus download time)
|
||||
1. **Finish the install:** start the VM (above), open VNC, let the installer finish (several reboots, pick `machd` /
|
||||
`macOS Installer` in OpenCore each time if it doesn't auto-boot).
|
||||
2. **Setup Assistant:** country, *skip* Apple ID ("Set Up Later"), create a local admin user. Put the user and password in
|
||||
`~/worker/jobs/macos/CREDENTIALS.txt` (`chmod 600`).
|
||||
3. **Enable SSH:** System Settings → General → Sharing → Remote Login: on.
|
||||
4. **Prerequisites (no Apple ID):** copy and run the guest script:
|
||||
```
|
||||
scp -P 10022 ~/worker/jobs/macos/guest/provision.sh <user>@127.0.0.1:
|
||||
ssh -p 10022 <user>@127.0.0.1 ./provision.sh
|
||||
```
|
||||
5. **Sign in with your Apple ID and install Xcode** (App Store, or developer.apple.com/download). Launch it once,
|
||||
accept the licence, install the **iOS platform + a Simulator runtime** when prompted.
|
||||
6. **Build and run:**
|
||||
```
|
||||
ssh -p 10022 <user>@127.0.0.1
|
||||
git clone -b night/2026-11-16 https://gitea.eom.dev/claude/wikideck.git && cd wikideck
|
||||
scripts/ios/build-sim.sh # optional arg: simulator name, default "iPhone 16"
|
||||
```
|
||||
It runs `npm ci`, `npm run build`, `npx cap sync ios`, `xcodebuild` for the simulator (no signing), installs and
|
||||
launches `dev.eom.wikideck`, and saves a screenshot to `~/wikideck-ios-sim.png`.
|
||||
|
||||
## App notes
|
||||
- Scaffold (`capacitor.config.ts`, Capacitor deps in `package.json`) is owned by mobile-android (#8); `ios/` builds on it.
|
||||
Capacitor **7** to match Android (Node 20 on inspiron).
|
||||
- **Swift Package Manager**, not CocoaPods: `ios/App/CapApp-SPM/Package.swift` is managed by `npx cap sync`; Xcode
|
||||
resolves `capacitor-swift-pm` itself. No Ruby/CocoaPods needed in the VM.
|
||||
- **Testnet build:** `build-sim.sh` sets the same defaults as `android/build-debug.sh`: `VITE_WIKIDECK_NETWORK=testnet`,
|
||||
`VITE_WIKIDECK_GENESIS_TIME=1792411200`, `VITE_NODE_URL=http://192.168.1.32:3101` (override via env).
|
||||
- **Plain HTTP to the LAN node:** `Info.plist` sets `NSAppTransportSecurity` → `NSAllowsLocalNetworking` (local/IP hosts
|
||||
only, not arbitrary HTTP), because iOS ATS blocks cleartext by default. From the VM's simulator, 192.168.1.32 is reached
|
||||
through QEMU's user-mode NAT on inspiron.
|
||||
- **Plugins:** `@capacitor/app` and `@capacitor/browser` (from #35) are wired into `CapApp-SPM/Package.swift`.
|
||||
- **Origin check:** mobile-android routes native requests through `CapacitorHttp`, which sends no `Origin` header, so
|
||||
`server/testnet/http.ts` needs no change. Without it, the iOS WebView origin would be `capacitor://localhost`.
|
||||
- **SSO (#7):** `Info.plist` registers the `dev.eom.wikideck` URL scheme; redirect `dev.eom.wikideck:/oauth/callback`
|
||||
returns to the app via `@capacitor/app`'s `appUrlOpen`.
|
||||
|
||||
## Progress at shutdown
|
||||
_(filled in before 01:25)_
|
||||
|
||||
## What's verified
|
||||
- `BaseSystem.dmg` sha256 matches macos-fetch's `SHA256SUMS`; converted `BaseSystem.img` is 3,221,110,784 bytes.
|
||||
- VM boots on inspiron (KVM, no host `ignore_msrs` change needed): OpenCore → Sequoia recovery → Terminal, Disk Utility.
|
||||
- Disk erase (APFS) and the installer download started.
|
||||
- `npx cap add ios --packagemanager SPM` (Capacitor 7.6.10) generates the project on Linux; bundle id `dev.eom.wikideck`.
|
||||
- **Not verified:** the macOS install finishing, Xcode, `build-sim.sh`, the app in the Simulator.
|
||||
@@ -0,0 +1,75 @@
|
||||
# WikiDeck Night 1: report
|
||||
|
||||
**Night:** 2026-11-16 22:45 → 2026-11-17 01:30 EST. 17 Claude agents on 4 machines, coordinated through Gitea (milestone 63, issues #1–#10).
|
||||
**Branch:** `claude/wikideck:night/2026-11-16`. Everything below came in through 38 PRs that night-review reviewed and night-lead squash-merged.
|
||||
**Untouched:** the live deployment, mainnet, and every consensus and protocol file. The off-limits list is in `docs/night/BOUNDARIES.md`.
|
||||
|
||||
## What works
|
||||
|
||||
| Area | Status | Where |
|
||||
|---|---|---|
|
||||
| **The game, "Edit War"** | Playable in the browser against an AI: a lobby, a deck builder with 4 loaner starter decks, matches, results and a tutorial. Works on a 360 px phone. | `src/game/`, PR #26 #30 (landing page, upstream WikiDeck/wikideck#3), #31 (easy and normal browser bots), #45 |
|
||||
| **Rules engine** | Pure, deterministic TypeScript with the rules as data. `createMatch`, `legalActions`, `applyAction`, `viewFor` and serialisation. 6 keywords and 6 Portals. Property tests, plus a §12 golden match checked by hand. | `shared/game/`, `docs/game/ENGINE_API.md`, #25 #27 #29 #33 #36 (v1.1 as the default), #38 (planning is hidden) |
|
||||
| **Design** | DESIGN.md v1 (frozen 23:01), then v1.1 tuned from the balance report. | `docs/game/DESIGN.md`, #13 #17 #23 #24 #32 |
|
||||
| **Card data** | 236 sampled articles, with real distributions, percentile tables and 48 starter pageIds. | `docs/game/CARD_DATA.md`, `card-sample.json`, #20 #28 |
|
||||
| **Balance** | Bots (random, greedy, lookahead) played thousands of matches per ruleset. On v1 the starter pairings ranged 23–77%, and the first player won 53.4%. The v1.1 re-run measured the first player at **51.2%**, starter decks at **52–53%** and owned decks at **42–51%** against starters, so owning NFTs adds variety, not power. | `docs/game/BALANCE.md`, `shared/bots/` #14 |
|
||||
| **eom.dev accounts** | Dex OIDC with PKCE: login and logout, and ID tokens verified against the JWKS. Wallet linking signs a message the **client builds**, never text from the server. The account ↔ wallet map is stored off-chain. | `server/account/`, `src/auth/`, #15 #37 #42 |
|
||||
| **Peer-hosted modes** | Modes are JSON data, never code. A node publishes them at `GET /api/game/modes`, peers are discovered through config, and the hosting node runs the match. It shows "Hosted by", with per-mode and host leaderboards. 3 example modes: classic, snake draft and trending. Lobbies survive restarts. | `shared/game/modes.ts`, `server/game/`, `docs/game/HOSTING.md`, #22 #43 |
|
||||
| **Private testnet** | 3 nodes on poweredge-r350, LAN only, at height 50. Auto-redeploy followed this branch until the freeze, with rolling restarts that wait for live matches to finish. | `deploy/night/`, #16 #19 #39 #40 |
|
||||
| **Android app** | Capacitor 7 (`dev.eom.wikideck`). A debug APK runs a full match against the AI in the emulator. CapacitorHttp gets past the node's Origin check with no server change. The SSO deep link round trip works up to Dex. | `android/`, `docs/night/ANDROID.md`, #35 #41 #44 |
|
||||
| **iOS app** | Capacitor 7 iOS project (SPM) and a simulator build script. The macOS Sequoia VM's install was still running at the end of the night. No Apple ID was used. | `ios/`, `docs/night/IOS.md`, #34 #52 |
|
||||
|
||||
## How to try it
|
||||
- **Browser:** http://192.168.1.32:3101, :3102 or :3103 (LAN only). Open **Play**, dismiss the tutorial, pick a starter deck and play the AI. The three nodes host different modes: A has classic and trending, B has draft, and C has all three.
|
||||
- **Android:** the APK is at `inspiron-3670:~/worker/jobs/night/mobile-android/apk/wikideck-night1-debug.apk` (debug-signed, testnet build). To rebuild it: `android/build-debug.sh`. Screenshots:
|
||||
|
||||

|
||||
- **iOS:** follow Eric's checklist in `docs/night/IOS.md`:
|
||||
1. resume the VM on inspiron and finish the macOS install
|
||||
2. sign in with your Apple ID
|
||||
3. install Xcode
|
||||
4. run `scripts/ios/build-sim.sh`
|
||||
|
||||
No Apple ID was used tonight. The VM got as far as the Sequoia installer downloading the full OS. Per the coordinator, the VM is shut down cleanly before 01:30 with its disk kept. `docs/night/IOS.md` (#52) records the install progress at shutdown, the resume steps and Eric's checklist.
|
||||
- **Login:** "Log in with eom.dev" uses Dex at `https://dex.eom.dev/`, through the `wikideck` public client that the coordinator applied. You need a membership account that's in `Dex Users`; the SSO issue #7 covers the sign-up path.
|
||||
|
||||
## QA (night-review, live testnet)
|
||||
- **API:** full hosted matches in all 3 modes (classic @A, snake draft @B, trending @C) with two scripted players. Records and leaderboards are correct. Rejected as they should be: forged card, cross-seat token, random token, client `timeout`, foreign Origin, self-join, out-of-turn pick.
|
||||
- **Browser:** Playwright played 3 full matches against the AI through the real Play UI (360×740 @A ×2, 1280×800 @B). Every one reached results, with no overflow, stuck turns or page errors.
|
||||
- **Engine fuzz:** 300 random matches per engine branch. 0 `viewFor` leaks (information-flow test), and every replay was deterministic.
|
||||
- **UX bug found and fixed:** the results card showed tied Topics ("13–13 Lost") with no tie-break explanation. Fixed after the freeze in #51.
|
||||
|
||||
## Known issues and gaps
|
||||
1. **The game ships rules v1.1** (`DEFAULT_RULESET = RULESET_V1_1`, #36), which matches DESIGN.md v1.1. The v1.1 numbers in BALANCE.md (first player 51.2%, starter decks 52–53%, owned decks 42–51%) were measured **before** #38 hid the opponent's queue, so the seat figure needs a re-run. Item 6 (`nostalgic` and `translated` at −1 power) is a v1.2 candidate and isn't in v1.1.
|
||||
2. **Hosted PvP trusts the host.** The seed is chosen by the host, and DESIGN §4.4's commit–reveal isn't implemented. A malicious host can see both hands. That's documented in HOSTING.md.
|
||||
3. **Hidden information.** #38 hides the opponent's queue during planning (with a test). The UI and the bots consume only `viewFor` output, and the log never names an opponent's hidden card. Remaining: `obscure` (item 4) and host trust (item 2).
|
||||
4. **The `obscure` keyword isn't masked in `viewFor`.** Modes reject it, so it can't be turned on.
|
||||
5. **Game traffic shares the chain's per-node RPC budget,** so one hot client can get everyone 503s (#6).
|
||||
6. **Wikipedia rate limits:** our egress IP got HTTP 429s on the action API. #19 adds an optional `WIKIDECK_USER_AGENT` with a contact URL, and only the testnet sets it. **The live deployment probably shares that IP and the old generic UA.** Whether to set it in production is Eric's decision.
|
||||
7. **Mobile polish:**
|
||||
- the dashed lane drop zone doesn't take taps, only the lane plate does
|
||||
- the home hero still says "Explore mining" inside the app
|
||||
- the real SSO login hasn't been done on a device yet
|
||||
- **Apple licences:** an agent clicked through the **macOS installer licence** in the VM, under Eric's VM approval on #9. Review that if you want to accept it yourself.
|
||||
- `scripts/ios/build-sim.sh` still runs `sudo xcodebuild -license accept`, which would accept Apple's Xcode licence on Eric's behalf. **Eric should accept it himself** (remove the line first).
|
||||
- Android allows cleartext HTTP to **any** host (`usesCleartextTraffic="true"`). Before any non-LAN use, restrict it with a `network_security_config` to the testnet host.
|
||||
8. **Factions are skewed:** owned cards are about 53% Culture and 0% Space, so `viral` and `local` dominate. Factions built on Wikidata P31 are the v1.1+ fix (CARD_DATA findings 6 and 7).
|
||||
9. **Tooling:** the repo needs **Node 24** (`node:sqlite`). On Node 20, 12 tests fail falsely. Every gate tonight ran in `node:24-alpine`.
|
||||
|
||||
**Held for Eric:** #49 (the normal bot uses sim-balance's lookahead). It's approved, but it's a behaviour change that arrived after the freeze.
|
||||
|
||||
## Next steps (in priority order)
|
||||
1. **Re-run balance on the final head** (after #38) and decide v1.2 item 6. The harness is `scripts/sim/` and `shared/bots/`, and it needs about 1 GB on r350, run under the heavy lock.
|
||||
2. **Hidden information everywhere:** mask `obscure`, and implement the §4.4 commit–reveal seed for hosted PvP.
|
||||
3. **Separate rate limits for game traffic** on the node, so they don't share the chain's RPC budget.
|
||||
4. **Finish iOS:** Xcode and a simulator run, then the same match against the AI as on Android.
|
||||
5. **SSO end to end** on a device with a real eom.dev account, then show account names on the leaderboards.
|
||||
6. **Factions from Wikidata P31**, then re-run the balance sims (item 6 on the BALANCE list is still open).
|
||||
7. **Host incentives on-chain:** the proposal in HOSTING.md. It's a protocol change, so it needs its own review.
|
||||
8. **Production user agent:** decide whether the live node should set `WIKIDECK_USER_AGENT`.
|
||||
|
||||
## Process notes
|
||||
- Every agent shared the `claude` Gitea account, so night-review approved with COMMENT reviews that start with `VERDICT: APPROVED`, naming the head SHA and the gate result.
|
||||
- **imac's Gitea MCP was down** all night. The council read issues anonymously and reported through PR bodies, and night-lead relayed.
|
||||
- **tower-plus ran out of memory** at about 23:25, and **r350 twice**. From then on, every heavy check ran on inspiron in `node:24-alpine` under `flock /tmp/night-heavy.lock`.
|
||||
- Squash merges dropped the history that stacked PRs shared, which caused add/add conflicts (#27, #22, #26). Each was resolved mechanically, with no content changes.
|
||||
|
After Width: | Height: | Size: 143 KiB |
@@ -0,0 +1,45 @@
|
||||
# Node resource controls — stage 1
|
||||
|
||||
This stage bounds public RPC transport/admission and browser state loading without changing consensus, chain identity, or launch approvals. **It does not make the node production-ready.**
|
||||
|
||||
## Admission and transport
|
||||
|
||||
API and P2P traffic have separate process-local token buckets. API saturation does not spend P2P tokens. Both lanes still share the event loop, ledger mutation queue, native engine and host resources: this is admission separation, not CPU/process isolation. Budgets are global per process rather than per wallet/IP, so changing wallet or source IP cannot bypass the global limit. Existing per-IP limits remain in place; no permissive proxy trust was enabled.
|
||||
|
||||
Admission precedes JSON parsing, signature verification and route work. Excess traffic receives 503 plus `Retry-After: 1`; there is no unbounded retry queue. JSON request bodies remain capped at 68 KiB and compressed request inflation is disabled. Response JSON is capped before transmission. Byte budget is charged on serialized JSON bytes, not network/TLS framing. Small error responses are not charged recursively when rejecting a payload/budget; edge limits are still needed.
|
||||
|
||||
| Variable | Default | Accepted range |
|
||||
| --- | --- | --- |
|
||||
| `WIKIDECK_RPC_REQUESTS_PER_SECOND` | 120 | 1–1000 |
|
||||
| `WIKIDECK_RPC_WRITES_PER_SECOND` | 10 | 1–100 |
|
||||
| `WIKIDECK_RPC_MAX_ACTIVE` | 32 | 1–256 |
|
||||
| `WIKIDECK_RPC_RESPONSE_BYTES` | 2097152 (2 MiB) | 128 KiB–2 MiB |
|
||||
| `WIKIDECK_RPC_BYTES_PER_SECOND` | 8388608 (8 MiB/s) | 2–128 MiB/s |
|
||||
| `WIKIDECK_RPC_LEGACY_BLOCKS` | 128 | 0–128 |
|
||||
|
||||
Token bursts equal one second of the configured rate. P2P uses a separate fixed lane of 40 requests/s, 10 writes/s and 16 active HTTP responses, with the same configured byte limits. Active slots are released on response finish/connection close; asynchronous route work already admitted may still be completing after disconnection. Existing bounded native, ledger and Wikimedia queues/concurrency remain necessary.
|
||||
|
||||
HTTP has at most 256 accepted connections, 10-second headers timeout, 15-second request timeout, 5-second idle keepalive and a 30-second socket inactivity timeout. These are process transport protections, not a substitute for proxy timeouts/connection limits, global ingress limits, OS limits or load-balanced per-instance policy. Body parsing is no longer ahead of admission. Health bypasses the API lanes for liveness, but still shares server connections and CPU.
|
||||
|
||||
Configuration is validated before opening node resources. Lower limits can shed legitimate traffic, including sync; test settings against the intended topology before deploying. Do not raise limits merely to hide overload. Custom settings require container environment forwarding when deploying with Compose.
|
||||
|
||||
## Bounded state API
|
||||
|
||||
- `GET /api/summary`: network/chain/genesis, canonical tip/height/work, process-local revision, peers/maturity and bounded pending transactions. No full-chain copy. Revision is only a local cache invalidation counter, not consensus or a durable sequence.
|
||||
- `GET /api/canonical?tip=<hash>&offset=0&limit=16`: up to **16 canonical blocks**, pinned to the current tip. Tip changes return 409 so the caller restarts. Offset cannot exceed current height. Each page uses the cached canonical branch and clones only its slice. The first page after a new tip may rebuild that branch in O(height).
|
||||
- Legacy `/api/state` and `/api/chain` still return full snapshots only up to the configured legacy height and response-byte cap. Beyond it, they return 413 with paging instructions **before full snapshot cloning**. They never silently truncate ownership history. Legacy scripts/API clients must migrate to paging for longer chains.
|
||||
- `/p2p/status` and `/p2p/mempool` now obtain only the fields needed instead of cloning the chain. P2P block inventory semantics are unchanged.
|
||||
|
||||
The browser and trade signing refresh use bounded streaming response reads (2 MiB/page), pagination/network/tip/parent continuity checks, one restart on tip conflict, shared in-flight loads, and append-history cache reuse. A final summary confirms the loaded tip. These checks are **not independent PoW/consensus verification**: the UI still trusts the node.
|
||||
|
||||
The existing snapshot-based UI still assembles complete ownership history, capped at **10,000 blocks or 64 MiB of encoded history** with a 30-second fetch deadline. If exceeded, it fails explicitly rather than presenting partial ownership as complete. That is a client resource guard, not a solution for an archival-sized wallet/explorer. Full state objects and parsed JS memory cost more than encoded JSON. A truly indexed wallet and fully paged explorer remain required before closing SEC-01. An unchanged refresh requests two summaries and no block pages; append loading verifies the cached prefix and requests only new blocks.
|
||||
|
||||
## Tests and safe load tooling
|
||||
|
||||
Final validation: **86 tests passed, 0 failed, 0 skipped** in the Node 24 Docker test image, including real RandomX HTTP integration. TypeScript/Vite build passed. The suite includes deterministic token refill/write/active/byte limits; a held-response 40-request loopback burst (4 admitted, 36 shed); health/P2P-lane availability during API saturation; canonical paging defensive copies/tip conflicts/legacy guards; client append caching, malformed pages/continuity, bounded history, single-flight loading and response size checks; non-recursive oversized-response errors; and paging against the real RandomX HTTP fixture.
|
||||
|
||||
`test:rpc-load` invokes the read-only [local smoke-load script](../scripts/rpc-load.ts). It requires `--consent`, accepts only **literal loopback IP origins** (not remote hosts or DNS names), at most 32 workers and 1,000 total requests. Options: `--node`, `--concurrency`, `--requests`. It reads summary and canonical-chain endpoints and checks health, with response/time bounds. It never submits a block or transaction. Use only a disposable isolated node: even read traffic consumes CPU/IO. Output includes status counts, bytes and p50/p95 latency; rejected load is visible, not counted as successful capacity.
|
||||
|
||||
Initial smoke measurements on a disposable empty-chain loopback Docker node are historical local baselines, not performance guarantees. They do not measure hashing load, long-chain costs, or hostile Internet traffic. The deterministic held-response test separately verifies overload shedding and peer/health-lane availability. Final test totals must be rerun against the selected release artifact.
|
||||
|
||||
Neither measurement establishes that a realistic long-chain public deployment meets its latency/throughput SLO. Production-scale chain/journal fixtures, slow clients, adversarial payloads, sustained concurrency, disk pressure and multi-host recovery measurements remain outstanding. No launch-readiness finding is marked resolved by this stage.
|
||||
@@ -0,0 +1,42 @@
|
||||
# Deployment, private monitoring, and recovery
|
||||
|
||||
**Production remains NO-GO.** These procedures are operator preparation, not an installed public edge, configured alerts, independent review, or deployment approval. Do not remove persistent node volumes as part of source cleanup.
|
||||
|
||||
## Reverse-proxy trust
|
||||
|
||||
`WIKIDECK_TRUSTED_PROXIES` is empty/untrusted by default. It accepts up to 16 comma-separated literal IPs or bounded CIDRs. Configure only the actual source address of a trusted edge connection. The edge must overwrite forwarded headers, and firewall rules must prevent direct backend access. A trusted-proxy setting does not configure the firewall.
|
||||
|
||||
The [nginx example](../deploy/nginx.conf.example) is not installed or deployment-validated. Replace its reserved hostname and certificate paths, and validate TLS, renewal, forwarded-IP handling, body/connection/time limits, and edge admission controls on the intended host. Container proxy source addresses may differ from host loopback; inspect the actual topology instead of copying a trust list blindly.
|
||||
|
||||
## Private diagnostics
|
||||
|
||||
Set `WIKIDECK_OPS_PORT` to an unused port (1–65535) to enable a separate HTTP listener bound to `127.0.0.1`; leave it unset to disable it. Never publish or reverse-proxy this port. Only `GET /status` is supported. It returns bounded, no-store aggregate JSON; any local process with loopback access can read it.
|
||||
|
||||
Reported diagnostics include node uptime/RSS, event-loop delay, canonical height and tip age, DAG and pending counts, native-engine status, configured/connected peers, RPC budgets, and available disk plus ledger database/WAL sizes. Native subprocess memory is not included in Node RSS. Peer count is not a security score. Health is liveness, not sync readiness or consensus assurance.
|
||||
|
||||
`ops:check -- --port <private-port>` reads only literal loopback with bounded time and response size. It emits warnings for stale/empty chain, peer isolation, native-engine failure, queue pressure, event-loop delay, and unavailable/low disk. Thresholds are starting points, not production SLOs. Route alerts to an external system and test delivery; this repository does not install a scheduler or alert destination.
|
||||
|
||||
## Stopped-node ledger backup
|
||||
|
||||
`node:backup` supports `create`, `verify`, and `restore`. New version-2 packages contain only the selected network's ledger database. Stop the node cleanly first; the tool takes the same exclusive network lock as startup, uses SQLite `VACUUM INTO`, checks SQLite integrity and chain metadata, hashes the snapshot, and writes the manifest last. It refuses to overwrite a destination, restore in place, or run when a node lock exists. Restore targets must not exist.
|
||||
|
||||
Example workflow, using the `node:backup` package command with explicit `--source`, `--destination`, and `--consent` as required by the CLI:
|
||||
|
||||
1. Stop the node and confirm all writers to its data directory are stopped.
|
||||
2. Create the backup in a new directory outside the node data directory. Keep wallet backups separately; this tool does not include browser wallets, secrets, configuration, binaries, or logs.
|
||||
3. Run `verify` against the backup before copying it off-host.
|
||||
4. Restore only to a new isolated data directory. The tool reports `proofsRevalidated: false`; reopen with the trusted RandomX implementation and verify the chain before resuming service.
|
||||
|
||||
Backups are not encrypted or authenticated by this tool. Store them in restricted, encrypted off-host storage, protect the manifest separately, and test cold restoration. Hashes detect accidental corruption, not a coherent malicious replacement. Filesystem, power-loss, Windows ACL, and network-share durability need validation on the actual storage platform.
|
||||
|
||||
## Retiring legacy financial data safely
|
||||
|
||||
Removing market/custody source code does **not** delete or resolve data left by an older deployment. The card-only node does not open or reconcile those files. If the selected network directory contains `market.sqlite`, `custody-sandbox.sqlite`, or a `custody-postgres.json` binding, new ledger-only backup creation refuses to proceed rather than silently omit those records. Preserve the existing volume and any PostgreSQL database; arrange an operator-reviewed archive before retiring it.
|
||||
|
||||
Historical version-1 paired backups containing `ledger.sqlite` and `market.sqlite` remain verifiable and restorable as opaque files for preservation. Restoration does not reactivate market services or imply that financial obligations have been resolved. External PostgreSQL data is not contained in a SQLite package. Do not delete old volumes, journals, database credentials, or backups as part of this source cleanup.
|
||||
|
||||
An operator must choose retention, recovery point/time objectives, off-host storage, and restore ownership. Never remove a lock or replace a running volume just to make recovery succeed.
|
||||
|
||||
## Remaining operational evidence
|
||||
|
||||
Verify the intended HTTPS/proxy/firewall topology, peer and tip freshness, alert delivery, disk growth, backup encryption/retention, and restore/replay time on the actual host. Assign an incident responder and document stop/rollback criteria. See the [card-only production plan](card-only-production-plan.md), [operator launch register](operator-launch.md), and [security review](security-review.md). No startup or payment approval is granted by these tools.
|
||||
@@ -0,0 +1,60 @@
|
||||
# Operator launch preparation and hold points
|
||||
|
||||
The [card-only production readiness plan](card-only-production-plan.md) defines the product scope and release gates. The supported product is mining, collecting, and direct card-for-card trades. Market, custody, and payment source has been removed. **Current decision: HOLD / NO-GO for mainnet, valuable assets, or public exposure until the relevant evidence below is reviewed.**
|
||||
|
||||
A successful build, local container startup, peer URL count, genesis timestamp, or configured approval flag is not proof of network security. The read-only launch preflight reports local blockers; it does not certify the release. The operator has chosen not to commission external audits and accepts the corresponding residual risk.
|
||||
|
||||
## Safe inspection
|
||||
|
||||
Use Node.js 24 and a clean, reviewed checkout. For mainnet assessment, select `WIKIDECK_NETWORK=mainnet` and run `launch:preflight`. Use `--network-manifest` for chain identity inspection. These commands do not start a node, create a ledger, start RandomX, or contact peers.
|
||||
|
||||
Mainnet startup is gated by a chain-specific approval, explicit unaudited-risk acceptance, the candidate genesis time, HTTPS origin, and multiple configured HTTPS peers. These are accident-prevention checks only; they do not prove peers are online/independent or that a network is secure. Keep deployment and release permissions restricted.
|
||||
|
||||
## Evidence required before a public non-monetary testnet beta
|
||||
|
||||
A beta is not mainnet production, valuable-asset use, or a claim of independent network security. Keep testnet explicitly selected, cards valueless, and the deployment described as experimental. Before public exposure:
|
||||
|
||||
- Freeze the card-only scope, testnet identity, known risks, privacy and data-retention terms, user support/contact, abuse-report path, and stop conditions.
|
||||
- Prefer managed hosting unless the intended host proves ISP permission/reachability, TLS renewal, trusted-proxy correctness, no direct backend exposure, firewall and admin controls, patching, and power/network resilience.
|
||||
- Run repeated load, mining, peer-sync, reorganization, crash/restart, and restore tests on the exact release candidate and intended hardware. Set measurable latency, error, memory, CPU, disk, and recovery limits.
|
||||
- Review wallet migration, lock/unlock, signing, backup, and fresh-profile recovery. Explain same-origin compromise and irreversible-transfer risks.
|
||||
- Deploy external monitoring and verify alert delivery for peer/tip freshness, reorgs, native failures, overload, disk growth, and service availability. Name a responder and test incident/rollback procedures.
|
||||
- Encrypt backups off-host and rehearse a cold restore/replay. Define recovery objectives and keep wallet backups separate from node backups.
|
||||
- Freeze image/dependency/native versions, generate an SBOM, scan the final artifacts, and record exact release hashes and a beta go/no-go. Publish a project license before public distribution.
|
||||
|
||||
If these conditions cannot be verified on a self-hosted site, do not expose it publicly; use a managed host or remain local-only.
|
||||
|
||||
## Mainnet and valuable-card blockers
|
||||
|
||||
Mainnet or valuable-card use requires the beta evidence plus internally reviewed and measured consensus parameters, adversarial multi-host partition/reorg/hashpower testing, a credible bootstrap and independent-peer/miner plan, production capacity evidence, and explicit governance/upgrade and incident procedures. External audit is not planned; the operator must record acceptance of this extra risk. The current initial target is deliberately easy and the retarget is not production-calibrated. Nodes retain the DAG in memory and replay proofs at startup. There is no formal finality or automatic peer discovery. Keep mainnet **NO-GO** until the remaining network and operational evidence is recorded and the operator explicitly accepts the residual risks.
|
||||
|
||||
## Hold-point register
|
||||
|
||||
Record owner, exact release/manifest, evidence location and hash, test/rehearsal, reviewer, residual risk, and disposition. Empty or unverified means **not passed**.
|
||||
|
||||
| Hold point | Required evidence | Current status |
|
||||
| --- | --- | --- |
|
||||
| Internal protocol/application review | Findings documented against the release; fixes have regression coverage; operator records unaudited-risk acceptance | Internal review and regression tests recorded; no external audit planned |
|
||||
| Consensus launch design | Final manifest; measured starting target/hashpower; timestamp, retarget, partition, and reorg analysis | Missing |
|
||||
| Node availability | Realistic long-chain and hostile-traffic capacity report with explicit limits | Missing |
|
||||
| Production wallet | Same-origin threat model, user confirmation, supported-browser lifecycle and offline recovery drill | Unverified |
|
||||
| Peer/miner topology | Independently administered hosts/failure domains, verified online peers, and sufficient independent hashpower | Unverified |
|
||||
| Edge and host security | TLS/certificate renewal, firewall, backend isolation, proxy trust, patching and restricted admin | Unverified |
|
||||
| Monitoring/on-call | External alert routes and successful drills for isolation, reorg, native failure, overload and disk pressure | Unverified |
|
||||
| Restore/reconciliation | Encrypted off-host ledger backup, isolated restore and proof replay; separate wallet recovery | Unverified |
|
||||
| Release supply chain | Frozen image digest, SBOM, dependency/native/container scans, provenance, and restricted release access | Partial; repeat for final artifact |
|
||||
| Incident/governance | Named decision owners, upgrade/fork policy, communications, rollback and stop criteria | Missing |
|
||||
|
||||
## Freeze and authorize
|
||||
|
||||
1. Fix known critical code findings in a new release and add regression coverage; do not change consensus rules under a launched chain ID. This is internal engineering, not external audit.
|
||||
2. Freeze the reviewed genesis/manifest, exact build/runtime profile, image digest, peer origins, and artifact hashes.
|
||||
3. Rehearse initial sync, independent mining, partitions/reconnects, invalid traffic, disk pressure, restart, and isolated full restore. Do not delete production data or weaken rules to pass a drill.
|
||||
4. Verify DNS/TLS, proxy forwarded-IP handling, no direct backend access, permissions, resource capacity, and monitoring on intended hosts. `/healthz` is liveness only.
|
||||
5. Record a go/no-go with operator name, evidence, known residual risks, change window, recovery objectives, and stop conditions in the controlled operations system.
|
||||
|
||||
Do not set the risk acknowledgement merely to bypass gates. It records acceptance of known risks; it does not attest that an audit occurred or make the system secure.
|
||||
|
||||
## Stop conditions
|
||||
|
||||
Treat deep reorgs, isolation, divergent manifests, sustained overload, disk exhaustion, native-engine failure, key compromise, or loss of monitoring as incidents. Stop accepting new exposure using the approved procedure. Stopping a node does not undo confirmed transactions. Preserve logs and backups; never delete the ledger, shorten history, or change genesis to get a node to start. Remove a stale lock only after verifying all owning processes have exited. Resolve chain conflicts under a reviewed incident policy, not with an ad hoc checkpoint or stale restore.
|
||||
@@ -0,0 +1,192 @@
|
||||
# Native RandomX engine
|
||||
|
||||
Wikideck's native CPU proof engine uses RandomX, the algorithm also used by Monero,
|
||||
designed to keep general-purpose consumer CPUs competitive. Mining a Wikideck block
|
||||
rewards its miner with a Wikipedia NFT card on Wikideck's independent chain. The Docker image builds this pinned
|
||||
implementation and runs its known-vector test. There is no GPU path, simulated hash,
|
||||
or production fallback hash.
|
||||
|
||||
This document covers building the executable, its memory modes, its line protocol,
|
||||
and the TypeScript adapter. For the user-facing install and run instructions, start
|
||||
with the [README](../README.md).
|
||||
|
||||
## Contents
|
||||
|
||||
- [Source and build](#source-and-build)
|
||||
- [Modes and resource use](#modes-and-resource-use)
|
||||
- [Line protocol](#line-protocol)
|
||||
- [Node API](#node-api)
|
||||
- [Real upstream known-vector check](#real-upstream-known-vector-check)
|
||||
|
||||
## Source and build
|
||||
|
||||
[RandomX v1.2.1](https://github.com/tevador/RandomX/tree/102f8acf90a7649ada410de5499a7ec62e49e1da)
|
||||
is fetched by CMake FetchContent from the official HTTPS Git repository, pinned to
|
||||
**102f8acf90a7649ada410de5499a7ec62e49e1da** (also the upstream v1.2.1 tag).
|
||||
The first configuration requires network access and Git; later builds reuse the
|
||||
checkout. Keep upstream copyright/license notices when distributing binaries.
|
||||
Do not override FetchContent sources with untrusted local code.
|
||||
|
||||
Requirements: CMake 3.24+, Git, a C/C++17 toolchain, and a 64-bit host for fast mode.
|
||||
MSVC needs its C++ and MASM tools in a developer terminal. MinGW needs its compiler
|
||||
and make on PATH; select the `MinGW Makefiles` generator. Linux/macOS need their
|
||||
normal C/C++ build tools. No administrator privileges or huge pages are required.
|
||||
On MSVC, upstream's pinned build invokes its own PowerShell assembly-generation
|
||||
script; review upstream build tooling before running under restrictive policies.
|
||||
|
||||
From the repository root:
|
||||
|
||||
```sh
|
||||
cmake -S native -B native/build -DCMAKE_BUILD_TYPE=Release -DWIKIDECK_RANDOMX_TESTS=OFF
|
||||
cmake --build native/build --config Release --target wikideck-randomx --parallel 2
|
||||
```
|
||||
|
||||
Convenience scripts (two compiler jobs by default):
|
||||
|
||||
```sh
|
||||
sh scripts/build-randomx.sh
|
||||
sh scripts/build-randomx.sh --test
|
||||
```
|
||||
|
||||
```powershell
|
||||
./scripts/build-randomx.ps1
|
||||
./scripts/build-randomx.ps1 -Generator 'MinGW Makefiles' -Test
|
||||
```
|
||||
|
||||
The scripts propagate configure/build/test failures. PowerShell execution policy
|
||||
must permit the script; do not bypass a managed policy. POSIX customization:
|
||||
`JOBS=2`, `RANDOMX_BUILD_DIR=/absolute/build/path`; PowerShell customization:
|
||||
`-Jobs 2`, `-BuildDirectory <path>`. Select a toolchain/generator through the normal
|
||||
CMake environment or a manual configuration. Don't switch generators in an
|
||||
existing build directory.
|
||||
|
||||
All generators place the executable directly under `native/build` (with `.exe` on
|
||||
Windows), including Release builds with multi-config generators.
|
||||
Upstream tests/benchmark/codegen are excluded from the default build: v1.2.1 does
|
||||
not provide a tests-disable option. No benchmark or dataset-heavy fast-mode test
|
||||
runs automatically.
|
||||
|
||||
## Modes and resource use
|
||||
|
||||
Run `wikideck-randomx` with no arguments for **light** mode (256 MiB cache plus
|
||||
approximately 2 MiB VM scratchpad and runtime overhead). `--fast` adds the real
|
||||
approximately 2080 MiB dataset; the 256 MiB cache is retained for key changes, so
|
||||
budget over 2.3 GiB per process. Dataset initialization is single-threaded and can
|
||||
be expensive. Neither mode allocates RandomX memory until its first valid request.
|
||||
Cache, dataset, and VM are reused for the same key. A changed key reinitializes the
|
||||
cache and, in fast mode, the entire dataset before creating a fresh VM.
|
||||
|
||||
Flags start with `randomx_get_flags()` (CPU-supported AES/JIT/Argon2 optimization).
|
||||
`RANDOMX_FLAG_SECURE` is explicitly added for VM JIT W^X, and upstream is compiled
|
||||
with `RANDOMX_FORCE_SECURE` for cache JIT policy too. Platforms without JIT use the
|
||||
reference interpreter; allocation/JIT failures are fatal, never a fake PoW result.
|
||||
No large pages are requested. RAII releases VM, dataset, then cache on normal EOF
|
||||
and caught errors. Public PoW key/cache data is not secret and is released, not
|
||||
claimed to be securely erased from physical memory.
|
||||
|
||||
## Line protocol
|
||||
|
||||
One ASCII command per LF-terminated line; CRLF is also accepted. Exactly one ASCII
|
||||
response line, flushed immediately, per valid command:
|
||||
|
||||
```text
|
||||
hash <key64hex> <blobhex>
|
||||
<hash64hex>
|
||||
|
||||
mine <key64hex> <blobhex> <target64hex> <nonceOffsetDecimal> <maxAttemptsDecimal>
|
||||
found <hash64hex> <nonceDecimal>
|
||||
exhausted
|
||||
```
|
||||
|
||||
`found` and `exhausted` are alternatives, not two responses. Input hex may use
|
||||
either case; output hashes are lowercase in the RandomX byte order. Keys and
|
||||
targets are exactly 32 bytes (64 hex characters); blobs are 1..8192 bytes.
|
||||
Tokens use exactly one ASCII space, without leading/trailing whitespace. Commands
|
||||
are capped at 16600 bytes before LF. Invalid characters, malformed/overflowing
|
||||
unsigned decimal, extra tokens, invalid bounds, or a partial final line cause a
|
||||
concise stderr error and nonzero exit, with no fabricated response on stdout.
|
||||
Empty stdin EOF exits successfully. There are no stdout banners or diagnostic logs.
|
||||
|
||||
Mining requires `maxAttempts` in 1..10000 and `nonceOffset + 8 <= blob.size`.
|
||||
The initial nonce is read from the blob's existing **eight little-endian bytes**.
|
||||
The first attempt uses that nonce, then increments by one and rewrites LE8 for
|
||||
each attempt. Only those eight bytes change. At uint64 maximum, search ends
|
||||
without wrapping. The native response contains an exact unsigned decimal nonce.
|
||||
|
||||
**Target convention: interpret the 32 output bytes and target bytes as unsigned
|
||||
BIG-ENDIAN integers; accept `hash <= target`. This intentionally differs from
|
||||
Monero's convention.** In particular, equal hashes pass. Never reverse the hash
|
||||
or target when using this interface.
|
||||
|
||||
## Node API
|
||||
|
||||
[RandomX](../server/testnet/randomx.ts) exports:
|
||||
|
||||
```ts
|
||||
interface PowEngine {
|
||||
hash(key: string, blob: Uint8Array): Promise<string>;
|
||||
close(): void;
|
||||
}
|
||||
class RandomX implements PowEngine {
|
||||
constructor(options?: { binary?: string; fast?: boolean });
|
||||
hash(key: string, blob: Uint8Array): Promise<string>;
|
||||
mine(key: string, blob: Uint8Array, target: string,
|
||||
nonceOffset: number, maxAttempts: number):
|
||||
Promise<{ hash: string; nonce: number } | null>;
|
||||
close(): void;
|
||||
}
|
||||
```
|
||||
|
||||
Binary precedence: `options.binary`, `RANDOMX_BINARY`, then the executable under
|
||||
the repository's native build directory (resolved relative to this module,
|
||||
independent of working directory). Relative explicit paths are resolved against
|
||||
the caller's working directory. Configure only a trusted executable: this is a
|
||||
native-code trust boundary, not a sandbox. The adapter uses `spawn` with a fixed
|
||||
argument array, `shell: false`, and pipe stdio; user data only enters stdin after
|
||||
strict validation. Missing/non-executable files throw in the constructor. Other
|
||||
spawn failures are retained and reject current/future requests.
|
||||
|
||||
Each instance owns one long-lived child, one active command, and at most 64 total
|
||||
active/queued requests. Calls are FIFO, including mixed hash/mine calls and key
|
||||
changes. Inputs are snapshotted before queuing. The 120-second deadline starts
|
||||
when each command is sent (includes cold cache/dataset initialization); queued
|
||||
requests wait for earlier work. Keep mining batches small enough to finish on the
|
||||
host CPU. The process is killed on timeout, malformed/unsolicited/oversized output,
|
||||
stream error, or crash, rejecting all outstanding work and subsequent calls.
|
||||
Responses and retained stderr are bounded. No automatic retry or process restart.
|
||||
|
||||
`mine` returns `null` for exhaustion and validates returned hash syntax, target,
|
||||
and nonce range (it does not independently recompute a native result). Because the
|
||||
API returns `number`, its entire requested nonce range must fit
|
||||
`Number.MAX_SAFE_INTEGER`; higher uint64 nonces are supported only by the direct
|
||||
native protocol. Invalid inputs reject without sending native work.
|
||||
|
||||
Always call `close()` in `finally`. It is idempotent, rejects pending/queued work,
|
||||
and sends EOF for graceful RAII cleanup; a busy child is forcibly killed after
|
||||
one second. A failed/closed instance cannot be reopened.
|
||||
|
||||
## Real upstream known-vector check
|
||||
|
||||
The opt-in `--self-test` executable argument validates upstream's exact
|
||||
[Hash test 1a/2a](https://github.com/tevador/RandomX/blob/102f8acf90a7649ada410de5499a7ec62e49e1da/src/tests/tests.cpp):
|
||||
|
||||
- Key: ASCII `test key 000` (12 bytes, **not NUL-terminated or zero-padded**).
|
||||
- Input: ASCII `This is a test` (14 bytes, no terminator).
|
||||
- Expected RandomX hash:
|
||||
`639183aae1bf4c9a35884cb46b09cad9175f04efd7684e7262a0ac1c2f0b4e3f`.
|
||||
|
||||
The self-test uses an internal API so the line protocol retains its strict
|
||||
32-byte-key requirement. Padding this upstream key to 32 bytes would change the
|
||||
hash and is not a valid reproduction of the vector. Self-test success is reported
|
||||
on stderr only, with exit zero; mismatch exits nonzero. `--fast --self-test` checks
|
||||
the same real vector in dataset mode, but requires the full memory allocation.
|
||||
|
||||
```sh
|
||||
cmake -S native -B native/build -DCMAKE_BUILD_TYPE=Release -DWIKIDECK_RANDOMX_TESTS=ON
|
||||
cmake --build native/build --config Release --target wikideck-randomx --parallel 2
|
||||
ctest --test-dir native/build -C Release --output-on-failure
|
||||
```
|
||||
|
||||
This test is OFF by default and is separate from the application's tests. Without
|
||||
a built native binary, no native engine or native test is run by the application.
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
# Security review and production readiness
|
||||
|
||||
## Decision: NO-GO for public production or valuable assets
|
||||
|
||||
This is an internal source-assisted readiness review, not a penetration test, formal consensus proof, or production certification. The operator has chosen not to commission external audits and accepts that residual risk. The card-only product consists of RandomX mining, wallets, collections, transfers, and direct atomic card trades. Market, custody, and payment components have been removed from the supported source tree; no real-money feature is part of this release.
|
||||
|
||||
A limited, non-monetary testnet beta may be considered only after the release-specific operational, wallet, capacity, recovery, and review gates in the [card-only production plan](card-only-production-plan.md) are met. Mainnet or valuable-card use remains **NO-GO**.
|
||||
|
||||
## Remaining production blockers
|
||||
|
||||
| Finding | Risk | Required disposition |
|
||||
| --- | --- | --- |
|
||||
| Consensus/economic security | Current initial proof-of-work target is deliberately easy and the ten-block retarget is not production-calibrated. Hashpower concentration, timestamp/retarget manipulation, eclipse, censorship, and reorganization costs have not been independently measured. RandomX use does not inherit Monero's security. | Measure representative hashpower; run multi-host clock, partition, stall, fork, and reorg simulations; document operator-accepted risk and freeze parameters/identity before launch. |
|
||||
| Node availability and scale | The DAG remains in memory, state-root work visits the NFT set, and startup revalidates stored proofs. Work, RAM, disk, and recovery time grow with history. | Repeated long-chain and hostile-traffic tests on intended hardware; define and validate latency, resource, storage, and recovery limits; establish an archival/capacity strategy. |
|
||||
| Wallet/key protection | Encrypted local storage helps while locked, but a compromised same-origin page, extension, browser, or OS can abuse an unlocked signer. Old plaintext copies and cross-browser recovery require careful handling. | Independent wallet review; supported-browser migration/lock/sign/backup/restore drills; document residual compromise and key-loss risks. Decide whether isolated/hardware signing is required. |
|
||||
| Deployment and operations | The real TLS/proxy/firewall topology, peer/miner independence, off-host recovery, alert delivery, and on-call response have not been verified. A liveness response is not readiness. | Verify intended hosts and external edge; test alert routes and incident procedures; encrypt off-host backups and complete an isolated restore/replay with measured recovery objectives. |
|
||||
| Release supply chain | A successful build or dependency advisory check does not establish artifact integrity or native/container safety. | Freeze base/dependency/native versions and image digest; produce an SBOM, scans, build provenance/signature, and restricted release process for the exact artifact. |
|
||||
| Governance and user terms | No production operator/reviewer sign-off, public support/abuse path, or published project software license is established. | Name accountable decision makers; publish license, support, privacy, experimental/no-value disclosures, abuse reporting, upgrade policy, and stop conditions. |
|
||||
|
||||
These are readiness gaps, not claims that each item is an exploited vulnerability. Local tests and rehearsals are useful, but they do not establish security or verify the intended production host.
|
||||
|
||||
## Implemented groundwork (not certification)
|
||||
|
||||
- Global RPC admission and response-byte budgets, bounded canonical pages, and client response/history checks reduce some resource-exhaustion exposure; they do not solve retained-DAG growth or prove a production capacity envelope. See [node resource controls](node-resources.md).
|
||||
- Local wallet vault encryption, explicit legacy migration, session expiry, and lock-aware signing improve storage lifecycle. They cannot protect an unlocked page from same-origin compromise. See [wallet security](wallet-security.md).
|
||||
- Stopped-node ledger backup/verify/restore and native-proof replay tests provide a local recovery starting point. They are not encrypted/off-host backup service, filesystem power-loss certification, or production RPO/RTO evidence. See [operations and recovery](operations-recovery.md).
|
||||
- The launch preflight is read-only and intentionally reports NO-GO while evidence is missing. Startup approval flags are accident-prevention gates, not proof of audit or readiness.
|
||||
|
||||
## Review evidence and limits
|
||||
|
||||
The exact release candidate must be rebuilt and fully retested after scope cleanup. No claims are made here about the user's production host, public peer topology, Internet-facing testing, native-code assurance, alert delivery, off-host recovery, or mainnet security. External audits are not planned; retain the NO-GO for mainnet/valuable assets until the remaining network, deployment, and recovery evidence is complete and the operator records informed risk acceptance. A successful test suite or container startup alone is insufficient.
|
||||
@@ -0,0 +1,96 @@
|
||||
# Experimental testnet consensus
|
||||
|
||||
Implementation reference for the current tree, **not a public-mainnet specification or security certification**. See [README](../README.md) for setup/wallet commands and [native-engine details](randomx-native.md) for RandomX tooling. Consensus code: [shared serialization](../shared/testnet.ts), [validation](../server/testnet/consensus.ts), [DAG/persistence](../server/testnet/ledger.ts), [peer transport](../server/testnet/peers.ts), [HTTP](../server/testnet/http.ts), [miner](../server/testnet/miner.ts).
|
||||
|
||||
This document is for operators and developers who need the exact current protocol
|
||||
rules. It is not a quick-start guide: consensus serialization and constants are
|
||||
implementation-specific, and changing them can create a different chain.
|
||||
|
||||
## Contents
|
||||
|
||||
- [Network, genesis and article selection](#network-genesis-and-article-selection)
|
||||
- [Header, work and three distinct identities](#header-work-and-three-distinct-identities)
|
||||
- [Targets, timestamps and epoch boundaries](#targets-timestamps-and-epoch-boundaries)
|
||||
- [Native NFT transition and commitments](#native-nft-transition-and-commitments)
|
||||
- [Fork choice, reorgs and storage](#fork-choice-reorgs-and-storage)
|
||||
- [Fixed peers and HTTP surface](#fixed-peers-and-http-surface)
|
||||
|
||||
## Network, genesis and article selection
|
||||
|
||||
- Network: `wikideck-randomx-testnet-6`, block version **6**. Genesis has no blocks, NFTs or work; first mined height is 1. No privileged issuance/admin mint key. Version 6 adds atomic NFT trade bundles and has a new chain identity; prior-version ledger files and wallet backups are not compatible.
|
||||
- `GENESIS_TIME = 1792411200` (Unix seconds). Let `S(x)` mean lowercase hex SHA-256 of UTF-8 `x`, and `J(x)` mean compact JavaScript `JSON.stringify(x)`; field order below is consensus-critical.
|
||||
- `MAX_TARGET` is `0fff` followed by 60 `f` digits. `CHAIN_ID = S(J([NETWORK, CONSENSUS, GENESIS_TIME, MAX_TARGET]))`, using the constants object's insertion order in the implementation. `CONSENSUS` identifies the random Wikipedia source and mint-statistics snapshot format.
|
||||
- `GENESIS_HASH = S(NETWORK + ':genesis:' + CHAIN_ID)`; `INITIAL_KEY = S(NETWORK + ':initial-key:' + CHAIN_ID)`. Nodes independently derive the same manifest and reject other network/chain IDs.
|
||||
- [Starter samples](../shared/catalog.ts) remain only as interface previews; they are not eligible for minting. Each mining-template request asks the fixed English Wikipedia API endpoint for up to ten random namespace-0 pages, with a plain-text extract and thumbnail. It makes at most three requests and returns a page with a usable extract and an HTTPS image on `upload.wikimedia.org` or `thumb.wikimedia.org`. A page may be minted repeatedly. There is no static fallback: if no pictured article or its statistics are available, template creation fails and the miner can retry.
|
||||
- The selected `Article` snapshot and `statsSnapshot` are copied into the block header and covered by the miner's block signature and block ID. `articleTuple = [pageId, revisionId, title, extract, image-or-empty-string, url, source, category]`. The at-mint statistics contain capture time, metadata revision, page bytes, language-link count/truncation, six-month pageviews when available, and the derived Attention/Depth/Reach scores. Missing pageviews are represented as unavailable, never invented zeroes. The node forces a fresh enrichment request for this snapshot; it is captured when the mining template is prepared, since changing it after work begins would invalidate the proof. Current UI statistics are fetched separately and may reflect later edits.
|
||||
- A repeated page still creates a distinct NFT: token identity includes the parent block, height, and owner. Validators check article/image and stats schemas, the page URL, Wikimedia HTTPS host, pageview summaries, derived scores, and block commitments, but do not constrain repeated page IDs.
|
||||
- Validators do **not** contact Wikipedia during consensus validation. They verify the committed snapshot's structure and internal metric summaries, not the API provenance or ongoing existence of the page/image. A miner can construct a syntactically valid snapshot itself; this experimental design avoids making block acceptance dependent on an external service being online. The node's template endpoint fetches the article and fresh statistics for ordinary mining clients.
|
||||
|
||||
## Header, work and three distinct identities
|
||||
|
||||
`headerMessage(h)` is `J([NETWORK, version, chainId, height, previousHash, createdAt, articleTuple(article), statsSnapshotTuple, owner, publicKey, target, key, transactionsRoot, stateRoot])`. `statsSnapshotTuple` commits capture time, revision, size/language counts, ordered monthly views and summary values, plus the three derived scores. It excludes the nonce. Hash its UTF-8 bytes with SHA-256 to obtain **32 raw bytes**, then append the nonce encoded as **8 unsigned little-endian bytes**. The resulting **40-byte mining blob** has nonce offset **32** (not a 32-bit nonce). Node's numeric interface restricts nonces to nonnegative safe integers; the native line protocol supports uint64.
|
||||
|
||||
| Identifier | Exact construction / meaning |
|
||||
| --- | --- |
|
||||
| Block ID (`hash`) | SHA-256 of the raw mining blob, lowercase hex. Does not include ECDSA signature bytes or the separate `powHash` field. |
|
||||
| RandomX proof (`powHash`) | Native RandomX of the mining blob using the 32-byte epoch key. Determines work eligibility and game rarity/stats, not the NFT ID. |
|
||||
| NFT ID (`tokenId`) | `S(J([NETWORK, CHAIN_ID, 'mint', previousHash, height, owner, article.pageId, statsSnapshotTuple]))`. The capture time and page statistics help distinguish repeated mints of the same page. Independent of nonce/proof/signature, avoiding a circular dependency through state commitment. |
|
||||
|
||||
Interpret RandomX output and target as **unsigned big-endian** integers; accept `powHash <= target` including equality. This differs from Monero's target convention. The initial/easiest threshold accepts exactly **1/16** of uniformly distributed hashes (expected 16 attempts). No fake or browser PoW is accepted by the production node.
|
||||
|
||||
The miner signs `J([NETWORK, 'block-claim', blockID])` using ECDSA P-256/SHA-256, IEEE-P1363 encoding. Address is SHA-256 of canonical SPKI DER public-key bytes. Nodes check public-key/address consistency, signature, body schema, exact parent/height, article, target, key, roots, mint ID, block ID and recomputed native proof. Signatures remain required even though their bytes are excluded from block identity.
|
||||
|
||||
## Targets, timestamps and epoch boundaries
|
||||
|
||||
- Desired spacing: **15 minutes (900 seconds)**; retarget interval: **10 ancestors**. Heights 1–10 use the initial target; height 11 first retargets. Otherwise inherit the parent target.
|
||||
- At each retarget, compare the last and first timestamps of the previous 10 blocks: expected span is **9 × 900 = 8,100 seconds**. Clamp elapsed to `floor(8,100/4) = 2,025` through `8,100*4 = 32,400` seconds, multiply the parent target by elapsed/8,100 with integer division, then clamp target to `[1, MAX_TARGET]`. Selection uses work, not height or wall-clock estimates.
|
||||
- A timestamp must exceed the median of up to **11** ancestors (sorted upper-middle for even counts; genesis time if none) and must be at most **120 seconds** ahead of validation time. Keep operator clocks synchronized.
|
||||
- Epoch key source height is `floor(max(0, height - 64) / 2048) * 2048`. Zero means `INITIAL_KEY`; otherwise use the ancestor block hash at that source height. Thus heights **1–2111** use the initial key, **2112–4159** use height 2048's hash, and height **4160** switches to height 4096's hash. Forks derive keys from their own ancestors.
|
||||
|
||||
## Native NFT transition and commitments
|
||||
|
||||
Each block executes its ordered transactions against its parent's NFT state, **then mints one NFT** to the block owner. State entries contain owner, sequence (initially 0), minted height and page ID. Transactions cannot spend this block's new issuance.
|
||||
|
||||
An individual transfer carries network, chain ID, `cardHash` (**NFT token ID**, despite the legacy field name), from, to, sequence, public key and signature. Its signed message is `J([NETWORK, 'nft-transfer', chainId, cardHash, from, to, sequence])`. **Transfer ID is SHA-256 of that message, excluding ECDSA signature bytes** to avoid signature-malleability identity changes. Require the current owner, matching public key, a different recipient, exact current sequence, valid signature, and inclusion height minus mint height **>= 2**; increment sequence on application. Replays and duplicate IDs within a block fail.
|
||||
|
||||
A trade is one `type: 'trade'` transaction with proposer and counterparty addresses, ordered offered/requested NFT legs (token ID plus current sequence), and one P-256 signature from each party over `J([NETWORK, 'nft-trade', chainId, proposer, counterparty, offeredLegs, requestedLegs])`, where each leg is `[cardHash, sequence]`. Both public keys must derive the respective party addresses. Each side must contain 1–8 distinct NFTs; duplicates across either side are rejected. At inclusion, validation checks **all** selected NFTs against the same pre-trade state, owners, sequences, maturity, and both signatures before writing any changes. If any leg is invalid, the entire trade is rejected; if valid, all offered ownerships move to the counterparty and all requested ownerships to the proposer, with each sequence incremented once. A trade counts as one mempool and block transaction and is committed by one transaction ID. It cannot be partially included or partially replayed. Offers are not reservations; stale offers fail validation.
|
||||
|
||||
`transactionsRoot` commits the **ordered transaction IDs** (individual transfer IDs or atomic trade IDs). `stateRoot` commits the complete **post-transaction, post-mint** state: sort token IDs lexicographically; each input leaf is `S(J([id, owner, sequence, mintedHeight, pageId]))`. `merkleRoot` returns `S(NETWORK + ':empty')` for no leaves. For nonempty input, hash each raw 32-byte input leaf with byte prefix `0x00`; hash pairs of raw children with byte prefix `0x01`, duplicating an odd final child at each layer. Finally return `S(J([NETWORK, 'merkle', originalLeafCount, treeRootHex]))`. Count commitment prevents odd-padding ambiguity; leaf/node prefixes separate domains. These commitment semantics, the RandomX version, and big-endian proof convention are pinned in the genesis consensus manifest.
|
||||
|
||||
The mempool holds at most **256** ordered transactions (transfers or trade bundles), validating sequentially against the next inclusion height; a template takes the first **64 transaction units**. A 202 response changes **no canonical ownership**. Mint at height `h` is eligible for inclusion at `h+2` (pool admission can happen at tip `h+1`). Confirmations are `tipHeight - mintedHeight + 1`, not a finality guarantee.
|
||||
|
||||
## Fork choice, reorgs and storage
|
||||
|
||||
Per-block work is `floor(2^256 / (target + 1))`; accumulate from genesis work zero. Keep all valid known-parent branches. Adopt a tip only for **strictly greater cumulative work**; equal-work ties retain the current tip, including across replay of persisted insertion order. A shorter, harder branch can win.
|
||||
|
||||
On reorg, reconstruct ownership from the winning branch. Orphan mints disappear from canonical ownership; disconnected transactions are reconsidered before existing pending entries, in order, only if still valid and not already committed. A trade is requeued as one unit only when every leg remains valid; otherwise the complete bundle is discarded. No checkpoints/finality or rollback protection beyond observed work; an isolated node has no peer-backed security.
|
||||
|
||||
The [ledger](../server/testnet/ledger.ts) is stored in `data/testnet/ledger.sqlite`, under the `WIKIDECK_DATA_DIR` testnet subdirectory (Docker uses `/app/data`). SQLite WAL mode with full synchronous commits stores each accepted block once in an indexed table and replaces the bounded mempool in the same transaction; writes no longer serialize/rewrite the entire DAG, and there is no 128 MiB/10,000-block ledger cap. A matching v6 legacy `ledger.json` is schema-checked and imported transactionally once; the source JSON is left untouched as a recovery copy. Earlier-protocol ledgers are not compatible and fail closed. Back up the complete stopped-node data directory, including SQLite database/WAL files. Do not copy only `ledger.sqlite` while the node is running.
|
||||
|
||||
The in-memory DAG keeps block records and cumulative work, while each block's NFT state is a persistent overlay containing only that block's changes rather than a full state copy. State-root calculation still visits the complete NFT state, and startup still revalidates every stored proof; CPU and startup work therefore grow with chain size. This is materially more storage-efficient, but not yet an archival-scale chain database or a public DoS defense. Blocks remain individually limited to **64 KiB and 64 transaction units**; the mempool remains capped at **256 transaction units**. Mutations are serialized (queue cap 256). HTTP startup exclusively creates a data-directory lock named `testnet-node.lock`. It is removed on normal shutdown, **not automatically after a crash**: stop and verify all owning processes have exited before manual stale-lock removal. Never bypass a live lock or share a writer directory. Back up node data and wallet exports separately; deleting a volume cannot be recovered from a wallet alone.
|
||||
|
||||
## Fixed peers and HTTP surface
|
||||
|
||||
Peers are **explicit operator-configured URL origins**, up to 16, not discovered from network input. Default: HTTPS/public addresses only, checked and pinned during DNS lookup; no credentials, paths, queries, fragments or redirects. `WIKIDECK_ALLOW_PRIVATE_PEERS=1` permits private/HTTP destinations only by explicit operator choice (used for local Docker tests). No bootnodes, DHT, automatic public deployment or claimed Sybil resistance.
|
||||
|
||||
Sync polls every **5 seconds**, checks network/chain ID, imports at most **32** topologically ordered DAG blocks per peer/pass, and validates remote pool entries locally. Accepted blocks and transactions (including complete trade bundles) are gossiped to configured peers; busy-peer gossip is dropped, with polling for catch-up. Responses are capped at 2 MiB with a 10-second deadline. Peer count is current outbound connectivity metadata, not consensus membership or a security score.
|
||||
|
||||
| Route | Purpose |
|
||||
| --- | --- |
|
||||
| `GET /healthz` | Process health/network, not sync or consensus security. |
|
||||
| `GET /api/state`, `/api/chain` | Canonical blocks, mined/pending transactions, tip/work and peer count. |
|
||||
| `GET /api/summary`, `/api/canonical?tip=<hash>&offset=0&limit=16` | Bounded state metadata and current-tip-pinned canonical pages. Full legacy snapshots are limited to 128 blocks and the response-byte budget. See [resource controls](node-resources.md). |
|
||||
| `GET /api/network` | Selected profile, pinned chain/genesis, and candidate launch status. |
|
||||
| `GET /api/nfts/:id`, `/api/peers` | Canonical NFT owner/sequence/confirmations, article and at-mint statistics; configured peer status. |
|
||||
| `GET /api/decks/:address?offset=0&limit=24` | Public canonical deck for a wallet address at one tip; paged, maximum 24 cards per response. This reveals public address holdings. |
|
||||
| `GET /api/wikipedia/:pageId` | Cached current enrichment for positive English Wikipedia page IDs: categories, views, size, languages and display-only scores. Never a consensus input. |
|
||||
| `POST /api/mining/template` | Rate-limited public miner identity; fetches a random article with a picture plus fresh at-mint statistics. Returns 503 when either cannot be fetched. |
|
||||
| `POST /api/blocks` | Independently validates a signed block, proof, article snapshot, required Wikimedia image URL, and statistics snapshot consistency. Repeated page IDs are accepted. |
|
||||
| `POST /api/transfer` | Signed single-card transfer admission; 202 means pending. |
|
||||
| `POST /api/trades` | Validates and admits one signed, atomic multi-card trade bundle; 202 means the whole bundle is pending. |
|
||||
| `GET /p2p/status`, `/p2p/blocks?offset=0`, `/p2p/mempool` | Manifest/size/tip, 32-block inventory pages, pending transactions. |
|
||||
| `POST /p2p/block`, `/p2p/transaction` | Same validation as local block/transaction submission; transaction endpoint accepts a transfer or atomic trade. |
|
||||
|
||||
POSTs require JSON, enforce supplied browser origins and signatures where applicable; peers without an Origin header are not authenticated by this check. HTTP parsing is capped at 68 KiB; API/P2P rate limits are 300/minute and block/transaction/trade submissions additionally 30/minute. There are no consensus fees, peer authentication, or economic spam deterrents. Same-origin browser RPC trusts the node; it does not independently verify these commitments. Deploy no valuable assets: majority-hashpower, eclipse, censorship, reorg and resource-exhaustion risks remain and are not externally audited under the operator's current policy.
|
||||
|
||||
Testnet storage and chain identities above remain unchanged. The [gated mainnet candidate](mainnet-launch.md) selects separate chain/signature domains, storage, lock and wallet identities; it is not a running or certified production network.
|
||||
@@ -0,0 +1,45 @@
|
||||
# Encrypted local wallet — stage 2
|
||||
|
||||
## What changes
|
||||
|
||||
The browser no longer creates or returns a plaintext wallet at startup. Open **Wallet backup & recovery** and choose:
|
||||
|
||||
- **Create encrypted wallet:** explicitly generate a new P-256 identity and choose a local password of 12–1024 characters.
|
||||
- **Encrypt existing wallet:** migrate the previous same-origin plaintext record, preserving its exact public key/address. This is required before the old key can sign in the new UI.
|
||||
- **Unlock wallet:** decrypt an existing local vault in this tab with its local password.
|
||||
- **Recover and save encrypted wallet:** decrypt a portable backup with its backup password and re-encrypt it under a new local password. Existing storage, even when locked, requires explicit replacement confirmation. Back up that identity first; replacement does not transfer its assets.
|
||||
|
||||
The local password and backup password may differ. They have no reset endpoint, are not sent to a server, and are not stored in local/session storage. Forgotten local passwords require a working portable backup and its password. Without either a usable local vault/password or backup/password, access is lost.
|
||||
|
||||
## Storage and migration guarantees
|
||||
|
||||
Vault records use the existing reviewed backup encryption primitive: PBKDF2-SHA256 (600,000 iterations), random 16-byte salt, AES-256-GCM with random 12-byte IV and authenticated format/network/public-key headers. The local wrapper stores a format/version and random revision plus the encrypted backup. It stores **no plaintext private CryptoKey or password** for newly created/migrated vaults. Public-key metadata remains visible; encryption does not hide wallet identity or on-chain holdings.
|
||||
|
||||
The existing testnet/mainnet IndexedDB names remain separate and unchanged to find legacy records safely. Migration reads the legacy key only after the user opts in, encrypts and decrypts to verify identity, then replaces the record in a committed IndexedDB readwrite transaction. No automatic deletion, new identity or network migration occurs. Storage failure leaves the original record intact. The old CryptoKey is never removed before encrypted replacement commits.
|
||||
|
||||
Cross-tab readwrite compare-and-swap checks the expected stored revision/record in the same transaction; optional Web Locks additionally serialize storage. A competing create/migration/restore must fail rather than overwrite a newly stored identity. This is application consistency, not protection against a malicious script deliberately editing IndexedDB. Old application versions/tabs must be closed before migration; cached old bundles are not guaranteed to understand a vault record.
|
||||
|
||||
Replacing a record does **not** securely erase previous browser storage pages, OS backups, disk snapshots, old downloaded files or keys previously copied by other scripts. If the old identity may have been exposed, encryption is not revocation: a separately planned transfer to a fresh identity is required. This work never transfers assets or silently rotates keys.
|
||||
|
||||
## Session and locking
|
||||
|
||||
UI components receive a public `Wallet` handle only; private keys remain inside the wallet module. All NFT transfer and trade signatures go through its session signer. A stale handle from before locking/re-unlocking is rejected even for the same address.
|
||||
|
||||
- Explicit **Lock wallet now** clears the module's session references immediately.
|
||||
- Five minutes without trusted pointer/keyboard input locks the session. RPC polling and automated signing do **not** reset idle time.
|
||||
- Four hours since unlocking locks it even if active.
|
||||
- Background/hidden-tab, pagehide and reload end the session. Hiding a tab during encryption/export/unlock may cancel its result; encrypted storage may already have committed, in which case it remains locked and can be unlocked again.
|
||||
- BroadcastChannel messages contain only a lock signal, never keys, passwords or decrypted backups. Manual/background locks and replacement invalidate other tabs where supported. If unavailable, storage revision is checked before returning signatures/backups; do not assume immediate cross-tab notification on every browser.
|
||||
- Lock epochs are checked across asynchronous crypto/storage steps. A signature finishing after a detected lock/replacement is discarded. Signing/export also recheck vault revision. An already returned/submitted signature cannot be revoked by locking; signed transactions/offers can remain valid on-chain.
|
||||
|
||||
Timers can be delayed by the browser or event-loop load. Expiry is checked again on signer/export/get-wallet access so delayed timer callbacks do not authorize an expired session. JS does not provide guaranteed zeroization of strings or CryptoKey/browser memory; clearing references is not a memory-forensics guarantee.
|
||||
|
||||
Form password values clear after operations, lock notifications, hiding the page and unmounting. Browser/password-manager behavior is outside this application's memory guarantees. Backups remain the existing portable format for native miner compatibility. A downloaded backup password does not implicitly change the local password.
|
||||
|
||||
## Validation and limitations
|
||||
|
||||
Node/WebCrypto storage-boundary tests cover encrypted record-only persistence, explicit no-wallet startup, signature verification, locked/stale handles, idle/absolute expiry, lock during unlock/export, wrong passwords, replacement consent, storage retry/quota failure, conflicting storage revisions, same-identity legacy migration and preservation after failed migration. Existing cryptographic tamper, wrong-network and native-miner backup tests remain.
|
||||
|
||||
Real browser smoke checks on a disposable loopback origin passed create → lock → unlock and reload → locked. IndexedDB inspection confirmed the vault wrapper/ciphertext and absence of a top-level private key/password without retrieving private material. Tests use ephemeral test credentials only. Final Node 24 TypeScript/Vite build passed; the complete suite passed **86 tests, 0 failed, 0 skipped**, including real RandomX HTTP integration and expanded wallet storage/lifecycle assertions.
|
||||
|
||||
**Wallet risks remain accepted but unresolved.** At-rest encryption reduces profile-theft exposure when locked but cannot protect an unlocked page or password entry from XSS, a malicious release, privileged extensions or a compromised browser/OS. The in-memory key intentionally remains extractable to support existing backup export. This is not hardware-isolated signing or a browser-extension wallet. External wallet audits are not planned; multi-browser/background/cross-tab races and destructive crash/restore drills remain internal engineering work. Do not use valuable assets merely because local encryption exists.
|
||||