diff --git a/README.md b/README.md index 5918793..93c572b 100644 --- a/README.md +++ b/README.md @@ -115,7 +115,7 @@ Light mode needs a 256 MiB cache plus scratchpad and process overhead. `--fast` - **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 decks** 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. -- **Marketplace** is the connected peer's market: fixed-price listings, timed auctions, USD prices and mock XMR checkout. Sales allocate a configurable fee to the hosting operator (default 2.5%) and a hardcoded 1% author fee (3.5% total by default). Buyers simulate payment, sellers sign real card delivery, and simulated seller-net/author-fee payouts happen after canonical delivery confirmations. **Never send real XMR: no payable checkout address or live processor is enabled.** Listings/orders are local to the selected market host, not gossiped; listing does not lock a card on-chain. See [peer markets, fees and payment status](docs/marketplace.md). +- **Marketplace** is the connected peer's market: new fixed-price listings and timed auctions use native XMR amounts; historical USD listings remain read-only. Checkout, fees and payouts are simulated. Sales allocate a configurable fee to the hosting operator (default 2.5%) and a hardcoded 1% author fee (3.5% total by default). Sellers still sign real card delivery after the mock payment step. **Never send real XMR: no payable checkout address or live processor is enabled.** Listings/orders are local to the selected market host, not gossiped; listing does not lock a card on-chain. See [peer markets, fees and payment status](docs/marketplace.md). - 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. diff --git a/compose.custody-pilot.yaml b/compose.custody-pilot.yaml new file mode 100755 index 0000000..d92568b --- /dev/null +++ b/compose.custody-pilot.yaml @@ -0,0 +1,119 @@ +# Private mock-only pilot profile. Start with a distinct Compose project name; +# this stack intentionally contains no Monero daemon, Wallet-RPC, or observer. +services: + provision: + image: wikideck:pilot-provision + build: + context: . + dockerfile: deploy/postgres/Dockerfile + volumes: + - pg-admin:/secrets/admin + - pg-owner:/secrets/owner + - pg-runtime:/secrets/runtime + - pg-backup:/secrets/backup + - pg-tls:/secrets/tls + network_mode: none + read_only: true + tmpfs: ["/tmp:mode=1777,size=16m"] + restart: "no" + database: + image: wikideck:postgres-pilot + build: + context: . + dockerfile: deploy/postgres/database.Dockerfile + depends_on: + provision: + condition: service_completed_successfully + environment: + POSTGRES_DB: wikideck_custody + POSTGRES_USER: postgres + POSTGRES_PASSWORD_FILE: /secrets/admin/password + POSTGRES_INITDB_ARGS: --auth-host=scram-sha-256 + command: [postgres, -c, ssl=on, -c, ssl_min_protocol_version=TLSv1.2, + -c, ssl_cert_file=/tls/server.crt, -c, ssl_key_file=/tls/server.key, + -c, hba_file=/etc/wikideck/pg_hba.conf, -c, log_statement=none, + -c, log_min_error_statement=panic, -c, log_parameter_max_length_on_error=0] + volumes: + - pg-data:/var/lib/postgresql/data + - pg-admin:/secrets/admin:ro + - pg-tls:/tls:ro + networks: [financial] + healthcheck: + test: [CMD-SHELL, "pg_isready -U postgres -d wikideck_custody"] + interval: 3s + timeout: 3s + retries: 30 + restart: unless-stopped + shm_size: 128m + stop_grace_period: 30s + migrate: + image: wikideck:private-pilot + build: + context: . + target: runtime + args: + WIKIDECK_NETWORK: pilot + depends_on: + database: + condition: service_healthy + environment: + WIKIDECK_NETWORK: pilot + WIKIDECK_LOCAL_PG_BOOTSTRAP: sandbox-only + command: [node, --experimental-strip-types, scripts/custody-deployment-init.ts] + volumes: + - pg-admin:/secrets/admin:ro + - pg-owner:/secrets/owner:ro + - pg-runtime:/secrets/runtime:ro + - pg-backup:/secrets/backup:ro + networks: [financial] + read_only: true + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + restart: "no" + wikideck: + image: wikideck:private-pilot + build: + context: . + target: runtime + args: + WIKIDECK_NETWORK: pilot + depends_on: + migrate: + condition: service_completed_successfully + ports: ["127.0.0.1:${WIKIDECK_PILOT_PORT:-3423}:3001"] + environment: + WIKIDECK_NETWORK: pilot + WIKIDECK_PILOT_MODE: private-mock-only + WIKIDECK_PAYMENT_MODE: mock + WIKIDECK_MARKET_ENABLED: "${WIKIDECK_MARKET_ENABLED:-1}" + WIKIDECK_MARKET_TRADING_ENABLED: "${WIKIDECK_MARKET_TRADING_ENABLED:-1}" + WIKIDECK_MARKET_HOST_FEE_ADDRESS: "${WIKIDECK_MARKET_HOST_FEE_ADDRESS:-44xHcCdFhW4b951yBHpkTPdLSJ85qTCnFQ8N7m96TtqqRL3dbhzbEH4fe2SJ3a6ESHcNyzCYH5nYJ9ActR1JtkeA7QYGbQv}" + WIKIDECK_CUSTODY_MODE: sandbox + WIKIDECK_CUSTODY_STORAGE: postgres + WIKIDECK_CUSTODY_PG_URL_FILE: /secrets/runtime/url + WIKIDECK_CUSTODY_PG_CA_FILE: /secrets/runtime/ca.crt + PUBLIC_ORIGIN: "http://127.0.0.1:${WIKIDECK_PILOT_PORT:-3423}" + volumes: + - custody-node:/app/data + - pg-runtime:/secrets/runtime:ro + networks: [financial, web] + init: true + restart: unless-stopped + read_only: true + tmpfs: ["/tmp:mode=1777,size=32m,noexec,nosuid"] + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + pids_limit: 128 + mem_limit: 1g + stop_grace_period: 30s +networks: + financial: {internal: true} + web: {} +volumes: + pg-data: + pg-admin: + pg-owner: + pg-runtime: + pg-backup: + pg-tls: + custody-node: diff --git a/docs/real-xmr-pilot-deployment.md b/docs/real-xmr-pilot-deployment.md new file mode 100755 index 0000000..eed693b --- /dev/null +++ b/docs/real-xmr-pilot-deployment.md @@ -0,0 +1,23 @@ +# Private pilot deployment: mock-only foundation + +Status: **application and isolated PostgreSQL sandbox only**. This is not a real-XMR stack, a public node, or an approval to accept deposits. The first deployment increment intentionally has no Monero daemon, Wallet-RPC gateway, observer, deposit enrollment, or withdrawal execution. + +## Start the isolated profile + +Use [compose.custody-pilot.yaml](../compose.custody-pilot.yaml) with the stable project name `wikideck-xmr-pilot`. Do not combine it with [the existing local custody sandbox](../compose.custody.yaml), the disposable PostgreSQL fixture, or another pilot project name. Project-scoped volumes hold the pilot's PostgreSQL database, credentials, and node state separately. + +Build/start with `docker compose -p wikideck-xmr-pilot -f compose.custody-pilot.yaml up -d --build`. Open `http://127.0.0.1:3423/` and confirm the page identifies **PRIVATE PILOT**. The service binds to loopback by default; set `WIKIDECK_PILOT_PORT` only when changing the local port. + +The app and browser bundle both select the `pilot` identity. Startup requires `WIKIDECK_PILOT_MODE=private-mock-only`; payments are fixed to `mock`. The market sandbox and PostgreSQL schema are freshly bound to this distinct chain ID. Do not point this stack at existing testnet/mainnet node or custody volumes. + +To stop while preserving pilot data, run `docker compose -p wikideck-xmr-pilot -f compose.custody-pilot.yaml down` without volume removal. Do not use `--volumes` unless the database, credentials, and node history are intentionally being destroyed. + +## What this enables—and does not + +The independent private chain uses a fixed pilot genesis time and its own deterministic chain/genesis identity. The app can run with the current sandbox features and mock balances while test cards and UI flows are exercised. Testnet and mainnet candidate identities and launch gates remain unchanged. + +This stack does **not** create real Monero deposit addresses, scan a wallet, approve real credits, construct or relay withdrawals, or settle NFT sales against active consensus. Deposit enrollment and withdrawal request flags remain rejected outside the mainnet profile, and mainnet remains separately gated. Do not expose the service publicly or solicit funds. Wallet integration requires the later observer/gateway and schema/role work, then actual withdrawal execution and activated sale settlement described in [the implementation plan](real-xmr-pilot-plan.md). + +## Initial checks + +The network manifest reports `profile: pilot`, `network: wikideck-randomx-pilot-1`, and `launchStatus: private-pilot-mock-only`. Verify startup refuses a missing pilot-mode opt-in and any non-mock payment setting. Deployment tests check loopback binding, distinct profile selection, database secret isolation, and absence of Monero services. A successful mock deployment is only evidence for this first slice, not for real-XMR readiness. diff --git a/docs/real-xmr-pilot-plan.md b/docs/real-xmr-pilot-plan.md new file mode 100755 index 0000000..2402381 --- /dev/null +++ b/docs/real-xmr-pilot-plan.md @@ -0,0 +1,119 @@ +# Get the real-XMR market running + +Updated: 2026-10-22. Implementation plan for a private, operator-supervised functional pilot—not a public production release. Wallet access and fund movement require separate explicit approval. + +## Progress checkpoint — 2026-10-22 + +- **Step 1 started; mock-only foundation implemented.** Added a distinct `pilot` profile with its own network/genesis identity, explicit private-mock-only startup opt-in, separate local ledger/market/custody paths and browser wallet database, and a loopback-bound PostgreSQL sandbox stack. Setup and limits are in [the pilot deployment guide](real-xmr-pilot-deployment.md). Testnet v6 and mainnet candidate identities/gates were left intact. +- **Step 1 is not complete.** This first stack has no Monero daemon, Wallet-RPC gateway, observer, real-fund deposit or withdrawal path. It is useful for isolated UI/mock-flow work only and must not receive funds. +- **Validation:** pilot-specific network/startup/storage/Compose tests pass (10/10); pilot runtime Docker image builds. The attempted serial full offline suite had one native RandomX HTTP peer-gossip convergence failure in `tests/api.test.ts`; the other reported tests passed. Treat full-suite status as not yet clean and rerun after the next increment. +- **Steps 2–5:** not started. Existing deposit/withdrawal APIs still require the separately gated mainnet profile; sale-lock transactions remain candidate-only and are not accepted by active consensus. + +## Finish line + +Two browser wallets complete this flow on one deployed stack: + +**Buyer deposits XMR → available balance → fixed-price purchase → card ownership changes → seller receives proceeds → seller withdraws XMR.** + +Use the existing pooled-custody architecture, PostgreSQL accounting, native Monero integration and UI. Do not restart architecture research, introduce another payment provider or build a general-purpose payment platform. + +## Reuse what exists + +- Exact atomic-XMR prices and fee calculations. +- PostgreSQL schema v9 and accounting/reorg records. +- Signed deposit enrollment, observation worker and reviewed credit/release commands. +- Signed balance reads and withdrawal reservation/cancellation APIs. +- Marketplace/custody UI and executable sale-lock/accounting models. + +The missing work is integration plus two substantial features: **actual withdrawal execution and activated NFT sale settlement**. Current market commands remain sandbox-only; reserved withdrawals never send XMR; active consensus rejects sale-lock transactions. + +## Smallest useful scope + +One Linux host, one authoritative market writer, one treasury tool/worker, fixed-price sales and operator-controlled accounts initially. Manual signed deposit approvals and operator-triggered sends are sufficient. Reuse existing UI components; no admin dashboard, unattended treasury or auction system is needed. + +## Implementation sequence + +### 1. Make one pilot stack runnable + +- Add an explicitly identified private pilot profile for the sale protocol, distinct from existing v6 and the final mainnet candidate. +- Bind signed market/payment requests to the pilot chain and custodian; select the Monero network explicitly. Real XMR requires Monero mainnet, not a public Wikideck launch. +- Give the pilot its own explicit genesis/startup configuration rather than inheriting the candidate's January 1, 2027 delay and public-peer requirements. Leave existing mainnet protections unchanged; do not fake review acknowledgements or alter v6 in place. +- Add one pilot deployment definition using existing Docker patterns: app, PostgreSQL, observer and private Wallet-RPC gateway, with explicit connections to the daemon/watch-only wallet and separate spending wallet. +- Include schema initialization, role grants and required configuration in a short setup procedure. Keep spending keys outside the web app and Wallet RPC off the public Internet. + +**Progress:** A separate mock-only pilot network/profile, launch opt-in, profile-isolated local storage, PostgreSQL Compose deployment and setup guide now exist. This establishes the private application base only; the planned Monero daemon/observer/gateway and any real-fund integrations remain outstanding. See [pilot deployment status and startup](real-xmr-pilot-deployment.md). + +**Result:** start the stack, open the UI, create two wallets and obtain a test card. Start preparing/syncing the Monero daemon and wallet while application development proceeds. + +### 2. Connect deposits to spendable balances + +- Add a deposit panel that signs the existing enrollment request and displays the allocated address. +- Run the observer against the configured wallet; show pending and available balances. +- Support the pilot identity in the existing prepare/stage/release workflow. Keep approvals operator-driven rather than adding automation. +- Report capabilities truthfully as the flow becomes available; keep mock-credit controls unreachable in real-fund mode. + +**Result:** a real Stagenet deposit is observed and approved into the buyer's available balance through the running application. This is private development progress, not a reason to solicit real deposits before cash-out works. + +### 3. Finish withdrawals with an operator tool + +- Extend signed reservations with durable preparation, prepared-transaction, relay and confirmation states, including an uncertain/review outcome. +- Claim a request exclusively and block cancellation once preparation begins. +- Construct/sign using the separate treasury wallet, enforcing destination, amount and maximum fee. +- Record preparation intent before wallet side effects and retain the recoverable signed transaction identity/blob before relay. Reconcile ambiguous preparation before trying again. +- Relay and track the stored transaction. Retries reuse that transaction rather than creating another payment. +- Settle the reserved liability with the actual fee and return unused fee allowance; keep uncertain sends reserved. +- Add browser withdrawal inputs, status and receipt. A CLI command can process the queue; no automatic payout scheduler is needed. + +**Result:** deposit → signed withdrawal → operator send → XMR received, with correct balances and fees. + +### 4. Connect purchases to NFT delivery and seller earnings + +Start this alongside steps 2–3 after defining the pilot identity. Do not wait for a separate release-hardening phase. + +- Integrate the existing lock/completion/cancellation/expiry model into pilot transaction validation, state commitments, mempool, canonical indexes/events, peer processing and restart replay. Use the existing RandomX ledger, not a toy substitute. +- Adapt custody listing/purchase commands for real balances and fresh signatures. Atomically reserve buyer funds with the order; exclude mock funding/payment authorizations. +- Collect seller/buyer lock consent, submit the lock and have the host attest completion only against the funded reservation. +- Feed actual canonical outcomes into PostgreSQL settlement instead of synthetic rehearsal witnesses. +- Credit seller, author and host once after configured confirmation depth; release buyer funds only after safe cancellation/expiry/non-admission evidence. Hold conflicting reorg outcomes rather than paying/refunding again. +- Allow withdrawal of legitimate sale and fee earnings. The current own-deposit backing limit prevents a seller who never deposited from cashing out. Replace it with pooled-backing accounting covering liabilities, pending sends and fees—not merely removal of the check. +- Apply existing accounting checks and incident holds to the connected sale and treasury writers. +- Adapt the existing marketplace UI to show funded checkout, lock/completion progress, delivered ownership and proceeds. + +**Result:** seller lists → buyer buys → card changes owner → exact seller/fee balances appear → seller withdraws, even without a prior seller deposit. + +### 5. Exercise the complete deployed flow, then test real XMR + +1. Run deposit → purchase → seller withdrawal on Stagenet using the actual browsers and deployment. +2. Include focused implementation checks for duplicate requests, restart after preparation/relay, cancellation versus send and canonical sale disconnect. These protect the flow from duplicate money/asset movement; they are not a separate certification program. +3. With explicit wallet/network/amount approval, configure Monero mainnet and repeat with operator-controlled accounts and a small amount sufficient for fees. + +**Result:** a functional private real-XMR market with repeatable startup and operator commands. Public launch is outside this increment. + +## Parallel work + +| Workstream | Start | Delivers | +| --- | --- | --- | +| Pilot identity + deployment | First | Running stack and unblocked integration | +| Deposit UI + reviewed credit | After identity/setup | Funded buyer balance | +| Treasury tool + withdrawal UI | Alongside deposits | Actual cash-out | +| Sale-lock activation + custody settlement | After identity is defined, alongside payment work | Paid NFT delivery and seller earnings | +| Browser end-to-end flow | As slices connect | Deployable functional pilot | + +Build each slice with its actual callers. Do not spend another increment adding a disconnected model or endpoint. + +## Move out of the functional critical path + +Track these separately as public-release/hardening follow-ups, rather than front-loading them as engineering phases: + +- Broad audit/certification and release evidence packets. +- Production-scale benchmarks, SLOs, HA, multi-host operations and additional orchestrators. +- SBOM/provenance automation, comprehensive scanning programs and artifact signing. +- Automated certificate rotation, backup scheduling, off-site recovery certification and full on-call systems. +- Automatic credit approval, unattended signing, batching and admin dashboards. +- Auctions, fiat conversion, alternate processors and final public-mainnet launch preparation. + +Keep the functional essentials: signed authorization, correct network binding, private wallet access, exact balanced accounting, one-time settlement and recoverable sends. Deferring broader hardening does not make this production-ready; public/customer-fund rollout still needs the separate policy/legal/security decisions in [the production plan](production-plan.md). + +## Next coding task + +**Finish step 1's operational checks, then design the pilot's separate Wikideck-chain/Monero-mainnet financial identity and schema/role contract before connecting deposits.** Existing observer/deposit contracts are mainnet-specific, so do not simply enable their flags on the pilot. Keep the next deployment mock-only until network binding, reviewed credit, actual withdrawal execution, recovery, and sale settlement are connected. Continue with the operator treasury tool and active sale-lock settlement as parallel implementation tracks where the identity contract permits. Completion means a buyer purchasing a card and the seller receiving withdrawable XMR—not another scaffold or release checklist. diff --git a/server/launch.ts b/server/launch.ts index eefe678..51a1a7e 100755 --- a/server/launch.ts +++ b/server/launch.ts @@ -1,13 +1,22 @@ -import { IS_MAINNET, NETWORK, PROFILE } from '../shared/network.ts'; +import { IS_MAINNET, IS_PILOT, NETWORK, PROFILE } from '../shared/network.ts'; import { CHAIN_ID, GENESIS_HASH, GENESIS_TIME } from './testnet/consensus.ts'; export function launchManifest() { return { profile: PROFILE, network: NETWORK, chainId: CHAIN_ID, genesis: GENESIS_HASH, - genesisTime: GENESIS_TIME, launchStatus: IS_MAINNET ? 'candidate-gated' : 'testnet', + genesisTime: GENESIS_TIME, launchStatus: IS_MAINNET ? 'candidate-gated' : IS_PILOT ? 'private-pilot-mock-only' : 'testnet', paymentMode: 'mock', audited: false }; } /** Operator attestation is an accident-prevention gate, NOT proof of a security audit. */ export function assertLaunchAllowed(env: NodeJS.ProcessEnv = process.env, now = Date.now()) { + if (IS_PILOT) { + if (env.WIKIDECK_PILOT_MODE !== 'private-mock-only') { + throw new Error('Private pilot requires WIKIDECK_PILOT_MODE=private-mock-only'); + } + if ((env.WIKIDECK_PAYMENT_MODE ?? 'mock') !== 'mock') { + throw new Error('Private pilot supports mock payments only; live XMR remains disabled'); + } + return; + } if (!IS_MAINNET) return; if (env.WIKIDECK_MAINNET_LAUNCH !== CHAIN_ID || env.WIKIDECK_MAINNET_REVIEW_ACK !== 'independent-review-complete') { throw new Error(`Mainnet candidate is launch-gated. Review the launch checklist; explicit chain approval required: ${CHAIN_ID}`); diff --git a/server/market/custody-storage.ts b/server/market/custody-storage.ts index 002d87c..afe4ee6 100755 --- a/server/market/custody-storage.ts +++ b/server/market/custody-storage.ts @@ -4,10 +4,12 @@ import { join } from 'node:path'; import { CustodyMarket } from './custody.ts'; import { PostgresCustody, type CustodyOptions } from './postgres-custody.ts'; import { custodyStorage, postgresConfig } from './postgres-config.ts'; +import { PROFILE } from '../../shared/network.ts'; /** No automatic SQLite reinterpretation or fallback after a database connection/configuration failure. */ export async function openCustodyStorage(directory: string, options: CustodyOptions, env = process.env): Promise { - const storage = custodyStorage(env), marker = join(directory, 'testnet', 'custody-postgres.json'); + const profileDirectory = join(directory, PROFILE); + const storage = custodyStorage(env), marker = join(profileDirectory, 'custody-postgres.json'); const observerMode = env.WIKIDECK_CUSTODY_CANONICAL_REHEARSAL; if (observerMode !== undefined && observerMode !== '0' && observerMode !== '1') { throw new Error('WIKIDECK_CUSTODY_CANONICAL_REHEARSAL must be exactly 0 or 1'); @@ -16,7 +18,7 @@ export async function openCustodyStorage(directory: string, options: CustodyOpti throw new Error('Canonical observer rehearsal requires PostgreSQL and the disposable database test guard'); } const custodyOptions = observerMode === '1' ? { ...options, disposableSaleRehearsal: true } : options; - await mkdir(join(directory, 'testnet'), { recursive: true, mode: 0o700 }); + await mkdir(profileDirectory, { recursive: true, mode: 0o700 }); let existing: { version: number; custodianId: string } | undefined; try { existing = JSON.parse(await readFile(marker, 'utf8')); } catch (e) { if ((e as NodeJS.ErrnoException).code !== 'ENOENT') throw e; } @@ -24,7 +26,7 @@ export async function openCustodyStorage(directory: string, options: CustodyOpti if (existing) throw new Error('Custody data directory is bound to PostgreSQL; SQLite fallback prohibited'); return CustodyMarket.open(directory, custodyOptions); } - const source = join(directory, 'testnet', 'custody-sandbox.sqlite'); + const source = join(profileDirectory, 'custody-sandbox.sqlite'); let frozen: string | undefined; try { const info = await lstat(source); @@ -44,7 +46,7 @@ export async function openCustodyStorage(directory: string, options: CustodyOpti try { await handle.writeFile(JSON.stringify({ version: 1, custodianId: market.id })); await handle.sync(); } finally { await handle.close(); } if (process.platform !== 'win32') { - const parent = await open(join(directory, 'testnet'), 'r'); + const parent = await open(profileDirectory, 'r'); try { await parent.sync(); } finally { await parent.close(); } } } diff --git a/server/market/custody.ts b/server/market/custody.ts index 452ac3a..0917cd8 100755 --- a/server/market/custody.ts +++ b/server/market/custody.ts @@ -2,7 +2,7 @@ import { DatabaseSync } from 'node:sqlite'; import { createHash, randomUUID } from 'node:crypto'; import { mkdir, chmod } from 'node:fs/promises'; import { join } from 'node:path'; -import { IS_MAINNET } from '../../shared/network.ts'; +import { IS_MAINNET, PROFILE } from '../../shared/network.ts'; import { NETWORK } from '../../shared/testnet.ts'; import { ADDITIONAL_MARKET_FEE } from '../../shared/market.ts'; import { allocateXmrSale } from '../../shared/xmr-pricing.ts'; @@ -50,7 +50,7 @@ export class CustodyMarket { if (IS_MAINNET) throw new Error('Custody sandbox cannot run on mainnet'); await validateMarketPolicy(options); if (!Number.isSafeInteger(options.feeBps) || options.feeBps < 0 || options.feeBps > 5000) throw new Error('Invalid custody fee'); - const folder = join(directory, 'testnet'); + const folder = join(directory, PROFILE); await mkdir(folder, { recursive: true, mode: 0o700 }); const file = join(folder, 'custody-sandbox.sqlite'); const db = new DatabaseSync(file); diff --git a/server/market/store.ts b/server/market/store.ts index 90f7260..e1ff901 100755 --- a/server/market/store.ts +++ b/server/market/store.ts @@ -16,6 +16,7 @@ import { RpcError } from '../resources.ts'; import type { CanonicalEvents, IndexedNft } from '../testnet/canonical-index.ts'; import { z } from 'zod'; import { operatorMarketPolicy, resolvedMarketPolicy, permitsMarketAction, validateMarketPolicy, type MarketPolicy } from './policy.ts'; +import { PROFILE } from '../../shared/network.ts'; type Chain = { snapshot(): TestnetSnapshot; summary?(): { tip: string; revision: number; height?: number }; submitTransfer(raw: unknown): Promise; nft?(token: string): IndexedNft | undefined; @@ -112,7 +113,7 @@ export class Market { static async open(directory: string, chain: Chain, config = marketConfig(), now = Date.now, reconciliation: { worker?: boolean } = {}): Promise { await validateMarketPolicy(config); - const folder = join(directory, NETWORK.includes('mainnet') ? 'mainnet' : 'testnet'); + const folder = join(directory, PROFILE); await mkdir(folder, { recursive: true, mode: 0o700 }); const file = join(folder, 'market.sqlite'); const db = new DatabaseSync(file); diff --git a/server/preflight.ts b/server/preflight.ts index 367b7b8..3e17a82 100755 --- a/server/preflight.ts +++ b/server/preflight.ts @@ -1,4 +1,4 @@ -import { IS_MAINNET } from '../shared/network.ts'; +import { IS_MAINNET, IS_PILOT } from '../shared/network.ts'; import { ADDITIONAL_MARKET_FEE } from '../shared/market.ts'; import { assertLaunchAllowed, launchManifest } from './launch.ts'; import { marketConfig } from './market/store.ts'; @@ -7,15 +7,17 @@ export type LaunchCheck = { id: string; status: 'pass' | 'blocked' | 'unverified /** Read-only local assessment. Never opens a ledger, starts PoW, contacts peers, or sets approvals. * Configured approvals cannot resolve findings that require new code or independent evidence. */ export function launchPreflight(env: NodeJS.ProcessEnv = process.env, now = Date.now()) { - const checks: LaunchCheck[] = [{ id: 'network-selection', status: IS_MAINNET ? 'pass' : 'blocked', - detail: IS_MAINNET ? 'Separate mainnet candidate selected.' : 'Testnet selected; this is not a production profile.' }]; + const checks: LaunchCheck[] = [{ id: 'network-selection', status: IS_MAINNET || IS_PILOT ? 'pass' : 'blocked', + detail: IS_MAINNET ? 'Separate mainnet candidate selected.' : IS_PILOT + ? 'Private pilot chain selected; this is not a public or production profile.' + : 'Testnet selected; this is not a production profile.' }]; try { marketConfig(env); checks.push({ id: 'mock-payment-boundary', status: 'pass', detail: 'Only mock payments are supported; market configuration is valid.' }); } catch { checks.push({ id: 'mock-payment-boundary', status: 'blocked', detail: 'Invalid market configuration or unsupported live payment mode. No secret values are included in this report.' }); } - if (IS_MAINNET) { + if (IS_MAINNET || IS_PILOT) { try { assertLaunchAllowed(env, now); checks.push({ id: 'operator-startup-gates', status: 'pass', detail: 'Local startup gates satisfied; this does not establish production readiness or peer independence.' }); diff --git a/server/testnet/http.ts b/server/testnet/http.ts index 2bca445..3ee425f 100644 --- a/server/testnet/http.ts +++ b/server/testnet/http.ts @@ -33,7 +33,7 @@ import { createMoneroDepositAddressRpc, loadMoneroObserverConfig } from '../mark import { loadMoneroMtlsTransport, loadMoneroMtlsTransportConfig } from '../market/monero-mtls-transport.ts'; import { postgresConfig } from '../market/postgres-config.ts'; import { validateMarketPolicy } from '../market/policy.ts'; -import { IS_MAINNET, PROFILE } from '../../shared/network.ts'; +import { IS_MAINNET, IS_PILOT, PROFILE } from '../../shared/network.ts'; import { assertLaunchAllowed, launchManifest } from '../launch.ts'; import { resourceConfig, RpcBudget, RpcError } from '../resources.ts'; import { trustedProxies, operationsPort, startOperations } from '../operations.ts'; @@ -353,7 +353,7 @@ app.use((err:Error & {status?:number},_req:express.Request,res:express.Response, }); const port=Number(process.env.PORT??3001),host=process.env.HOST??'127.0.0.1'; const server=app.listen(port,host,()=>{ - const a=server.address();console.log(`Wikideck RandomX ${IS_MAINNET?'mainnet candidate':'testnet'}: http://${host}:${typeof a==='object'&&a?a.port:port} · chain ${CHAIN_ID} · ${ledger.snapshot().blocks.length} blocks`); + const a=server.address();console.log(`Wikideck RandomX ${IS_MAINNET?'mainnet candidate':IS_PILOT?'private pilot':'testnet'}: http://${host}:${typeof a==='object'&&a?a.port:port} · chain ${CHAIN_ID} · ${ledger.snapshot().blocks.length} blocks`); peers.start(); }); const operations=startOperations(opsPort,()=>({network:NETWORK,paymentMode:'mock', diff --git a/shared/network.ts b/shared/network.ts index ca76c0d..8cee714 100755 --- a/shared/network.ts +++ b/shared/network.ts @@ -1,13 +1,18 @@ /** Selection is fixed at server startup / browser build, never learned from an untrusted RPC. */ -export function networkProfile(value: string | undefined): 'testnet' | 'mainnet' { +export type NetworkProfile = 'testnet' | 'mainnet' | 'pilot'; +export function networkProfile(value: string | undefined): NetworkProfile { const profile = value ?? 'testnet'; - if (profile !== 'testnet' && profile !== 'mainnet') throw new Error('WIKIDECK_NETWORK must be testnet or mainnet'); + if (profile !== 'testnet' && profile !== 'mainnet' && profile !== 'pilot') { + throw new Error('WIKIDECK_NETWORK must be testnet, mainnet, or pilot'); + } return profile; } export const PROFILE = networkProfile(typeof process !== 'undefined' && process.versions?.node ? process.env.WIKIDECK_NETWORK : import.meta.env?.VITE_WIKIDECK_NETWORK); export const IS_MAINNET = PROFILE === 'mainnet'; -export const NETWORK = IS_MAINNET ? 'wikideck-randomx-mainnet-1' as const : 'wikideck-randomx-testnet-6' as const; +export const IS_PILOT = PROFILE === 'pilot'; +export const NETWORK = IS_MAINNET ? 'wikideck-randomx-mainnet-1' as const + : IS_PILOT ? 'wikideck-randomx-pilot-1' as const : 'wikideck-randomx-testnet-6' as const; // Candidate mainnet genesis: 2027-01-01 00:00 UTC. NOT a commitment to a launch date. -export const NETWORK_GENESIS_TIME = IS_MAINNET ? 1_798_761_600 : 1_792_411_200; -export const NETWORK_LABEL = IS_MAINNET ? 'MAINNET CANDIDATE' : 'TESTNET'; +export const NETWORK_GENESIS_TIME = IS_MAINNET ? 1_798_761_600 : IS_PILOT ? 1_792_627_200 : 1_792_411_200; +export const NETWORK_LABEL = IS_MAINNET ? 'MAINNET CANDIDATE' : IS_PILOT ? 'PRIVATE PILOT' : 'TESTNET'; diff --git a/src/App.tsx b/src/App.tsx index 6673125..4b9a3d2 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -12,7 +12,7 @@ import { useModalFocus } from './useModalFocus.ts'; import { ThemePicker } from './ThemePicker.tsx'; import { TradeDesk } from './TradeDesk.tsx'; import { Marketplace } from './Marketplace.tsx'; -import { IS_MAINNET, NETWORK_LABEL } from '../shared/network.ts'; +import { IS_MAINNET, IS_PILOT, NETWORK_LABEL } from '../shared/network.ts'; import { StateClient } from '../shared/rpc-client.ts'; import './App.css'; import './testnet.css'; @@ -166,18 +166,18 @@ export default function App() { const Icon = [LayoutDashboard, Layers3, Globe2, ArrowLeftRight, ShoppingBag][i]; return ; })} -
✦

Your cards.
Your community.

Mine Wikipedia NFT cards, build collections, and trade in peer-hosted markets.

+
✦

Mine together.
Trade your way.

Discover illustrated Wikipedia cards, build a deck around what you love, and find your collector community.

{peerLabel}{NETWORK_LABEL}
Explore {view}
RandomX {NETWORK_LABEL}{peerLabel}
-
RPC {rpcAvailable ? 'available' : 'unavailable'}{peerLabel}{IS_MAINNET?'Gated mainnet candidate · unaudited · mock payments only':'Unbootstrapped testnet · no public mainnet'}{snapshot && !rpcAvailable && Showing last known state}
+
RPC {rpcAvailable ? 'available' : 'unavailable'}{peerLabel}{IS_MAINNET?'Gated mainnet candidate · unaudited · mock payments only':IS_PILOT?'Private pilot · mock custody only · no real XMR':'Unbootstrapped testnet · no public mainnet'}{snapshot && !rpcAvailable && Showing last known state}
{error &&
{error}
} {view === 'Discover' && <>
-
WIKIPEDIA CARDS. THEIR OWN NFT BLOCKCHAIN.

Mine knowledge.
Collect the extraordinary.

Mine a block. Earn a Wikipedia NFT card. Build collections, trade discoveries, and find your community in peer-hosted markets. Trading card games are next on the roadmap.

Consumer-CPU mining Peer-hosted markets
+
MINE · BUILD A DECK · TRADE WITH YOUR PEOPLE

Mine with your CPU.
Build a deck from the world.

Turn random illustrated Wikipedia discoveries into collectible cards. Use the same RandomX algorithm as Monero, grow a collection around what you love, then trade with other collectors. Community markets are here; card games are on the way.

CPU-friendly RandomX Collector-run markets
✳+
Preview cards · not owned
setSelected(samples[2])} />
setSelected(samples[0])} />
A world worth collecting
@@ -187,13 +187,13 @@ export default function App() {
Proof of work{snapshot?.algorithm ?? 'RandomX'}native CPU mining
-
RANDOMX · BUILT FOR GENERAL-PURPOSE CPUS

Mine blocks. Earn cards.

Wikideck uses RandomX, the proof-of-work algorithm also used by Monero, to keep mining competitive on consumer-grade CPUs. Each accepted block rewards its miner with an illustrated Wikipedia NFT card. Results depend on your hardware and network difficulty; Wikideck does not share Monero’s network security.

Consumer hardware Independent validating peers
Light · default256 MiB cache + scratchpad and overhead.Fast · --fast~2 GiB dataset plus cache; budget over 2.3 GiB per process. Mining consumes CPU, memory and energy; RandomX is not a guarantee of ASIC resistance or profitability.
-
NEXT WIKIPEDIA ARTICLE{snapshot ? 'Chosen when the miner requests work' : 'Waiting for testnet RPC…'}

Each mining template requests a random English Wikipedia article with a Wikimedia picture. Pages may repeat; every minted card carries its own statistics snapshot.

  1. Build wikideck-randomx using the repository’s native build instructions.
  2. Save your encrypted backup and keep its password separate.
  3. Replace <backup.json> with your local file path (quote paths with spaces), then run:
{nativeCommand}

Node: {window.location.origin}. Same-origin RPC, including the development proxy. Use HTTPS for remote nodes. Password entry stays local; never put it in the command. Defaults to one worker and at most one block. Ctrl+C stops the native miner; closing this page does not.

+
RANDOMX · DESIGNED FOR GENERAL-PURPOSE CPUS

Mining should be for more people.

Wikideck and Monero use RandomX, an algorithm designed to resist specialized ASICs and keep general-purpose CPUs competitive. That can make mining more accessible—not make every machine equally powerful or promise rewards. Each accepted Wikideck block earns its miner a distinct illustrated Wikipedia card. Wikideck is its own independent network.

Mine with a CPU Independently validating peers
Hardware, rewards & network details
Light · default256 MiB cache plus scratchpad and process overhead.Fast · --fastAbout 2 GiB dataset plus cache; budget over 2.3 GiB per process. Mining uses CPU, memory, electricity and time. ASIC resistance is a design goal, not a guarantee; results depend on hardware and network difficulty. Wikideck does not share Monero’s network, hashpower or security.
+
NEXT WIKIPEDIA ARTICLE{snapshot ? 'Chosen when the miner requests work' : 'Waiting for testnet RPC…'}

The miner selects a random illustrated English Wikipedia article. The same article can appear again; each card keeps its own mint-time statistics.

Want to run a miner? Setup & safety details
  1. Build wikideck-randomx using the repository’s native build instructions.
  2. Save your encrypted backup and keep its password separate.
  3. Replace <backup.json> with your local file path (quote paths with spaces), then run:
{nativeCommand}

Node: {window.location.origin}. The command connects to this node; use HTTPS for remote nodes. Password entry stays local—never put it in the command. It defaults to one worker and at most one block. Ctrl+C stops the native miner; closing this page does not.

-
COLLECT & TRADE

A collection with a story.

Collect Wikipedia pages as cards, swap multiple cards in one trade, or list discoveries at a fixed price or timed auction.

-
HOST YOUR OWN MARKET

Your peer. Your community.

Run a peer and host a market for everyone or a community centered on a collection. Sales allocate a hosting fee to the operator and a hardcoded 1% to the project author. Cryptocurrency checkout is designed for XMR; today payments and fees are simulated.

-
ON THE ROADMAP · NOT PLAYABLE YET

Cards made for more.

Trading card games and peer-hosted custom TCGs are planned. The open-source direction is to let communities adapt markets and games; a software license still needs to be published. Built-in collection curation and custom game hosting are not available yet.

+
COLLECT · DECK-BUILD · TRADE

Make every deck your own.

Chase a theme, collect the unexpected, or put together a multi-card swap. List a favorite for a fixed price or let collectors bid in an auction.

+
A MARKET FOR YOUR COMMUNITY

Collectors set the scene.

Each peer can run its own market, with listings local to that host. New listings use XMR prices, but checkout is simulated: no real XMR is accepted or sent. Host and author fees are shown before you sign.

+
NEXT UP · GAMEPLAY IS IN DEVELOPMENT

Your cards, ready to play.

Trading-card games and community-made rules are the bigger idea: build decks with a point of view, then play your way. The game engine and custom game hosting are planned, not playable today.

} {view === 'Marketplace' ? : view === 'Trade decks' ? : view !== 'Block explorer' ?
@@ -217,14 +217,14 @@ export default function App() { {toast &&
{toast}
} {(dialog || selected) &&
{ if (e.target === e.currentTarget) close(); }}>
{dialog === 'guide' ? <> -
THE WIKIDECK FIELD GUIDE

Mine. Collect. Make it yours.

+
THE WIKIDECK FIELD GUIDE

Mine. Build a deck. Find your people.

-
01

Mine a block. Earn a Wikipedia card.

Wikideck is an NFT blockchain: each accepted block rewards its miner with a card based on a random illustrated Wikipedia page and its mint-time statistics. RandomX, also used by Monero, is designed for competitive mining on consumer CPUs. Wikideck is its own network, not part of Monero. Mining uses CPU, memory and energy; rewards depend on hardware and network difficulty.

-
02

Build a collection. Trade your discoveries.

Collect broadly or focus on a theme. Your encrypted local wallet controls your cards. Trade decks lets two players sign a multi-card swap that settles together when mined. Fixed-price sales and timed auctions live in the connected peer’s market. Transfers remain pending until mined, and chain reorganizations can change ownership and confirmations.

-
03

Host a peer. Grow a community.

A peer can host a general-purpose market or a community devoted to a collection. Listings and orders stay with that host, while card ownership follows the shared blockchain. Sales allocate a configurable hosting fee to the operator and a hardcoded 1% author fee. Prices are in USD with XMR cryptocurrency settlement planned; today payments, fees and payouts are simulations only.

-
04

Custom trading card games — coming later.

Playing TCGs with your cards and hosting custom TCGs on a peer are planned, not implemented. The open-source direction is to give operators freedom to adapt their market and future games; publishing the software license is still pending. Built-in collection curation and custom rules hosting are also future work. Shared consensus remains the same across compatible peers.

+
01

Mine with a CPU. Discover a card.

RandomX—the algorithm used by Wikideck and Monero—is designed to make specialized ASICs less advantageous and general-purpose CPUs more competitive. Mine a block to earn a one-of-a-kind card featuring a random illustrated Wikipedia article.

Mining, rewards & network facts

ASIC resistance is a design goal, not a guarantee of equal performance. Results depend on hardware and network difficulty; there is no promised reward rate or profit. Wikideck is an independent network and does not share Monero’s hashpower or security. Mining uses CPU, memory, electricity and time.

+
02

Build a deck that feels like yours.

Collect across the encyclopedia or follow a theme. Your encrypted local wallet controls your cards. Trade multi-card bundles with another player, then explore fixed-price listings and timed auctions on the connected peer’s market.

How ownership and trades work

Both players sign the same card list; the whole swap is applied together when mined or rejected. Transfers remain pending until confirmed, and a chain reorganization can change confirmed ownership. Looking up a public wallet address reveals its confirmed holdings.

+
03

Trade locally. Grow a collector community.

Every peer can host its own market, so communities can create a place to trade around their interests. New listings are priced in XMR, but all checkout, fees and payouts are simulated today. Never send real XMR.

Market fees & what “simulated” means

Listings and orders stay with the market host; NFT ownership follows the shared blockchain. The operator sets a hosting fee and the project author fee is 1%; both are deducted from simulated seller proceeds. Card delivery is a real on-chain transfer after the mock payment step. No payable Monero address or live payment processor is enabled.

+
04

And then, play.

Trading-card games are the fun we’re building toward: deck-building, collecting, and community-made ways to play with your cards.

What is available now?

Playable TCGs, match systems, deck rules and peer-hosted custom games are not implemented yet. Today’s card stats are collectible snapshots, not final game balance or a promise of financial value. This is an experimental testnet, not a public production network.

-
Collectible cards, not ownership of Wikipedia.

NFT rewards represent article snapshots, not rights to Wikipedia text or images. Follow each card’s attribution and licenses. This is an experimental testnet, not a launched production network; never send real XMR to its mock checkout. Current stats are not final TCG rules or a promise of financial value.

+
Collectible snapshots—not ownership of Wikipedia.

Cards do not grant rights to Wikipedia text or images. Check each card’s attribution and licenses. This is an experimental testnet; cards have no promised monetary value.

: dialog === 'wallet' ? <>
YOUR LOCAL TESTNET IDENTITY

A wallet for your wonders.

No server login. This recoverable wallet controls native NFTs through local signatures. It is separate from the original demo wallet.

{wallet?.address ?? 'Wallet unavailable. Enable local browser storage and retry.'}

{owned.length} confirmed native NFTs in your collection

diff --git a/src/Marketplace.tsx b/src/Marketplace.tsx index 44c48c4..5c0da34 100755 --- a/src/Marketplace.tsx +++ b/src/Marketplace.tsx @@ -154,8 +154,8 @@ export function Marketplace({ wallet, snapshot, rpcAvailable, onNotice }: Props) return
{page&&(page.info.marketEnabled===false||page.info.tradingEnabled===false)&&

{page.info.marketEnabled===false?'This peer does not offer a public marketplace.':'This peer has paused new trading.'} Existing orders, cancellations and resolution remain accessible through Your activity.

} {page?.info.hostFeeAddress&&

Host fee wallet (public payout recipient, not a deposit address): {page.info.hostFeeAddress}

} -
THIS PEER’S COLLECTOR EXCHANGE

Your next find.
Your kind of market.

Buy a fixed-price card or join a timed auction. Prices are listed directly in XMR atomic units (12 decimal places). Every peer can host its own market; listings and orders remain local to that host.

PEER-HOSTED · COMMUNITY-DRIVEN
-

Sales support the hosting peer’s operator through a configurable fee and the project author through a hardcoded 1% fee. Both are deducted from seller proceeds. Collection-specific curation tools and peer-hosted custom TCGs are planned, not available yet.

+
A MARKET RUN BY THIS PEER

Find your next card.
Trade with your people.

Browse fixed-price cards or join a timed auction. Prices are shown in XMR. Each peer runs its own market, so listings and orders stay with this host.

PEER-HOSTED · COMMUNITY-DRIVEN
+

The host sets its market fee; a separate 1% author fee also applies. Both are taken from simulated seller proceeds and shown before signing. Community curation and custom trading-card games are planned, not available yet.

Mock payments only · never send real XMR

Quotes, payment confirmations, refunds, fees, and automatic seller payouts are simulated. Card delivery is a real on-chain transfer. There is no payable Monero address. Listings are local to this marketplace node, not shared by peers.

SANDBOX
{(['browse','sell','orders','custody'] as const).map(t=>)}
{tab==='custody'&&} diff --git a/src/TradeDesk.tsx b/src/TradeDesk.tsx index cfa1182..97e2a72 100755 --- a/src/TradeDesk.tsx +++ b/src/TradeDesk.tsx @@ -206,17 +206,17 @@ export function TradeDesk({ wallet, snapshot, rpcAvailable, onNotice }: Props) { : tx.cardHash === card.block.tokenId))); return
-
PLAYER-TO-PLAYER · ATOMIC SETTLEMENT

Trade decks

Browse a public wallet deck, choose multiple cards on both sides, then exchange a signed offer. The complete trade settles as one indivisible on-chain transaction.

Up to {CONSENSUS.maxTradeCards} cards per side
+
PLAYER-TO-PLAYER · THE WHOLE SWAP OR NONE

Build a card-for-card trade

Choose cards from each collection, agree on the swap, and both sign. The network settles the entire bundle together—never a partial trade.

Up to {CONSENSUS.maxTradeCards} cards per side
{!wallet &&

Open or restore your wallet to build and accept trade offers.

} {!rpcAvailable &&

Node is unavailable. Reconnect before creating or accepting a trade.

} -
setAddress(event.target.value)} placeholder="Paste a 64-character wallet address" maxLength={64} autoComplete="off"/>

Decks are public canonical ownership at the node’s reported chain tip. Viewing an address can reveal its holdings.

+
setAddress(event.target.value)} placeholder="Paste a 64-character wallet address" maxLength={64} autoComplete="off"/>

Wallet holdings are public on this chain. Looking up an address reveals its confirmed cards at the node’s current chain tip.

toggle(setOffered, offered, id)} disabled={!wallet || busy}/>
Swap
toggle(setRequested, requested, id)} disabled={busy || !remoteDeck}/>
{offered.size} offered · {requested.size} requested
-
OFFER JSON · COPY OR PASTE

Only the proposing wallet signs when creating an offer. It is not active until the addressed player reviews and accepts it. Acceptance signs all requested cards and submits one atomic trade bundle; stale offers are rejected.