diff --git a/.gitattributes b/.gitattributes index 3c93e21..1dce17d 100644 --- a/.gitattributes +++ b/.gitattributes @@ -3,3 +3,4 @@ *.png binary *.joblib binary *.parquet binary +tests/fixtures/ofac/*.xml -text diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..77693db --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,40 @@ +# Dependency update automation. Updates arrive as pull requests and go through the full CI +# (tests, dependency audit, Docker smoke test); nothing is merged or published automatically. +# The hash locks (requirements/*.lock.txt) are regenerated with the commands in their +# headers; Dependabot keeps them hash-pinned when it bumps a version. +version: 2 +updates: + - package-ecosystem: pip + directory: /requirements + schedule: + interval: weekly + open-pull-requests-limit: 5 + # the serving image's ML stack must stay equal to the model registry's training + # environment (requirements/serve.in): bumped deliberately, with a retrain + ignore: + - dependency-name: numpy + - dependency-name: pandas + - dependency-name: pyarrow + - dependency-name: scikit-learn + - dependency-name: xgboost + - dependency-name: xgboost-cpu + - dependency-name: joblib + groups: + python-minor-and-patch: + update-types: [minor, patch] + - package-ecosystem: npm + directory: /frontend + schedule: + interval: weekly + open-pull-requests-limit: 5 + groups: + npm-minor-and-patch: + update-types: [minor, patch] + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + - package-ecosystem: docker + directory: / + schedule: + interval: weekly diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b1451d2..facec80 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,7 +2,14 @@ name: CI on: push: + branches: [main] # pull requests run through pull_request; avoids running every check twice pull_request: + workflow_dispatch: + +# a newer push to the same branch or PR supersedes the running checks +concurrency: + group: ci-${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true # least privilege: CI only needs to read the repository permissions: @@ -12,6 +19,7 @@ jobs: python: name: python / ${{ matrix.os }} / py${{ matrix.python }} runs-on: ${{ matrix.os }} + timeout-minutes: 30 # the suite takes 2-4 min; a hung async test must not hold a runner for 6 h strategy: fail-fast: false matrix: @@ -23,8 +31,11 @@ jobs: with: python-version: ${{ matrix.python }} cache: pip - - name: Install - run: python -m pip install -e ".[dev]" + cache-dependency-path: requirements/dev.lock.txt + - name: Install (hash-locked; nothing resolved or built from unpinned sources) + run: | + python -m pip install --require-hashes -r requirements/dev.lock.txt + python -m pip install --no-deps --no-build-isolation -e . - name: Lint run: | ruff check . @@ -32,8 +43,31 @@ jobs: - name: Test (synthetic fixtures only; the real dataset is never needed in CI) run: python -m pytest -q + deployed-locks: + # the suite on the exact versions the serving image and the VM install (the dev lock + # resolves newer ones); Python 3.12 is what Ubuntu 24.04 ships on the VM + name: python / deployed locks / py3.12 + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 + with: + python-version: "3.12" + cache: pip + cache-dependency-path: | + requirements/serve.lock.txt + requirements/test.lock.txt + - name: Install (serving lock, a superset of the VM lock, plus pytest) + run: | + python -m pip install --require-hashes -r requirements/serve.lock.txt -r requirements/test.lock.txt + python -m pip install --no-deps --no-build-isolation -e . + - name: Test + run: python -m pytest -q + frontend: runs-on: ubuntu-latest + timeout-minutes: 15 defaults: run: working-directory: frontend @@ -49,9 +83,41 @@ jobs: - run: npm test - run: npm run build + audit: + name: dependency audit + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 + with: + python-version: "3.13" + - name: Known vulnerabilities in the locked Python dependencies (CI, serving image, VM) + run: | + python -m pip install --require-hashes -r requirements/audit.lock.txt + for lock in dev serve live; do + pip-audit --disable-pip --require-hashes --progress-spinner off \ + -r "requirements/$lock.lock.txt" + done + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + with: + node-version: "22" + - name: Known vulnerabilities in the dashboard's npm dependencies + working-directory: frontend + run: npm audit --audit-level=high + + shell: + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - name: Shellcheck (installer, smoke tests) + run: shellcheck deploy/oracle/*.sh scripts/*.sh docker/entrypoint.sh + docker: runs-on: ubuntu-latest - needs: [python, frontend] + timeout-minutes: 30 + needs: [python, deployed-locks, frontend, audit] steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Build images (hash-locked dependencies, digest-pinned bases) diff --git a/.github/workflows/publish-demo-image.yml b/.github/workflows/publish-demo-image.yml index fe2b473..3cb44e9 100644 --- a/.github/workflows/publish-demo-image.yml +++ b/.github/workflows/publish-demo-image.yml @@ -4,8 +4,17 @@ name: Publish demo image # models takes minutes), validates it, and publishes it to GHCR so that Render pulls a # prebuilt image instead of training during its own build (which exceeded Render's limit). # Only synthetic data and synthetic-trained models are in this image (scripts/check_demo_image.sh). +# +# Release gate: an image is only ever built from a commit whose full CI run (tests on Linux +# and Windows, frontend, dependency audit, shellcheck, Docker smoke test) succeeded. +# * Automatically: after CI completes successfully for a push to main (workflow_run), for +# exactly the commit CI tested (not whatever main points at by then). +# * Manually (workflow_dispatch on main): the same check is made through the API first. +# A failed, cancelled or still-running CI publishes nothing. on: - push: + workflow_run: + workflows: [CI] + types: [completed] branches: [main] workflow_dispatch: @@ -20,12 +29,37 @@ concurrency: jobs: publish: runs-on: ubuntu-latest - if: github.ref == 'refs/heads/main' + if: >- + github.ref == 'refs/heads/main' && ( + github.event_name == 'workflow_dispatch' || ( + github.event.workflow_run.conclusion == 'success' && + github.event.workflow_run.event == 'push' && + github.event.workflow_run.head_branch == 'main' && + github.event.workflow_run.head_repository.full_name == github.repository)) permissions: contents: read packages: write + actions: read # to confirm the CI result for the commit + env: + # the commit CI tested (workflow_run), or main's head for a manual run + SHA: ${{ github.event.workflow_run.head_sha || github.sha }} steps: + - name: Require a successful CI run for this exact commit + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + ok=$(gh api "repos/${GITHUB_REPOSITORY}/actions/workflows/ci.yml/runs?head_sha=${SHA}&event=push&status=success" \ + --jq '.total_count') + if [ "${ok:-0}" -lt 1 ]; then + echo "::error::CI has not succeeded for a push of ${SHA}; refusing to publish" + exit 1 + fi + echo "CI succeeded for ${SHA} (${ok} run(s))" + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + ref: ${{ env.SHA }} + persist-credentials: false - name: Image name and version id: meta @@ -36,11 +70,13 @@ jobs: echo "version=${version}" >> "$GITHUB_OUTPUT" - name: Build synthetic demo image (linux/amd64; hash-locked deps, digest-pinned bases) + env: + VERSION: ${{ steps.meta.outputs.version }} run: | docker build --platform linux/amd64 --target demo \ --label org.opencontainers.image.source="https://github.com/${GITHUB_REPOSITORY}" \ - --label org.opencontainers.image.revision="${GITHUB_SHA}" \ - --label org.opencontainers.image.version="${{ steps.meta.outputs.version }}" \ + --label org.opencontainers.image.revision="${SHA}" \ + --label org.opencontainers.image.version="$VERSION" \ --label org.opencontainers.image.licenses=MIT \ --label org.opencontainers.image.description="ChainWatch public demo: synthetic data and synthetic-trained models only" \ -t chainwatch-demo:candidate . @@ -55,20 +91,25 @@ jobs: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | echo "$GH_TOKEN" | docker login ghcr.io -u "$GITHUB_ACTOR" --password-stdin - docker tag chainwatch-demo:candidate "$IMAGE:sha-$GITHUB_SHA" - docker push "$IMAGE:sha-$GITHUB_SHA" - # version tags are never overwritten: bump the version in pyproject.toml to publish a new one - if docker manifest inspect "$IMAGE:$VERSION" > /dev/null 2>&1; then - echo "::notice::$IMAGE:$VERSION already exists; not overwritten (published sha-$GITHUB_SHA only)" - else + docker tag chainwatch-demo:candidate "$IMAGE:sha-$SHA" + docker push "$IMAGE:sha-$SHA" + # version tags are never overwritten: bump the version in pyproject.toml to publish a + # new one. Only an explicit "manifest unknown" means the tag is free; any other + # failure (network, rate limit, auth) stops the job rather than overwrite a release. + if out=$(docker manifest inspect "$IMAGE:$VERSION" 2>&1); then + echo "::notice::$IMAGE:$VERSION already exists; not overwritten (published sha-$SHA only)" + elif grep -qiE "manifest unknown|no such manifest|not found" <<<"$out"; then docker tag chainwatch-demo:candidate "$IMAGE:$VERSION" docker push "$IMAGE:$VERSION" + else + echo "::error::could not check whether $IMAGE:$VERSION exists: $out" + exit 1 fi - digest=$(docker inspect --format '{{index .RepoDigests 0}}' "$IMAGE:sha-$GITHUB_SHA") + digest=$(docker inspect --format '{{index .RepoDigests 0}}' "$IMAGE:sha-$SHA") docker logout ghcr.io { echo "### Published synthetic demo image" echo "- digest (immutable): \`$digest\`" - echo "- tags: \`sha-$GITHUB_SHA\`, \`$VERSION\` (if new)" + echo "- tags: \`sha-$SHA\`, \`$VERSION\` (if new)" echo "- Render: image URL in render.yaml, then Manual Deploy (docs/DEPLOYMENT.md)" } >> "$GITHUB_STEP_SUMMARY" diff --git a/.gitignore b/.gitignore index cfcf3e7..64cec8b 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,7 @@ data/raw/* data/processed/* data/demo/ +data/live/ !data/raw/.gitkeep !data/processed/.gitkeep diff --git a/CHANGELOG.md b/CHANGELOG.md index f88921e..ba6c90a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,283 @@ # Changelog +## v0.8.1: second independent audit (2026-10-23, not deployed) + +Seven parallel adversarial reviews of v0.8.0 and a second review of the fixes; every code +fix has a test that fails on v0.8.0. Matrix: [docs/AUDIT.md](docs/AUDIT.md#v081-independent-audit). + +- **Security updates.** certifi 2026.10.19 (a trusted root with compromised intermediates), + pillow 13.0.0 (serving image), vitest 4.1.12; setuptools 84.1.0 (GHSA-xmj3-9gf7-h52w, + published after the first v0.8.1 validation; dev, serve and live locks). +- **Screening.** Retrospective screening uses only listings in force (no "now listed" + alerts for closed ones); the mass-removal guard measures a source's own rows; a stale + mirror cannot re-list what the official file superseded (`indicators.closed_by`); + older-dated snapshots are refused (`--allow-older`); a refused official snapshot exits 3. +- **Restore and backups.** Writers hold a shared lock, restore an exclusive one and copies + through SQLite's backup API (no file renames: a restore can no longer be overwritten by + a process starting meanwhile); the pre-restore copy includes WAL data; backups are + verified before rotation and carry a `.sha256`; a corrupted database stops the collector + (exit 78). +- **Assessment states.** A failed assessment leaves an "Assessment failed" record and keeps + its addresses for later re-screening; feed rows carry `risk_state`; the dashboard shows + "?" (insufficient evidence), "err" (failed) and "screening unavailable" (no list was + loaded) instead of "no finding". +- **Collector.** Retries are never lost on shutdown; a locked database in the failure path + is not fatal; mempool re-sync stretches are recorded as coverage gaps; the stale watchdog + needs mempool updates; stricter input validation; availability subtracts re-sync time. +- **Anomaly detector `robust-tail/3`.** "Strong" needs flags in two evidence groups (size, + fee, value, output shape): vsize and the counts that determine it are one fact. +- **Alerts.** Alerts a person acted on are kept with their notes (only untouched `new` + alerts expire after 90 days). +- **Paged risk lists.** The findings list and the investigation queue are filtered and + paged on the server (`/v1/live/findings`, `/v1/live/alerts`: type, source authority, + priority, status, time range; keyset cursors; totals), so no finding or alert is out of + the dashboard's reach any more (it showed the newest 50 / first 200). Live and + retrospective source matches are separate alert types; insufficient evidence is its + own list, never mixed with findings. Older clients keep working; a dashboard refuses + filters an older edge API would ignore. `scripts/bench_risk_pages.py`: every query + ≤ 46 ms at 50,000 observations and 50,000 alerts. +- **API.** Out-of-range ids are 422 (not 500); edge validation errors use the envelope; + `/v1` answers are `no-store`; Caddy passes GET only; the synthetic demo states a synthetic + disclaimer. +- **Deploy kit and CI.** `install.sh` verifies `EXPECTED_SHA` before changing anything and + re-executes the new installer on upgrades; CI runs the suite on the deployed locks + (Python 3.12); publish never overwrites a version tag on an inspect failure; Dependabot + leaves the ML stack alone. +- **Dashboard.** Replay never shows stale rows after an error; stale-source and + never-observed states are flagged; tab switching no longer triggers 429s; the tab is in the + URL; accessibility and contrast fixes. +- **Docs.** Restore-based rollback (reinstalling an older version on a migrated database is + unsafe); Render proxy hop-count verification procedure; real-network checklist; measured + database size per table. + +## v0.8.0: independent hardening audit (2026-10, not deployed) + +Every defect below was reproduced first; each regression test fails on v0.7.0 (`f9f8765`) +and passes now. Full matrix: [docs/AUDIT.md](docs/AUDIT.md#v080-independent-hardening-audit). + +- **Indicator data.** + - Empty or mass-delisting snapshots are refused unless `--allow-mass-removal`. + - Snapshots are diffed against active listings (reverted content re-lists). + - The official SDN file and its mirror are one ranked authority: an official snapshot + closes the mirror's extra listings; the fallback mirror never delists or re-lists + official listings. One match per authority. v0.7 alerts are re-keyed, keeping their + status. + - Truncated XML falls back to the mirror; `--fallback` with `--file` is refused. + - XML parser: UTF-8 only, bounded memory per record and per party, https on every + redirect hop. +- **Screening and alerts.** + - Retrospective screening covers the reload window and runs in the collector on reload. + - Graph relations re-screen parents at the child's time, deduplicated, with coverage. + - Alert keys carry authority and role; `alert_txids` makes upserts idempotent. + - Anomaly detector `robust-tail/2`: "strong" needs two flagged measurements; + `min_reference` 1,000. Risk engine `risk-engine/2`. +- **Collector.** + - Overall REST deadline and 16 MB body cap; lifecycle (mined is final) remembered + across waits; block conflicts not fetched. + - A repeated `mempoolSequence` is a re-sync, not new traffic. + - DB errors contained per write; disk-full rollback detected; counters after commit. + - Feature and sequence validation; single-transaction migrations; consistent reads. + - Configuration ranges validated (exit 78 on invalid config). +- **Edge API and dashboard proxy.** + - The dashboard's own polling cannot be starved by anonymous cache-busting; snapped + windows; 60 s last-good fallback; overall upstream deadline; 15 s risk summary cache + (cold 0.48 s → 0.10 s at the cap). + - SSE hard deadline; token format checked; `CHAINWATCH_LIVE_TOKEN_NEXT` for rotation + without downtime; credentials redacted from status. +- **Deployment.** Caddy read/idle timeouts and GET/HEAD only; `install.sh` token and + firewall fixes; CI job timeouts, one run per PR, shellcheck. +- **Dashboard.** No silent feed freeze; explicit unavailable states; server-provided + anomaly baseline; superseded sources labelled; accessibility fixes. +- **Release blockers (final pass).** + - Bounded retries of transient detail-fetch failures (exponential backoff with jitter, + request-budget accounting, transient vs permanent classification, never past the queue + age limit; `fetch_max_attempts`, `fetch_retry_base_s`). + - Security headers on 500 answers (dashboard and edge). + - CI installs a hash lock (`requirements/dev.lock.txt`) and audits every lock (pip-audit, + npm audit); Dependabot for pip, npm, Actions and Docker. + - The public demo image is published only after CI succeeded for that exact commit. + - `stats` for 24 h at the cap: 220 → 160 ms (identical output). +- **Research documents.** Feature-subset gain shares recomputed over the trees prediction + uses; tie-aware P@20; below-chance late ranking reported; amendments section. No + published AP, interval or split changed. + +## v0.7.0: risk intelligence for the live monitor (2026-10, not deployed) + +- **Separate assessment layers.** Every fetched transaction is assessed by separate layers + that are never blended into one score (`src/chainwatch/risk/`, [RISK_ENGINE.md](docs/RISK_ENGINE.md)): + - **A. Source-backed screening**: + - address extraction (`live-features/2`); + - base58check / bech32 / bech32m validation; + - versioned OFAC SDN snapshots: the official XML is streamed, and a third-party + mirror is the fallback; + - point-in-time matching with full provenance; + - outcomes `SCREENING_MATCH`, `NO_KNOWN_SCREENING_MATCH`, + `SCREENING_DATA_UNAVAILABLE`, `INSUFFICIENT_INFORMATION`. + - **A'. Observed-graph relations** at distance 2, within this collector's observations + only. + - **B. Behavioural anomalies** (`robust-tail/1`): + - empirical tail probability and robust z over 8 measurements, against the previous + 2,000 fetched transactions; + - `INSUFFICIENT_BASELINE` below 500; + - per-measurement explanations. + - **C. Supervised gate**: a model card must prove live validation, so the layer returns + `NO_VALIDATED_MODEL`. +- **Engine behaviour.** + - Each layer runs in its own guard, so one failure does not stop the others. + - An ordinal review priority (P1–P4) that is not a probability. + - `insufficient_evidence` abstention. + - About 2 ms per transaction. +- **Alerts.** + - Grouped and deduplicated review queue; a repeat of a dismissed alert is suppressed, a + repeat of a resolved one reopens it. + - Retrospective alerts when a later snapshot lists an earlier observed address; the + original record is never rewritten. + - Statuses change through the CLI only (`chainwatch-live alerts`), with an audit log. + - No external notifications. +- **Lifecycle.** mined / removed / replaced states are tracked for display only. +- **API.** + - New routes: `/v1/live/risk/summary`, `/v1/live/findings`, `/v1/live/alerts`. + - `risk` and `lifecycle` in the transaction detail; `risk_priority` and `risk_assessed` + in feed rows. + - Proxied by the remote backend. +- **Dashboard.** Risk overview, investigation queue, recent findings, a per-transaction + assessment with evidence and limitations, and a priority column. Mock data is labelled + everywhere, and the wording is checked by tests. +- **Deploy.** + - `chainwatch-indicators.service` / `.timer`: daily refresh, `MemoryMax=400M`. + - `chainwatch-live indicators update|status` with `--fallback` and `--file`. +- **Data feasibility and Layer C decision** ([RISK_DATA_FEASIBILITY.md](docs/RISK_DATA_FEASIBILITY.md)): + - no labelled dataset maps to live features under usable terms, so no live model is + trained; + - an offline diagnostic whose protocol was committed before the runs ([results](docs/LIVE_FEATURE_SUBSET_RESULTS.md)) + restricted Elliptic++ to the 16 live-computable features; + - XGBoost AP fell from 0.797 to 0.646 (paired Δ −0.151, 95% [−0.216, −0.089]) and + collapses after step 42; + - rejected for promotion. +- **Verification.** + - 34 risk tests, 410 Python and 41 frontend tests in total. + - The browser end-to-end test now covers TEST indicator list → matches → UI. + - The soak test now refreshes indicators mid-run and checks that every row is + assessed. + - Real OFAC data parsed: official XML 516 addresses, mirror 531. + - Audit findings: [AUDIT.md](docs/AUDIT.md#v070-risk-intelligence-audit). +- **Not done.** + - No measurement of the anomaly layer on real traffic. + - Nothing deployed. + +## v0.6.0: always-on collector kit (2026-10, prepared, not deployed) + +- **`chainwatch-live`** is a lightweight entry point with no ML imports. Commands: + - `collect` runs the collector; + - `serve-edge` serves a token-protected, read-only edge API on 127.0.0.1; + - `backup` takes an online SQLite backup, runs an integrity check and rotates copies; + - `report` prints reliability figures. +- **Recovery and gap tracking:** + - an `outages` table records `collector_down` (clean or unclean exit, measured from the + last heartbeat), `disconnected`, and `sequence_gap` (the mempool update sequence jumps + within a connection); + - "observed share" availability is computed from those outages; + - old databases migrate automatically. +- **Storage:** retention by age as well as by row count, hourly WAL checkpoints and an + index on fetch time. 50,000 rows measured at about 63 MB. +- **Edge API:** + - bearer token of at least 32 characters, compared in constant time; + - per-client rate limit, body size limit, `no-store`, security headers; + - no docs or OpenAPI routes; + - `/health/live` and `/health/ready`. +- **Dashboard remote mode** (`RemoteBackend`, `configs/public-demo-live.yaml`): the + Render service proxies the edge API over HTTPS with the token, through a short shared + cache. The Live tab shows how the data arrives, the last successful observation, the + 24-hour observed share and a table of gaps and outages. +- **Deployment kit** (`deploy/oracle/`): + - hardened systemd units (restart on crash, start on boot, memory and CPU caps); + - daily backup timer; + - Caddy HTTPS template; + - idempotent `install.sh` that installs from a hash-locked, ML-free + `requirements/live.lock.txt`; + - `smoke_live.sh`. +- **Tests:** 24 new Python tests in `tests/test_live_cloud.py`, plus 1 frontend test. The + install was also tested in a fresh Ubuntu 24.04 container, including a `kill -9` + restart; see `docs/LIVE_CLOUD.md` §11. +- **Engineering audit** (four independent reviews; table in `docs/AUDIT.md`; no P0): + - **P1 fixed:** + - the reconnect backoff overflowed after ~8.5 h of outage and silently stopped + reconnecting; + - a dead worker or heartbeat left a live-looking process that no longer collected + (now fatal exit 1, so systemd restarts it); + - concurrent event-stream opens bypassed the cap and could take the Render app's health + check down; + - the dashboard labelled mock data as real, and showed "Connected", whenever the + status call failed; + - feed rows were not reachable by keyboard; + - the protocol-timing claim in the research docs is now stated as unverifiable. + - **Remote proxy:** single flight, cached failures, LRU, upstream request budget, + bounded reads. + - **Edge API:** the token holder is exempt from the per-IP limit. + - **Collector:** + - removed and mined txids are not fetched; + - outages start at the last message; + - payload amounts are range-checked; + - `Retry-After` dates are honoured; 5xx pauses fetching; + - `restore` command. + - **Store:** a covering index and planner hints: at 50k rows, `stats(60)` 92 → 14 ms and + the default page 15.7 → 2.8 ms. + - **Deploy:** + - token file 0600 root:root; + - host, REF and `EXPECTED_SHA` checks; + - Caddyfile validated before replacing; + - `SystemCallFilter`, loopback-only edge API (systemd exposure 3.0 → 1.3 / 1.1). + - **Dashboard:** + - honest source and connection states; + - stale-response guards; + - event-stream reconnect after HTTP errors; + - WCAG AA colours; + - no horizontal scroll at 390 px; + - charts without a fake final-minute drop. + - **Research:** + - `manifest.json` records the actual raw-file hashes; it used to record the + published constants, even for synthetic data; + - misquoted numbers corrected against `reports/`, and the README leads with the + primary pooled result. No result changed. +- **Verification:** + - 33 new regression tests (`tests/test_live_faults.py`, `tests/test_live_security.py`) + plus 13 frontend tests. + - A real-systemd container test of `install.sh` and the units: crash restart, + lock-contention fatal exit, backup/restore, upgrade, input validation, reboot. + - Fault-injection soak runs with `scripts/soak_test.py`: + - 6 min: 11 of 11 checks passed; + - 110 min: 52 faults, 99.97 % API availability, 0 tracebacks, integrity ok; it found that + the database can end a little above the row cap (now pruned on stop). + - A browser end-to-end test, `scripts/e2e_live_browser.py`: 10 of 10 checks passed. +- **Not done:** no cloud resource has been created, real mempool.space ingestion is + still unverified (the build proxy blocks it), and no 24/7 reliability is claimed. + `render.yaml` and the public demo are unchanged. + +## v0.5.0: live Bitcoin mempool monitor MVP (2026-10) + +- **Collector** (`chainwatch live-collect`, `src/chainwatch/live/`): asynchronous pipeline + from the mempool.space WebSocket (`track-mempool-txids`) through REST details to + observation-time features and SQLite. + - reconnection with exponential backoff and jitter, plus a staleness watchdog; + - bounded dedupe, queue and retention; deterministic sampling; + - token-bucket request limit that honours HTTP 429 `Retry-After`; + - timeouts, idempotent storage, graceful shutdown and metrics. +- **API** (`/v1/live/status|transactions|transactions/{txid}|stats|events`): read-only, + with SSE streaming. Disabled (404 `live_disabled`) unless `live.enabled`; the API never + contacts mempool.space. +- **Dashboard:** "Live monitor" tab with connection state, throughput and fee-rate charts, + a filterable feed, a detail panel with mempool.space links, and explicit labels for + real, synthetic and mock data. +- **Features and indicators** respect Bitcoin semantics (change outputs, no ownership + inference). Indicators are rule-based, not predictions. No Elliptic++ model is applied + to live data. +- **Tests:** 44 new Python tests (local WebSocket and REST mocks), 3 frontend helper tests; + `scripts/live_load_test.py`; `scripts/mock_mempool.py`. +- **Not verified:** real mempool.space ingestion. The build environment's proxy refused + every connection (HTTP 403). +- The public demo image and `render.yaml` (0.4.1) are unchanged. No research result + changed. + ## v0.4.1: deployable on Render Free (2026-10) - **Fix:** the first Render deployment failed after 2 h (exit 143), because Render's @@ -24,7 +302,7 @@ service that serves the frozen research models. - **Phase 1, chronological baselines.** XGBoost pooled test AP 0.797 (logistic regression 0.231). Per-step evaluation shows a collapse after step 42: AP 0.917 on steps 35–42 vs 0.043 on 43–49. -- **Phase 2, pre-registered rolling-origin backtest.** Five retraining strategies with +- **Phase 2 rolling-origin backtest (protocol fixed before the runs, author's record).** Five retraining strategies with explicit label latency, several seeds and a block bootstrap over time steps. Retraining as labels arrive raises AP on steps 43–49 from 0.050 to 0.458 (+0.41, 95% CI 0.16–0.62). This is **exploratory**, because that period had been inspected in Phase 1. diff --git a/README.md b/README.md index a31ad36..cf50e19 100644 --- a/README.md +++ b/README.md @@ -3,19 +3,23 @@ [![CI](https://github.com/Apostal322/ChainWatch/actions/workflows/ci.yml/badge.svg)](https://github.com/Apostal322/ChainWatch/actions/workflows/ci.yml) [![License: MIT](https://img.shields.io/badge/license-MIT-blue)](LICENSE) ![Python 3.11–3.13](https://img.shields.io/badge/python-3.11%E2%80%933.13-blue) -![Tests](https://img.shields.io/badge/tests-265%20Python%20%2B%203%20frontend-brightgreen) +![Tests](https://img.shields.io/badge/tests-561%20Python%20%2B%2058%20frontend-brightgreen) **How well does an illicit-transaction ranking model hold up when behaviour changes over time, and does retraining on newly arriving labels help?** ChainWatch answers this on the public [Elliptic++](https://github.com/git-disl/EllipticPlusPlus) Bitcoin dataset (203,769 transactions, 49 time steps, 77% unlabelled) with a -leakage-guarded, pre-registered temporal study. It then serves the frozen research models +leakage-guarded temporal study whose protocol was fixed before the runs (author's record; +not verifiable from the published git history). It then serves the frozen research models through a FastAPI and React replay application that reproduces the research scores exactly. -> **Scope.** A *historical replay* of a research dataset, not live blockchain monitoring. -> Scores rank transactions by similarity to past *labelled* illicit activity; they are not -> calibrated probabilities, evidence of crime, or validated for current transactions. +> **Scope.** The research and its replay are *historical*. Scores rank transactions by +> similarity to past *labelled* illicit activity; they are not calibrated probabilities, +> evidence of crime, or validated for current transactions. A separate, opt-in +> [live monitor](docs/LIVE_MONITOR.md) observes real mempool data and applies **no** trained +> model: it screens addresses against sourced lists (OFAC SDN) and flags statistically unusual +> transactions, each reported by its own layer and never as evidence of fraud. ![ChainWatch replay dashboard on synthetic demo data](docs/images/demo_replay.png) Replay dashboard running the synthetic demo (every screenshot in this repository uses @@ -26,8 +30,9 @@ synthetic data; real-data results appear only as aggregate figures under `report | Finding | Result | Evidence status | |---|---|---| | Strong baseline hides a collapse | XGBoost pooled test AP **0.797**, but **0.917** on steps 35–42 vs **0.043** on 43–49 | one-time test evaluation | -| Ranking itself degrades, not just the base rate | ROC-AUC 0.97 → 0.70 after step 42 | diagnostic | -| Retraining as labels arrive | late-period AP **0.050 → 0.458** (+0.41, 95% CI 0.16–0.62) | **exploratory**: period seen before | +| Ranking itself degrades, not just the base rate | same XGBoost model: ROC-AUC 0.97 → 0.69 after step 42 | diagnostic | +| Retraining as labels arrive (protocol's primary comparison: pooled AP, steps 35–49) | expanding vs static: AP 0.807 → 0.892, Δ **+0.085** [95% CI 0.024, 0.229] | **exploratory**: period seen before | +| …concentrated after the shift (sub-period 43–49; its boundary came from Phase 1 inspection) | AP 0.050 → 0.458 (+0.41 [0.16, 0.62]); expanding beats static at all 7 late steps (exact one-sided sign test p = 1/128) | **exploratory**; the CI comes from a block bootstrap over only 7 steps (few distinct resamples), so its coverage is likely below 95% | | Slower labels shrink the gain | label latency 3: Δ AP +0.065 [0.013, 0.173] | exploratory sensitivity | | Unlabelled transactions crowd the review budget | known illicit in top 20 per step ≈ 0 on 43–49 when unknowns compete | exploratory | @@ -44,7 +49,7 @@ in [the temporal robustness report](docs/TEMPORAL_ROBUSTNESS.md). |---|---| | **Leakage-safe, reproducible experiments**: chronological splits, label-latency canaries, configs, seeds and data hashes recorded per run | [evaluation protocol](docs/EVALUATION.md), `tests/test_splits_and_leakage.py` | | **Distribution-shift analysis**: prior vs covariate vs class-conditional shift, within-period learnability, calibration | [temporal robustness §3](docs/TEMPORAL_ROBUSTNESS.md) | -| **Adaptive retraining under delayed labels**: pre-registered rolling-origin backtest, 5 strategies, block bootstrap over time | [protocol](docs/PHASE2_PROTOCOL.md) (committed before the experiments) | +| **Adaptive retraining under delayed labels**: rolling-origin backtest, 5 strategies, block bootstrap over time | [protocol](docs/PHASE2_PROTOCOL.md) (written before the runs per the author's record; it first appears in git alongside the results, so the timing is not independently verifiable) | | **Training/serving consistency**: one `FeatureStore`; 234,596 replayed scores equal the research predictions (max diff **0.0**), natively and in Docker | `chainwatch verify-replay`, [report](reports/phase3/replay_consistency.json) | | **API engineering**: typed FastAPI contract, provenance-checked model registry, TreeSHAP explanations, size limits, rate limiting, security headers | [inference contract](docs/INFERENCE_CONTRACT.md), [architecture](docs/ARCHITECTURE.md) | | **Docker and CI/CD**: hash-locked dependencies, digest-pinned images, read-only non-root demo; CI on Ubuntu and Windows plus a container smoke test | [`Dockerfile`](Dockerfile), [CI](.github/workflows/ci.yml) | @@ -107,10 +112,85 @@ Research numbers are guaranteed for the recorded library versions (scikit-learn xgboost 3.4.1, Python 3.13); every artifact records its config, seed, data hashes and git commit. +## Live Bitcoin monitor (Phase 5, local and opt-in) + +A zero-cost asynchronous pipeline: +1. the mempool.space WebSocket (`track-mempool-txids`) announces new txids; +2. they are validated and deduplicated, and a 5% hash sample is taken; +3. details are fetched over REST, rate-limited (30 requests/min, pauses on HTTP 429) with + bounded queues; +4. observation-time features and **rule-based** indicators are computed; +5. results go to SQLite, then to a read-only FastAPI (`/v1/live/*`, server-sent events) + and the "Live monitor" tab. + +```bash +chainwatch --config configs/live.yaml live-collect # separate process; talks to mempool.space +chainwatch --config configs/live.yaml serve # dashboard reads the SQLite file +``` + +* Live mode is **disabled** in the public demo and in every other config. +* The tab labels real network data separately from synthetic data, and labels any + non-mempool.space source as a mock. +* Output sums are never treated as payment amounts, and no ownership is inferred. +* The build environment cannot reach mempool.space. The maintainer reported a run against + the real network from Windows: 471 txids received in 120 s, 16 fetched, no rate-limit + errors and no reconnections. That shows the pipeline works on real data; it says nothing + about continuous reliability. Verification status, measurements and limitations are in + [docs/LIVE_MONITOR.md](docs/LIVE_MONITOR.md), and a plan for a properly evaluated live + model in [docs/LIVE_ML_PROPOSAL.md](docs/LIVE_ML_PROPOSAL.md). + +### Always-on collector (v0.6.0, prepared, not deployed) + +`deploy/oracle/` holds a kit for running the collector on its own on a small Linux VM, +targeting Oracle Cloud Always Free. It contains systemd units, Caddy HTTPS, an +idempotent `install.sh` and `smoke_live.sh`. + +* The VM runs only `chainwatch-live`: the collector, a token-protected read-only edge API + on 127.0.0.1 and daily backups. It has hash-locked dependencies and no ML stack. +* The Render dashboard can proxy that API server-to-server + (`configs/public-demo-live.yaml`). Browsers never see the token or the database. +* Restarts, disconnections and mempool sequence gaps are recorded as outages, and the + dashboard shows them together with the observed share of time. + +Nothing has been deployed, and no 24/7 reliability is claimed. See +[docs/LIVE_CLOUD.md](docs/LIVE_CLOUD.md) for provider limits, Oracle's idle-reclamation +risk, the manual activation steps and the 24-hour test plan. + +### Risk intelligence (v0.7.0, hardened in v0.8.0 and v0.8.1; live monitor) + +Every fetched transaction is assessed by separate layers that are never blended into one +score ([contracts](docs/RISK_ENGINE.md)): + +| Layer | Output | Means | Does not mean | +|---|---|---|---| +| A. Screening | `SCREENING_MATCH` + provenance, or `NO_KNOWN_SCREENING_MATCH`, `SCREENING_DATA_UNAVAILABLE`, `INSUFFICIENT_INFORMATION` | an enabled source (OFAC SDN, refreshed daily, versioned) lists an input or output address | fraud, or who controls the funds | +| A'. Observed graph | `RELATION_FOUND` (distance 2, observed data only) | the tx spends an output of an observed tx that spent from a listed address | ownership or culpability | +| B. Behavioural anomaly | `ANOMALY` with per-measurement explanations | tail of recent sampled traffic (empirical p ≤ 0.002 and robust z ≥ 3; "strong" needs two independent evidence groups; baseline of 1,000 fetched transactions) | wrongdoing (batch payouts and CoinJoins are unusual) | +| C. Supervised | `NO_VALIDATED_MODEL`, always | no labelled data maps to live features ([feasibility](docs/RISK_DATA_FEASIBILITY.md)) | | + +* Screening is point in time: a listing counts only from when this deployment fetched it, + and matches found later are separate retrospective alerts that never rewrite records. +* A snapshot that would empty or mostly empty the list is refused, and the official SDN + file and its mirror count as one authority (an official delisting closes the mirror's + copy; the fallback mirror can never delist an official listing). +* Alerts are grouped and deduplicated in a review queue (new, under review, dismissed, + resolved, insufficient evidence). Statuses change only via the collector's CLI, and + nothing is sent externally. +* The Layer C decision was tested offline. Restricted to the 16 Elliptic++ features a + collector could compute, XGBoost keeps AP 0.646 against 0.797 with all 182 features, and + collapses after step 42 like every model. Exploratory only; rejected for promotion + ([results](docs/LIVE_FEATURE_SUBSET_RESULTS.md)). +* Verified with real OFAC data: the official XML (516 addresses, streamed in 16 MB) and the + mirror (531). Anomaly behaviour on real traffic has **not** been measured yet. + ## Limitations - **No untouched holdout.** Steps 35–49 were inspected in Phase 1, so the retraining gains are exploratory. The label latency is an assumption. +- **Protocol timing is not verifiable.** The Phase 2 protocol was written before the runs + according to the author's record, but the pre-release history is not published. +- **Publisher-computed features.** The 72 aggregate features cannot be verified to use + only within-step, pre-step-end information ([dataset card](docs/DATASET.md)). - **Unknown labels.** 77% of transactions are unlabelled and labels are heuristic; labelled-only metrics overstate operational value (the dashboard shows the gap). - **Historical model.** The features are anonymised by the publisher and need each step's @@ -122,13 +202,15 @@ git commit. ## Repository layout ```text -src/chainwatch/ data, features, training, evaluation, backtest, analysis, serving (API) +src/chainwatch/ data, features, training, evaluation, backtest, analysis, serving (API), live frontend/ React + TypeScript dashboard -configs/ default.yaml (real data), demo.yaml, public-demo.yaml (hosted demo) -tests/ 265 tests: leakage canaries, metrics, backtest causality, API contract +configs/ default.yaml (real data), demo.yaml, public-demo.yaml (hosted demo), live.yaml +tests/ 561 tests: leakage canaries, metrics, backtest causality, API contract, risk reports/ committed aggregate results and figures (no row-level data) docs/ case study, protocols, results, inference contract, deployment, audit -scripts/ screenshot capture, demo smoke test +deploy/oracle/ always-on collector: systemd units, Caddy, install and smoke scripts +scripts/ screenshot capture, demo smoke test, mock mempool (with fault injection), live + load test, soak/fault-injection test, browser end-to-end test ``` ## Documentation @@ -139,7 +221,9 @@ scripts/ screenshot capture, demo smoke test | [Temporal robustness](docs/TEMPORAL_ROBUSTNESS.md) · [protocol](docs/PHASE2_PROTOCOL.md) | Phase 2 research, CIs and negative results | | [Results](docs/RESULTS.md) · [evaluation](docs/EVALUATION.md) · [dataset card](docs/DATASET.md) | Phase 1 baselines, metrics, data provenance and licensing | | [Inference contract](docs/INFERENCE_CONTRACT.md) · [architecture](docs/ARCHITECTURE.md) | what the service may claim and how it is built | -| [Deployment](docs/DEPLOYMENT.md) · [audit](docs/AUDIT.md) · [release readiness](docs/RELEASE_READINESS.md) · [changelog](CHANGELOG.md) | hosting, security review, release checklist, v0.4.0 notes | +| [Deployment](docs/DEPLOYMENT.md) · [audit](docs/AUDIT.md) · [release readiness](docs/RELEASE_READINESS.md) · [changelog](CHANGELOG.md) | hosting, security review, release checklist, release notes | +| [Live monitor](docs/LIVE_MONITOR.md) · [always-on cloud kit](docs/LIVE_CLOUD.md) · [live ML proposal](docs/LIVE_ML_PROPOSAL.md) | Phase 5 data pipeline, API contract, limits, measurements; 24/7 deployment plan | +| [Risk engine](docs/RISK_ENGINE.md) · [data feasibility](docs/RISK_DATA_FEASIBILITY.md) · [feature-subset results](docs/LIVE_FEATURE_SUBSET_RESULTS.md) | screening, anomaly and supervised-gate contracts; dataset decision gate; Layer C experiment | | [Interview guide](docs/INTERVIEW_GUIDE.md) · [portfolio material](docs/PORTFOLIO.md) | explanations and verified resume bullets | ## Development @@ -150,9 +234,11 @@ cd frontend && npm ci && npm run typecheck && npm test && npm run build scripts/smoke_demo.sh http://localhost:8000 # end-to-end check of a running public demo ``` -**Status.** Completed: data pipeline, Phase 1 baselines, Phase 2 pre-registered backtest -and shift diagnostics, replay service and dashboard, Docker, CI. Planned (not -implemented): pickle-free model format, label-efficiency study, probability calibration +**Status.** Completed: data pipeline, Phase 1 baselines, Phase 2 retraining backtest (protocol fixed before the runs, author's record) +and shift diagnostics, replay service and dashboard, Docker, CI, live mempool monitor MVP +(no model), always-on collector deployment kit (not deployed). Planned (not +implemented): a properly evaluated live-data model, pickle-free model format, +label-efficiency study, probability calibration under prior shift, and a graph-model comparison only after a cheaper graph-feature baseline. ChainWatch contains no graph neural network. diff --git a/configs/default.yaml b/configs/default.yaml index 1150c23..40c90fe 100644 --- a/configs/default.yaml +++ b/configs/default.yaml @@ -59,7 +59,7 @@ tracking: tracking_uri: sqlite:///mlflow.db # --------------------------------------------------------------------------- # -# Phase 2: rolling-origin backtests (pre-registered in docs/PHASE2_PROTOCOL.md) +# Phase 2: rolling-origin backtests (protocol fixed before the runs: docs/PHASE2_PROTOCOL.md) # --------------------------------------------------------------------------- # backtest: label_latency: 1 # label of step u is available at the end of step u + L @@ -90,7 +90,7 @@ backtest: bootstrap: {n_resamples: 2000, block_length: 3, seed: 0} confirm_split_after: 42 # confirm sub-periods 35-42 and 43-49 (protocol §5) time_proxy_threshold: 0.9 # |Spearman(feature, time step)| on steps <= time_proxy_max_step - time_proxy_max_step: 34 # (deviation 1: added after pre-registration) + time_proxy_max_step: 34 # (deviation 1: added after the protocol was fixed) # --------------------------------------------------------------------------- # # Phase 3: inference service (docs/INFERENCE_CONTRACT.md) diff --git a/configs/live-cloud.yaml b/configs/live-cloud.yaml new file mode 100644 index 0000000..2f50530 --- /dev/null +++ b/configs/live-cloud.yaml @@ -0,0 +1,19 @@ +# ALWAYS-ON COLLECTOR VM (docs/LIVE_CLOUD.md). Used by systemd units in deploy/oracle/. +# Conservative 24/7 limits for the free public mempool.space API: one WebSocket and at most +# 12 detail requests per minute (~17k/day). Coverage is a SAMPLE, never the whole network. +extends: default.yaml + +live: + enabled: true + db_path: /var/lib/chainwatch/live.sqlite # persistent boot volume, not /tmp + sample_rate: 0.02 # ~2% of announced txids + fetch_per_minute: 12 + fetch_burst: 3 + fetch_concurrency: 1 + queue_max: 100 + fetch_max_attempts: 3 # transient failures: 2 retries at most, 2.5-5 s then 5-10 s; + fetch_retry_base_s: 5.0 # every attempt counts against fetch_per_minute + retention_rows: 50000 # plus retention_days; bounds the database (measured: ~285 MB at the cap with risk records) + retention_days: 7 + edge_rate_limit_per_minute: 240 + edge_trusted_proxy_hops: 1 # Caddy in front of the edge API diff --git a/configs/live.yaml b/configs/live.yaml new file mode 100644 index 0000000..4895e55 --- /dev/null +++ b/configs/live.yaml @@ -0,0 +1,13 @@ +# LOCAL live Bitcoin monitor (docs/LIVE_MONITOR.md). Opt-in; never used by the public demo. +# Terminal 1: chainwatch --config configs/live.yaml live-collect (talks to mempool.space) +# Terminal 2: chainwatch --config configs/live.yaml serve (reads the SQLite file) +# The replay tabs keep showing the SYNTHETIC demo (demo-setup first); live data is real and +# labelled separately in the "Live monitor" tab. +extends: demo.yaml + +live: + enabled: true + db_path: data/live/live.sqlite + sample_rate: 0.05 # ~5% of announced txids: about 18 detail requests/min at 6 tx/s + fetch_per_minute: 30 # well below the 200 req/min in mempool's sample nginx config + fetch_concurrency: 2 diff --git a/configs/public-demo-live.yaml b/configs/public-demo-live.yaml new file mode 100644 index 0000000..f647ab4 --- /dev/null +++ b/configs/public-demo-live.yaml @@ -0,0 +1,15 @@ +# Public Render dashboard WITH the remote live monitor (docs/LIVE_CLOUD.md section 7). +# Not active: render.yaml keeps public-demo.yaml until the owner switches it. +# Required Render environment variables (set in the dashboard, never in Git): +# CHAINWATCH_LIVE_URL https:// (the Caddy-fronted edge API) +# CHAINWATCH_LIVE_TOKEN the edge API token (Render "secret" env var) +extends: public-demo.yaml + +live: + enabled: true + remote_url: env:CHAINWATCH_LIVE_URL + api_token_env: CHAINWATCH_LIVE_TOKEN + remote_timeout_s: 5 + remote_cache_s: 2 + sse_max_clients: 10 # well below serving.limit_concurrency (32): streams hold a slot + sse_max_per_client: 2 diff --git a/configs/subset-augmented.yaml b/configs/subset-augmented.yaml new file mode 100644 index 0000000..5413ba7 --- /dev/null +++ b/configs/subset-augmented.yaml @@ -0,0 +1,10 @@ +# Feature-subset experiment (docs/LIVE_FEATURE_SUBSET_PROTOCOL.md): identical to the Phase 1 +# protocol in default.yaml except the feature set and the output folders. +extends: default.yaml + +paths: + artifacts_dir: artifacts/runs-subset-augmented + reports_dir: reports/phase6/subset-augmented + +data: + feature_set: augmented diff --git a/configs/subset-live.yaml b/configs/subset-live.yaml new file mode 100644 index 0000000..592da8f --- /dev/null +++ b/configs/subset-live.yaml @@ -0,0 +1,10 @@ +# Feature-subset experiment (docs/LIVE_FEATURE_SUBSET_PROTOCOL.md): identical to the Phase 1 +# protocol in default.yaml except the feature set and the output folders. +extends: default.yaml + +paths: + artifacts_dir: artifacts/runs-subset-live + reports_dir: reports/phase6/subset-live + +data: + feature_set: live_computable diff --git a/deploy/oracle/Caddyfile.template b/deploy/oracle/Caddyfile.template new file mode 100644 index 0000000..37414d1 --- /dev/null +++ b/deploy/oracle/Caddyfile.template @@ -0,0 +1,34 @@ +# HTTPS front for the edge API. install.sh replaces __CHAINWATCH_HOST__ with the VM's +# hostname, e.g. 203-0-113-7.sslip.io (free wildcard DNS for the public IP); Caddy then +# obtains and renews a Let's Encrypt certificate automatically. +{ + servers { + # slow or idle clients must not hold the edge API's 32 connections + timeouts { + read_header 10s + read_body 10s + idle 60s + } + } +} + +__CHAINWATCH_HOST__ { + encode zstd gzip + @edge { + path /v1/live/* /health/live /health/ready + method GET + } + handle @edge { + reverse_proxy 127.0.0.1:8100 + } + handle { + respond 404 + } + header { + Strict-Transport-Security "max-age=31536000" + -Server + } + request_body { + max_size 64KB + } +} diff --git a/deploy/oracle/chainwatch-backup.service b/deploy/oracle/chainwatch-backup.service new file mode 100644 index 0000000..aed3443 --- /dev/null +++ b/deploy/oracle/chainwatch-backup.service @@ -0,0 +1,35 @@ +# Daily consistent SQLite backup (online backup API + integrity check, keeps 7). +[Unit] +Description=ChainWatch live database backup +Documentation=https://github.com/Apostal322/ChainWatch/blob/main/docs/LIVE_CLOUD.md + +[Service] +Type=oneshot +User=chainwatch +Group=chainwatch +WorkingDirectory=/opt/chainwatch/app +ExecStart=/opt/chainwatch/venv/bin/chainwatch-live --config /opt/chainwatch/app/configs/live-cloud.yaml backup --dest /var/backups/chainwatch --keep 7 +Nice=10 +IOSchedulingClass=idle +MemoryMax=200M +NoNewPrivileges=yes +ProtectSystem=strict +ProtectHome=yes +PrivateTmp=yes +PrivateNetwork=yes +PrivateDevices=yes +ProtectKernelTunables=yes +ProtectKernelModules=yes +ProtectKernelLogs=yes +ProtectControlGroups=yes +ProtectClock=yes +ProtectHostname=yes +RestrictNamespaces=yes +RestrictRealtime=yes +RestrictSUIDSGID=yes +LockPersonality=yes +SystemCallArchitectures=native +RestrictAddressFamilies=AF_UNIX +CapabilityBoundingSet= +UMask=0027 +ReadWritePaths=/var/lib/chainwatch /var/backups/chainwatch diff --git a/deploy/oracle/chainwatch-backup.timer b/deploy/oracle/chainwatch-backup.timer new file mode 100644 index 0000000..2e9392d --- /dev/null +++ b/deploy/oracle/chainwatch-backup.timer @@ -0,0 +1,10 @@ +[Unit] +Description=Daily ChainWatch live database backup + +[Timer] +OnCalendar=*-*-* 03:17:00 +RandomizedDelaySec=600 +Persistent=true + +[Install] +WantedBy=timers.target diff --git a/deploy/oracle/chainwatch-collector.service b/deploy/oracle/chainwatch-collector.service new file mode 100644 index 0000000..8c60ff8 --- /dev/null +++ b/deploy/oracle/chainwatch-collector.service @@ -0,0 +1,61 @@ +# ChainWatch live mempool collector (REAL Bitcoin data from mempool.space, sampled). +# Installed by deploy/oracle/install.sh; see docs/LIVE_CLOUD.md. +[Unit] +Description=ChainWatch live mempool collector +Documentation=https://github.com/Apostal322/ChainWatch/blob/main/docs/LIVE_CLOUD.md +After=network-online.target +Wants=network-online.target +# never give up restarting (a long mempool.space outage must not stop collection for good) +StartLimitIntervalSec=0 + +[Service] +Type=simple +User=chainwatch +Group=chainwatch +WorkingDirectory=/opt/chainwatch/app +ExecStart=/opt/chainwatch/venv/bin/chainwatch-live --config /opt/chainwatch/app/configs/live-cloud.yaml collect +# crash -> restart after 10 s, backing off to 5 min on repeated failures (systemd >= 254) +Restart=always +# a config error (exit 78, EX_CONFIG) cannot be fixed by restarting: stay failed, visibly +RestartPreventExitStatus=78 +RestartSec=10 +RestartSteps=5 +RestartMaxDelaySec=300 +# SIGTERM -> graceful shutdown (final heartbeat "stopped", outage bookkeeping) +KillSignal=SIGTERM +TimeoutStopSec=30 +Environment=PYTHONUNBUFFERED=1 +# cost and blast-radius limits (measured need: < 100 MB, < 5% of one core) +MemoryMax=300M +CPUQuota=50% +TasksMax=64 +# sandbox +NoNewPrivileges=yes +ProtectSystem=strict +ProtectHome=yes +PrivateTmp=yes +PrivateDevices=yes +ProtectKernelTunables=yes +ProtectKernelModules=yes +ProtectKernelLogs=yes +ProtectControlGroups=yes +ProtectClock=yes +ProtectHostname=yes +RestrictNamespaces=yes +RestrictRealtime=yes +RestrictSUIDSGID=yes +LockPersonality=yes +SystemCallArchitectures=native +SystemCallFilter=@system-service +SystemCallFilter=~@privileged @resources @mount @debug +SystemCallErrorNumber=EPERM +ProtectProc=invisible +ProcSubset=pid +RemoveIPC=yes +RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX +CapabilityBoundingSet= +UMask=0027 +ReadWritePaths=/var/lib/chainwatch + +[Install] +WantedBy=multi-user.target diff --git a/deploy/oracle/chainwatch-indicators.service b/deploy/oracle/chainwatch-indicators.service new file mode 100644 index 0000000..4970966 --- /dev/null +++ b/deploy/oracle/chainwatch-indicators.service @@ -0,0 +1,45 @@ +# Daily refresh of risk-indicator sources (docs/RISK_ENGINE.md section 2): the official OFAC +# SDN XML, falling back to the third-party nightly extraction if the official file cannot be +# fetched. A failed refresh keeps the previous version; the dashboard shows its age. +[Unit] +Description=ChainWatch indicator source refresh (OFAC SDN) +Documentation=https://github.com/Apostal322/ChainWatch/blob/main/docs/RISK_ENGINE.md +Wants=network-online.target +After=network-online.target + +[Service] +Type=oneshot +User=chainwatch +Group=chainwatch +WorkingDirectory=/opt/chainwatch/app +ExecStart=/opt/chainwatch/venv/bin/chainwatch-live --config /opt/chainwatch/app/configs/live-cloud.yaml indicators update --source ofac-sdn --fallback ofac-sdn-mirror +TimeoutStartSec=600 +Nice=10 +IOSchedulingClass=idle +MemoryMax=400M +NoNewPrivileges=yes +ProtectSystem=strict +ProtectHome=yes +PrivateTmp=yes +PrivateDevices=yes +ProtectKernelTunables=yes +ProtectKernelModules=yes +ProtectKernelLogs=yes +ProtectControlGroups=yes +ProtectClock=yes +ProtectHostname=yes +RestrictNamespaces=yes +RestrictRealtime=yes +RestrictSUIDSGID=yes +LockPersonality=yes +SystemCallArchitectures=native +SystemCallFilter=@system-service +SystemCallFilter=~@privileged @resources @mount @debug +SystemCallErrorNumber=EPERM +ProtectProc=invisible +ProcSubset=pid +RemoveIPC=yes +RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX +CapabilityBoundingSet= +UMask=0027 +ReadWritePaths=/var/lib/chainwatch diff --git a/deploy/oracle/chainwatch-indicators.timer b/deploy/oracle/chainwatch-indicators.timer new file mode 100644 index 0000000..edd03af --- /dev/null +++ b/deploy/oracle/chainwatch-indicators.timer @@ -0,0 +1,12 @@ +# OFAC publishes changes irregularly; a daily check keeps screening sources under a day old. +[Unit] +Description=Daily ChainWatch indicator source refresh + +[Timer] +OnBootSec=5min +OnCalendar=*-*-* 04:41:00 +RandomizedDelaySec=15min +Persistent=true + +[Install] +WantedBy=timers.target diff --git a/deploy/oracle/chainwatch-live-api.service b/deploy/oracle/chainwatch-live-api.service new file mode 100644 index 0000000..4e5c0a3 --- /dev/null +++ b/deploy/oracle/chainwatch-live-api.service @@ -0,0 +1,62 @@ +# ChainWatch edge API: authenticated, read-only /v1/live/* on 127.0.0.1:8100. +# Only Caddy (HTTPS) is reachable from the internet; the SQLite file never is. +[Unit] +Description=ChainWatch live edge API (read-only, token-protected) +Documentation=https://github.com/Apostal322/ChainWatch/blob/main/docs/LIVE_CLOUD.md +After=network-online.target chainwatch-collector.service +Wants=network-online.target +StartLimitIntervalSec=0 + +[Service] +Type=simple +User=chainwatch +Group=chainwatch +WorkingDirectory=/opt/chainwatch/app +# CHAINWATCH_LIVE_TOKEN (generated on the VM by install.sh; never committed). The file is +# 0600 root:root: systemd reads it before dropping privileges, so the collector (same +# service user, parses internet data) cannot read the token file. +EnvironmentFile=/etc/chainwatch/live.env +ExecStart=/opt/chainwatch/venv/bin/chainwatch-live --config /opt/chainwatch/app/configs/live-cloud.yaml serve-edge --host 127.0.0.1 --port 8100 +Restart=always +# a config error (exit 78, EX_CONFIG) cannot be fixed by restarting: stay failed, visibly +RestartPreventExitStatus=78 +RestartSec=5 +RestartSteps=5 +RestartMaxDelaySec=120 +Environment=PYTHONUNBUFFERED=1 +MemoryMax=250M +CPUQuota=50% +TasksMax=64 +NoNewPrivileges=yes +ProtectSystem=strict +ProtectHome=yes +PrivateTmp=yes +PrivateDevices=yes +ProtectKernelTunables=yes +ProtectKernelModules=yes +ProtectKernelLogs=yes +ProtectControlGroups=yes +ProtectClock=yes +ProtectHostname=yes +RestrictNamespaces=yes +RestrictRealtime=yes +RestrictSUIDSGID=yes +LockPersonality=yes +SystemCallArchitectures=native +SystemCallFilter=@system-service +SystemCallFilter=~@privileged @resources @mount @debug +SystemCallErrorNumber=EPERM +ProtectProc=invisible +ProcSubset=pid +RemoveIPC=yes +RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX +# loopback only: Caddy is its sole client; it never needs the internet +IPAddressDeny=any +IPAddressAllow=localhost +CapabilityBoundingSet= +UMask=0027 +# SQLite opens the database read-only (mode=ro) but WAL readers need the -shm file +ReadWritePaths=/var/lib/chainwatch + +[Install] +WantedBy=multi-user.target diff --git a/deploy/oracle/install.sh b/deploy/oracle/install.sh new file mode 100755 index 0000000..043326d --- /dev/null +++ b/deploy/oracle/install.sh @@ -0,0 +1,171 @@ +#!/usr/bin/env bash +# Install / upgrade the ALWAYS-ON ChainWatch live collector on a fresh Ubuntu 24.04 VM +# (Oracle Cloud Always Free: VM.Standard.A1.Flex ARM64 or VM.Standard.E2.1.Micro x86-64). +# See docs/LIVE_CLOUD.md. Idempotent: re-run it to upgrade to a newer ref. +# +# sudo CHAINWATCH_HOST=203-0-113-7.sslip.io bash install.sh +# +# Environment: +# CHAINWATCH_HOST public hostname for HTTPS (required unless SKIP_CADDY=1) +# REPO_URL, REF source to install (default: the public repository, branch main); a +# branch or a tag (git clone --branch), e.g. REF=main after a merge +# EXPECTED_SHA abort, before anything changes, unless the fetched commit is exactly +# this full SHA (strongly recommended) +# DRY_RUN=1 print the commands instead of running them +# SKIP_SYSTEMD=1 do not install/enable systemd units (container tests) +# SKIP_CADDY=1 do not install/configure Caddy (container tests) +# +# It never creates cloud resources, never prints the token after first creation, and never +# opens any port except 80/443 (Caddy) in the host firewall. +set -euo pipefail + +REPO_URL="${REPO_URL:-https://github.com/Apostal322/ChainWatch.git}" +REF="${REF:-main}" +DRY_RUN="${DRY_RUN:-0}" +SKIP_SYSTEMD="${SKIP_SYSTEMD:-0}" +SKIP_CADDY="${SKIP_CADDY:-0}" +PREFIX=/opt/chainwatch +APP="$PREFIX/app" +VENV="$PREFIX/venv" +DATA=/var/lib/chainwatch +BACKUPS=/var/backups/chainwatch +ETC=/etc/chainwatch + +run() { echo "+ $*"; if [ "$DRY_RUN" != "1" ]; then "$@"; fi; } +note() { echo "== $*"; } +# the commit must be verified before it replaces anything on disk +verify() { + if [ -n "${EXPECTED_SHA:-}" ] && [ "$1" != "$EXPECTED_SHA" ]; then + echo "fetched $1, expected $EXPECTED_SHA; aborting (nothing was changed)" >&2 + exit 1 + fi + [ -z "${EXPECTED_SHA:-}" ] || echo " verified commit $1" +} +# what this process is executing: bash keeps running the old text when an upgrade replaces +# the file, so after the checkout the new installer is re-executed (see "source" below) +SELF_SHA="" +if [ -f "$0" ]; then SELF_SHA=$(sha256sum "$0" | cut -d' ' -f1); fi + +[ "$(id -u)" = "0" ] || { echo "run as root (sudo)" >&2; exit 1; } +if [ "$SKIP_CADDY" != "1" ]; then + [ -n "${CHAINWATCH_HOST:-}" ] || { echo "set CHAINWATCH_HOST (e.g. .sslip.io)" >&2; exit 1; } + # a bare hostname only: no scheme, port, path, spaces or Caddyfile syntax + [[ "$CHAINWATCH_HOST" =~ ^[A-Za-z0-9]([A-Za-z0-9.-]{0,251}[A-Za-z0-9])?$ ]] \ + || { echo "CHAINWATCH_HOST must be a bare hostname, got: $CHAINWATCH_HOST" >&2; exit 1; } +fi +[[ "$REF" =~ ^[A-Za-z0-9][A-Za-z0-9._/-]*$ ]] || { echo "invalid REF: $REF" >&2; exit 1; } + +note "packages" +export DEBIAN_FRONTEND=noninteractive +run apt-get update -q +run apt-get install -y -q --no-install-recommends python3 python3-venv git sqlite3 openssl ca-certificates curl +[ "$SKIP_CADDY" = "1" ] || run apt-get install -y -q caddy + +note "service user and directories" +if ! id chainwatch >/dev/null 2>&1; then + run useradd --system --home-dir "$PREFIX" --no-create-home --shell /usr/sbin/nologin chainwatch +fi +run install -d -m 0755 -o root -g root "$PREFIX" +run install -d -m 0750 -o chainwatch -g chainwatch "$DATA" "$BACKUPS" +run install -d -m 0750 -o root -g chainwatch "$ETC" + +note "source ($REPO_URL @ $REF), owned by root and read-only to the service" +if [ "$DRY_RUN" = "1" ]; then + run git clone -q --depth 1 --branch "$REF" "$REPO_URL" "$APP" +elif [ -d "$APP/.git" ]; then + run git -C "$APP" fetch --depth 1 origin "$REF" + verify "$(git -C "$APP" rev-parse 'FETCH_HEAD^{commit}')" + run git -C "$APP" checkout -q --force FETCH_HEAD +else + staging=$(mktemp -d "$PREFIX/.app-new.XXXXXX") + trap 'rm -rf "$staging"' EXIT # an unverified tree is never left behind + run git clone -q --depth 1 --branch "$REF" "$REPO_URL" "$staging" + verify "$(git -C "$staging" rev-parse HEAD)" + run chmod 0755 "$staging" + run mv "$staging" "$APP" + trap - EXIT +fi +new_installer="$APP/deploy/oracle/install.sh" +if [ "$DRY_RUN" != "1" ] && [ -z "${CHAINWATCH_INSTALL_REEXEC:-}" ] && [ -f "$new_installer" ] \ + && [ "$(sha256sum "$new_installer" | cut -d' ' -f1)" != "$SELF_SHA" ]; then + note "re-running the installer of the new version" + CHAINWATCH_INSTALL_REEXEC=1 exec bash "$new_installer" +fi + +note "virtualenv from the hash-locked live dependency set (no ML stack)" +[ -x "$VENV/bin/python" ] || run python3 -m venv "$VENV" +run "$VENV/bin/pip" install -q --upgrade --require-hashes -r "$APP/requirements/live.lock.txt" +run "$VENV/bin/pip" install -q --no-deps --no-build-isolation -e "$APP" + +note "secret: edge API token (generated here, never committed)" +if [ ! -s "$ETC/live.env" ]; then + if [ "$DRY_RUN" != "1" ]; then + token=$(openssl rand -hex 32) || { echo "openssl rand failed" >&2; exit 1; } + [ "${#token}" -eq 64 ] || { echo "generated token has the wrong length" >&2; exit 1; } + (umask 077 && printf 'CHAINWATCH_LIVE_TOKEN=%s\n' "$token" > "$ETC/live.env") + unset token + chown root:root "$ETC/live.env" + chmod 0600 "$ETC/live.env" # systemd reads it as root; the service user cannot + echo " created $ETC/live.env. Read it ONCE with: sudo cat $ETC/live.env" + echo " and store the value as the Render secret CHAINWATCH_LIVE_TOKEN." + else + echo "+ (write $ETC/live.env with a random 64-hex token, mode 0600 root:root)" + fi +else + echo " $ETC/live.env exists; keeping the current token" + run chown root:root "$ETC/live.env" # upgrade from v0.6.0-rc (0640 root:chainwatch) + run chmod 0600 "$ETC/live.env" +fi + +note "journald size cap" +run install -d -m 0755 /etc/systemd/journald.conf.d +if [ "$DRY_RUN" != "1" ]; then + printf '[Journal]\nSystemMaxUse=200M\n' > /etc/systemd/journald.conf.d/chainwatch.conf +fi + +if [ "$SKIP_SYSTEMD" != "1" ]; then + note "systemd units (restart on crash, start on boot)" + for unit in chainwatch-collector.service chainwatch-live-api.service \ + chainwatch-backup.service chainwatch-backup.timer \ + chainwatch-indicators.service chainwatch-indicators.timer; do + run install -m 0644 "$APP/deploy/oracle/$unit" "/etc/systemd/system/$unit" + done + run systemctl daemon-reload + run systemctl restart systemd-journald + run systemctl enable --now chainwatch-collector.service chainwatch-live-api.service \ + chainwatch-backup.timer chainwatch-indicators.timer + run systemctl restart chainwatch-collector.service chainwatch-live-api.service +fi + +if [ "$SKIP_CADDY" != "1" ]; then + note "Caddy: HTTPS for $CHAINWATCH_HOST -> 127.0.0.1:8100" + if [ "$DRY_RUN" != "1" ]; then + # render to a temporary file and validate before replacing the live Caddyfile + tmp=$(mktemp /etc/caddy/Caddyfile.XXXXXX) + sed "s/__CHAINWATCH_HOST__/$CHAINWATCH_HOST/" "$APP/deploy/oracle/Caddyfile.template" > "$tmp" + if ! caddy validate --config "$tmp" --adapter caddyfile >/dev/null; then + rm -f "$tmp"; echo "rendered Caddyfile is invalid; the current one is unchanged" >&2; exit 1 + fi + chmod 0644 "$tmp" && mv "$tmp" /etc/caddy/Caddyfile + fi + run systemctl enable --now caddy + run systemctl reload caddy + + note "host firewall: Oracle's Ubuntu images REJECT everything but SSH in iptables" + if [ -f /etc/iptables/rules.v4 ] && command -v iptables >/dev/null; then + for port in 80 443; do + if ! iptables -C INPUT -p tcp --dport "$port" -m state --state NEW -j ACCEPT 2>/dev/null; then + # before Oracle's catch-all REJECT rule (its position varies), else at the end + pos=$(iptables -L INPUT --line-numbers -n | awk '$2 == "REJECT" {print $1; exit}') + run iptables -I INPUT "${pos:-$(( $(iptables -L INPUT --line-numbers -n | tail -n +3 | wc -l) + 1 ))}" \ + -p tcp --dport "$port" -m state --state NEW -j ACCEPT + fi + done + command -v netfilter-persistent >/dev/null && run netfilter-persistent save + fi +fi + +note "done. Verify:" +echo " systemctl status chainwatch-collector chainwatch-live-api --no-pager" +echo " sudo -u chainwatch $VENV/bin/chainwatch-live --config $APP/configs/live-cloud.yaml report --hours 1" +[ "$SKIP_CADDY" = "1" ] || echo " TOKEN=... $APP/deploy/oracle/smoke_live.sh https://$CHAINWATCH_HOST" diff --git a/deploy/oracle/live.env.example b/deploy/oracle/live.env.example new file mode 100644 index 0000000..c6b4634 --- /dev/null +++ b/deploy/oracle/live.env.example @@ -0,0 +1,4 @@ +# /etc/chainwatch/live.env on the collector VM (mode 0600, root:root: systemd reads it before +# dropping privileges, so the service user cannot). +# install.sh generates it; this example is the only copy in Git and holds no secret. +CHAINWATCH_LIVE_TOKEN=<64 hex characters from `openssl rand -hex 32`> diff --git a/deploy/oracle/smoke_live.sh b/deploy/oracle/smoke_live.sh new file mode 100755 index 0000000..009d098 --- /dev/null +++ b/deploy/oracle/smoke_live.sh @@ -0,0 +1,53 @@ +#!/usr/bin/env bash +# Deployment smoke test of the collector's edge API (run from anywhere, after install.sh). +# +# TOKEN= deploy/oracle/smoke_live.sh https://203-0-113-7.sslip.io +# +# Checks: health, auth enforcement (401 without / with a wrong token), status with the +# token, that the source is the public mempool.space service (unless ALLOW_MOCK=1), that the +# collector is connected and has observed a transaction recently (MAX_AGE_S, default 900), +# bounded list responses, and that the database is not downloadable. Exit 0 = PASS. +set -euo pipefail +BASE="${1:?usage: TOKEN=... smoke_live.sh }" +BASE="${BASE%/}" +TOKEN="${TOKEN:?set TOKEN to the edge API token}" +MAX_AGE_S="${MAX_AGE_S:-900}" +fail() { echo "FAIL: $*" >&2; exit 1; } +ok() { echo "ok $*"; } +code() { curl -s -o /dev/null -w '%{http_code}' --max-time 15 "$@"; } + +[ "$(code "$BASE/health/live")" = "200" ] || fail "/health/live" +ok "health/live" +[ "$(code "$BASE/v1/live/status")" = "401" ] || fail "status without token must be 401" +[ "$(code -H "authorization: Bearer wrong-token-0000000000000000000000000000" "$BASE/v1/live/status")" = "401" ] \ + || fail "status with a wrong token must be 401" +ok "auth enforced (401 without / with wrong token)" + +status=$(curl -sf --max-time 15 -H "authorization: Bearer $TOKEN" "$BASE/v1/live/status") || fail "status with token" +ALLOW_MOCK="${ALLOW_MOCK:-0}" MAX_AGE_S="$MAX_AGE_S" python3 -c ' +import json, os, sys, time +s = json.loads(sys.argv[1]) +assert s["mode"] == "live", s.get("mode") +if os.environ["ALLOW_MOCK"] != "1": + assert s["source_is_public_mempool"], f"source is {s['"'"'source_url'"'"']}, not mempool.space" +assert s["connection"] == "connected", f"collector connection: {s['"'"'connection'"'"']}" +last = s.get("last_observation_at") +age = time.time() - last if last else None +assert age is not None and age < float(os.environ["MAX_AGE_S"]), f"last observation age {age}" +a = s.get("availability_24h") or {} +print(f"ok status: connected, source {s['"'"'source_url'"'"']}, last observation {age:.0f}s ago, " + f"observed share (24 h) {a.get('"'"'observed_share'"'"')}") +' "$status" + +curl -sf --max-time 15 -H "authorization: Bearer $TOKEN" "$BASE/v1/live/transactions?limit=5" | python3 -c ' +import json, sys +d = json.load(sys.stdin) +assert d["rows"] and len(d["rows"]) <= 5, "expected 1..5 rows" +print("ok transactions:", d["total"], "stored; newest", d["rows"][0]["txid"][:16], "...")' +[ "$(code -H "authorization: Bearer $TOKEN" "$BASE/v1/live/transactions?limit=1000")" = "422" ] || fail "limit cap" +ok "request bounds enforced (limit > 200 rejected)" +for p in /live.sqlite /var/lib/chainwatch/live.sqlite /docs /openapi.json; do + [ "$(code "$BASE$p")" = "404" ] || fail "$p must not be served" +done +ok "database, docs and schema are not exposed" +echo "PASS $BASE" diff --git a/docker-compose.yml b/docker-compose.yml index 0d9da1c..425a725 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -21,6 +21,6 @@ services: volumes: - ./data/processed:/app/data/processed:ro - ./artifacts/registry:/app/artifacts/registry:ro - ports: ["8000:8000"] + ports: ["127.0.0.1:8000:8000"] # real-data registry: this machine only read_only: true tmpfs: ["/tmp"] diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index a09282b..1d21c49 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -5,6 +5,32 @@ one container. Research code (Phases 1–2) and serving code (Phase 3) share the loading, feature and training functions, and the service is tested to reproduce the research predictions exactly. +## System boundaries + +Four parts share one package but never share data: + +| Part | Runs where | Data | Models | Entry point | +|---|---|---|---|---| +| Historical ML research (Phases 1–2) | your machine | Elliptic++ CSVs you download (never committed) | trained here; results committed as aggregates in `reports/` | `chainwatch prepare / train / backtest` | +| Synthetic demonstration (Phase 3) | Render (public), Docker | generated synthetic data baked into the image | trained on that synthetic data at image build | `chainwatch serve` with `public-demo.yaml` | +| Local live monitoring (Phase 5) | your machine | real mempool.space observations in a local SQLite file | **none**: rule-based indicators and the risk engine (address screening against sourced lists, observed-graph relations, statistical anomalies; the supervised layer abstains) | `chainwatch live-collect` + `serve` with `live.yaml` | +| Persistent cloud monitoring (v0.6.0, prepared) | a small VM (Oracle Always Free target) | the same, designed to be collected continuously (not deployed) | **none**; the VM has no ML packages (the risk engine is pure Python) | `chainwatch-live collect / serve-edge` (systemd) | + +* The Elliptic++ models are never applied to live transactions: their anonymised features + cannot be computed for new transactions. +* Live rows never enter the synthetic replay. The two modes have separate routes + (`/v1/replay/*` vs `/v1/live/*`), storage and dashboard tabs, and every live response + says where its data came from. +* In remote mode the public dashboard proxies `/v1/live/*` to the VM's edge API server to + server. It never opens the database or contacts mempool.space, and the browser never + sees the token. See [LIVE_CLOUD.md](LIVE_CLOUD.md) for the deployment and + [LIVE_MONITOR.md](LIVE_MONITOR.md) for the pipeline. + +Why SQLite for live data: one writer (the collector) and a few readers on one machine; +WAL gives concurrent reads; the whole store is one file to back up; retention keeps it +bounded at about 60 MB. A second collector, or readers on other machines, would need a +server database. That is outside the current scope and documented as a scaling limit. + ## Components ```mermaid diff --git a/docs/AUDIT.md b/docs/AUDIT.md index 5379bc3..f4475ba 100644 --- a/docs/AUDIT.md +++ b/docs/AUDIT.md @@ -1,3 +1,256 @@ +# Engineering audits + +* [v0.8.1 independent audit](#v081-independent-audit) (2026-10-23): seven parallel adversarial reviews (collector, persistence, screening, HTTP surface, dashboard in a browser, anomaly/ML, supply chain and deploy kit) of v0.8.0 (`d8fcb94`), then a second review of the fixes. +* [v0.8.0 independent hardening audit](#v080-independent-hardening-audit) (2026-10): all components, re-audited by independent reviewers; adversarial cases reproduced before fixing. +* [v0.7.0 risk intelligence audit](#v070-risk-intelligence-audit) (2026-10): screening, indicator parsing, anomaly detector, engine, alerts, dashboard. +* [v0.6.0 audit](#v060-engineering-audit-live-monitor-cloud-kit-research-claims) (2026-10): live collector, edge API and remote proxy, deployment kit, dashboard, research claims. +* [Phase 4 audit](#phase-4-engineering-audit-release-readiness): serving layer and release. + +## v0.8.1 independent audit + +Baseline `d8fcb94` (v0.8.0): 473 Python and 51 frontend tests passed, CI 8/8. Seven +independent reviewers worked on read-only copies with deterministic repros. Severity as +above (P1 = misleading risk or data state, data loss, or anonymous low-effort DoS in plausible +operation). Every code fix has a regression test that **fails on `d8fcb94`** and passes now. + +| # | Sev | Component | Problem (root cause) | Fix | Test | Commit | +|---|---|---|---|---|---|---| +| W1 | P1 | supply chain | After v0.8.0 was validated, new advisories turned the audit gate red: certifi < 2026.10.18 trusts a CA with compromised intermediates (all locks; the collector's and proxy's HTTPS), pillow 12.3.0 (~40 advisories, serving image), vitest (dev) | certifi 2026.10.19, pillow 13.0.0, vitest 4.1.12; only these packages changed | pip-audit and npm audit: 0 | `1b12c2f` | +| W2 | P1 | retro screening | Re-run at every collector start for each source's latest version, it matched listings closed since (e.g. a mirror row the official file superseded): a P1 "now listed" alert for a correctly unmatched transaction | only listings in force | `test_retro_screening_ignores_listings_closed_since` | `bf8b7f8` | +| W3 | P1 | restore (was accepted as LOW) | Restore renamed the live files while other processes could open the database: a collector restarted by systemd (state still `stopped`) or a timer-run indicator refresh wrote to the renamed files or paired its fresh WAL with the restored file; a restore that reported OK lost its data | shared flock held by every writer; restore needs it exclusively and copies through the backup API (no renames); a writer starting meanwhile exits 75 | `test_restore_is_refused_while_any_writer_has_the_database_open`, `test_no_writer_can_open_the_database_during_a_restore`; systemd §6 | `bd7b900` | +| W4 | P1 | dashboard | The synthetic demo stated the research-dataset disclaimer, contradicting its SYNTHETIC banner | synthetic disclaimer from the API | `test_the_synthetic_demo_does_not_claim_the_research_dataset` | `b6acd8f` | +| W5 | P1 | dashboard | Replay kept the previous step's rows (and a mixed "Model used" tile) under the new step's caption after a failed request | cleared on change and error; announced | browser repro | `b6acd8f` | +| W6 | P2 | ingest | Superseding the mirror's extra rows counted towards the official file's mass-removal limit: one such mirror blocked every later official refresh | own rows only (first official snapshot against the copy) | `test_official_refresh_is_not_blocked_by_a_mirrors_extra_rows` | `bf8b7f8` | +| W7 | P2 | ingest | A mirror row closed by the official file left no trace; the same stale mirror content re-listed it | `indicators.closed_by`; veto | `test_a_stale_mirror_cannot_relist_what_the_official_file_superseded` | `bf8b7f8` | +| W8 | P2 | ingest | Older official content (stale CDN, old file) was a new version: re-listed delisted, delisted new | refused unless `--allow-older` | `test_older_official_content_is_refused` | `bf8b7f8` | +| W9 | P2 | collector | A retry waiting in the queue or for a token (the 30 s pause after a 5xx exceeds the retry delay) was lost on shutdown without a row | interrupted and queued retries recorded | `test_a_retry_waiting_in_the_queue_is_recorded_on_shutdown` | `b4e9236` | +| W10 | P2 | collector | `add_failed` in the failure path: a writer lock longer than the busy timeout killed the worker | contained (`db_errors`) | `test_a_locked_database_in_the_failure_path_is_not_fatal` | `b4e9236` | +| W11 | P2 | collector | mempool repeats its sequence during a whole out-of-sync stretch; skipped arrivals left no trace and availability looked complete | stretch recorded as a `sequence_gap` with duration | `test_resync_stretches_are_recorded_as_coverage_gaps` | `b4e9236` | +| W12 | P2 | persistence | The pre-restore copy lacked un-checkpointed WAL data | backup-API copy | `test_restore_keeps_uncheckpointed_data_in_the_pre_restore_copy` | `bd7b900` | +| W13 | P2 | persistence | A failed assessment looked like "risk off" and its addresses were rolled back (never re-screened) | addresses in their own savepoint; all-ERROR "Assessment failed" record; `risk_state` | `test_failed_risk_write_keeps_the_observation_and_leaves_a_failed_record` | `bd7b900` | +| W14 | P2 | persistence | Dismissed alerts with notes were deleted after 90 days; the next occurrence re-notified | only untouched `new` alerts expire | `test_alerts_a_person_acted_on_are_not_pruned` | `bd7b900` | +| W15 | P2 | anomaly | "strong" counted vsize and the count that determines it: ~1.2 priority-3 alert groups per hour of realistic noise | robust-tail/3 evidence groups | `test_correlated_size_measurements_do_not_make_noise_strong` | `42fbe1b` | +| W16 | P2 | deploy | `install.sh` checked out before verifying `EXPECTED_SHA`; upgrades ran the old installer (bash executes the old text) | verify first, staging clone, re-exec the new installer | systemd §8 | `4d8a5e5` | +| W17 | P2 | CI | The suite never ran on the deployed versions (dev lock resolves newer web stack) | `deployed locks / py3.12` job | CI | `4d8a5e5` | +| W18 | P2 | dashboard | Feed showed "no finding" for rows whose screening never ran; graph "no parents" when skipped; green "no match" from a stale source; green "Connected" with nothing ever fetched; tab switches into 429s | `risk_state` markers, wording and tones, live view kept mounted | vitest | `bd7b900`, `b6acd8f` | +| W19 | P2 | docs | The rollback runbook claimed an older collector can open a v0.8 database (false: duplicate alerts, lost dismissals); install examples named tags that do not exist; a too-low proxy hop count was called "safe" (it is an anonymous DoS) | corrected; restore-based rollback; hop verification procedure | — | this release | +| W20 | P3 | collector | Pongs satisfied the stale watchdog; duplicate announcement of a txid with a pending retry; expired retry counted twice; vin sequence not validated (bool/negative switched on rbf_signal); fee unbounded with missing prevouts | fixed | `tests/test_live_collector_audit.py` | `b4e9236` | +| W21 | P3 | persistence | Backups: a failed check left the final file (counted by rotation), `.partial` never cleaned, rotation deleted operator files, no checksum; corrupted database opened silently; orphans when every row aged out; anomaly window updated before commit | fixed; exit 78 on a failed `quick_check` | `test_backup_rotation_counts_only_verified_copies`, `test_collector_refuses_a_corrupted_database_without_a_restart_loop`, `test_orphans_are_removed_when_every_transaction_aged_out` | `bd7b900` | +| W22 | P3 | API | ids above SQLite's INTEGER range: 500 + traceback; edge 422 echoed input; no `no-store` on `/v1`; Caddy forwarded HEAD (405) | fixed | `test_edge_validation_errors_use_the_envelope_and_huge_ids_are_422`, `test_api_answers_are_not_cached` | `4038332` | +| W23 | P3 | CLI / release | A refused official snapshot with a working fallback exited 0; version tag pushed on any inspect failure; template expression in `run:`; entrypoint not shellchecked; Dependabot could bump the ML stack | exit 3; explicit "manifest unknown"; env; shellcheck; ignores | `test_a_refused_official_snapshot_fails_the_refresh_even_if_the_mirror_works` | `bf8b7f8`, `4d8a5e5` | +| W24 | P3 | anomaly / dashboard | Two-sided explanation used the doubled p; replay rows not buttons; tab not in the URL; empty replay page; legend contrast; panel errors not announced | fixed | `test_two_sided_explanation_states_the_actual_share`, vitest | `42fbe1b`, `b6acd8f` | +| W25 | P2 | second review | Found in the independent second review of the fixes above: rows closed before the upgrade had no `closed_by` (W7's veto missed them); rows screened by no list after the baseline showed `no_finding`; a damaged schema page raised before `quick_check` ran (restart loop, not exit 78); resync stretches counted as observed time; the skip link reset the dashboard tab; a replay selection survived a ranking change; backup removed a concurrent run's `.partial`; the installer left its staging clone on failure | backfill from `indicator_versions`; `screening_unavailable`; read-only `quick_check` before opening; gaps with duration subtracted; only tab slugs switch views; selection keyed to the ranking; only partials older than 1 h; `trap` cleanup | `test_closures_from_before_the_upgrade_still_block_a_stale_mirror`, `test_rows_screened_by_nothing_are_never_no_finding_after_the_baseline`, `test_collector_refuses_a_database_with_a_damaged_schema_page`, `test_resync_stretches_count_as_unobserved_time`, `test_backup_rotation_counts_only_verified_copies` (all fail on `62b42ad`); vitest | `dba5a82` | + +Verified correct by the reviewers (not changed): every research number spot-checked +reproduces exactly (feature-subset report re-run: identical 120 values; dataset hashes +match); no fit on validation or test data; the supervised gate abstains for every malformed +card; the publish gate rejects fork PRs, fork branches named `main`, tag pushes and +non-`main` dispatches; the token is compared in constant time and never logged; security +headers on every status of both apps; ARM64 wheels exist for every VM package; no secrets +or datasets in Git history. + +### Follow-up: paged risk lists + +| # | Sev | Component | Problem | Fix | Test | Commit | +|---|---|---|---|---|---|---| +| X1 | P2 | dashboard / API | Only the 50 newest findings and the first 200 alerts reached the UI; no type, retrospective, source, priority or time filter; "open" filtered in the browser over a truncated list | server-side filters and keyset pagination with totals from one read snapshot; covering indexes; remote proxy validates and refuses filters an older edge would ignore; pager and filters in the UI (keyboard, 375 px) | `tests/test_risk_pages.py` (54), vitest "paged risk lists", e2e 5 checks; benchmark in RISK_ENGINE.md §9 | `a26b60d` | + +### Accepted or open after v0.8.1 + +* **External:** Render's real `X-Forwarded-For` hop count (procedure in DEPLOYMENT.md; + a wrong value is P1 on the public demo), real mempool.space traffic (the egress proxy + here refuses it: HTTP 403, 0 txids), the Oracle VM, a 24-hour run. +* **Closed after v0.8.1 review (was open, P2, dashboard):** the alert queue and findings + list showed at most 200 / 50 items with no layer or retrospective filter. Now filtered + and paged on the server (row X1 above). +* **Open, P3:** a copy-txid control; the tab bar at 360 px scrolls without a cue; one + 649 kB JS bundle; uvicorn `limit_concurrency` counts idle keep-alives (safe behind Caddy, + never expose uvicorn directly); the first frame of a connection cannot be recognised as + a re-sync; a percentage mass-removal guard can be worn down over several days; graph + worst case ~0.2-0.4 s for a transaction with 200 parents × 500 inputs (estimated). +* **Accepted:** an address re-designated while the official fetch keeps failing is missed + until the official file lists it (the official source shows as stale meanwhile). + +## v0.8.0 independent hardening audit + +Baseline: `f9f8765` (v0.7.0). Independent reviewers audited the collector, risk engine, +API and proxy, deployment kit, dashboard and research claims. Each code defect was +reproduced first: **every new regression test fails on `f9f8765` and passes after the fix** +(checked by running the tests against a worktree of the baseline). Severity: P1 = wrong +results, data loss or availability loss reachable in normal operation or by an anonymous +visitor; P2 = wrong results under plausible faults; P3 = misleading output or robustness. +None of these problems was deployed: the risk layers had never run on the public network. + +### Code and deployment + +| # | Sev | Component | Problem (root cause) | Fix | Test / evidence | Commit | +|---|---|---|---|---|---|---| +| V1 | P1 | config | `retention_rows: 0` was accepted and `prune()` deleted every stored row; `heartbeat_s: 0` spun the heartbeat loop (no range validation) | `LiveConfig.__post_init__` validates every count, duration and URL scheme; invalid config exits 78 | `test_live_config_rejects_unsafe_values`; systemd §12 (exit 78, no restart loop) | `dc8d428` | +| V2 | P1 | indicator refresh | An empty or truncated snapshot (error page, schema change) silently delisted every address | an empty snapshot, or one that would delist more than max(5, 25 % of the active listings), is refused (`SnapshotRejected`) unless `--allow-mass-removal`; truncated XML falls back | `test_empty_or_mass_delisting_snapshot_is_refused`, `test_truncated_official_xml_falls_back_and_file_inputs_never_do` | `a2d0802` | +| V3 | P1 | indicator versions | `UNIQUE(source, sha256)` made a snapshot that reverts to earlier content "unchanged", so a re-listed address stayed delisted | diff against active listings; uniqueness dropped by an id-preserving migration | `test_content_reverting_to_an_earlier_version_relists_it` | `a2d0802` | +| V4 | P1 | screening | The official SDN file and its mirror were independent sources: an address delisted officially stayed listed through the mirror | one authority (`ofac-sdn`, official rank 0); an official snapshot closes the mirror's extra listings; one match per authority. The first version let the mirror close official listings too (see V28) | `test_official_list_and_its_mirror_are_one_list` | `a2d0802` | +| V5 | P1 | retro screening | Transactions assessed while a new snapshot was loading were missed by both the live path and the retrospective pass | retro covers every stored transaction whose own record lacks the match; the collector runs it on reload, in a transaction | `test_retro_screening_covers_the_reload_window_and_is_idempotent`, `test_collector_retro_screens_when_it_loads_a_new_snapshot` | `a2d0802` | +| V6 | P1 | collector | A trickling REST body held a fetch worker forever while health said connected (per-read timeout only) | overall `asyncio.timeout` deadline and a 16 MB body cap | `test_rest_read_has_an_overall_deadline` | `a2d0802` | +| V7 | P1 | proxy | An anonymous visitor cycling query parameters missed the cache each time, drained the shared upstream budget and turned the dashboard's own polling into 502s | fixed polling queries bypass the budget; `hours`/`window` snapped; 60 s last-good fallback; edge caches risk summary 15 s | `test_anonymous_parameter_cycling_cannot_starve_the_dashboards_own_polling`, `test_last_good_answer_is_served_when_the_edge_fails` | `064612f` | +| V8 | P2 | XML parser | UTF-16 input could hide a DOCTYPE from the byte scan; one party with 1 M features peaked at 749 MB | UTF-8 only; every finished top-level record freed; features dropped as they end; 10,000 addresses per party → 21 MB | `test_utf16_and_bom_inputs`; 1 M-feature stress run | `a2d0802` | +| V9 | P2 | indicator fetch | https was checked only on the first URL, not on redirect hops | checked on every hop | `test_fetch_refuses_a_redirect_through_plain_http` | `a2d0802` | +| V10 | P2 | graph relations | Parents' inputs were screened at the parent's time, duplicates per address, and coverage overstated | re-screened at the child's time; deduplicated per (parent, address, authority), capped at 20; `parents_checked` reported | `test_graph_relations_screen_parents_at_the_childs_time` | `a2d0802` | +| V11 | P2 | alerts | Upserts deduplicated only over the 50 displayed txids; keys ignored authority and role | `alert_txids` table; keys `screening:{authority}:{role}:{address}` | `test_alert_group_includes_the_role`, `test_alert_upserts_are_idempotent_beyond_the_displayed_txids` (added after the second review) | `a2d0802` | +| V12 | P2 | anomaly | One flag outside a small window was always "strong"; the two-sided fee test could not reach alpha | `robust-tail/2`: strong needs ≥ 2 flags; `min_reference` 1,000; reachability validated two-sided | `test_strong_means_several_measurements_not_a_small_window` | `a2d0802` | +| V13 | P2 | collector lifecycle | `replaced` could override `mined`; txids leaving the mempool during a token wait or an in-flight GET were forgotten; block conflicts were fetched | mined is final; `LifecycleMemo` applied at store time; gone txids not fetched | `test_mined_overrides_replaced`, `test_lifecycle_event_during_fetch_is_not_lost`, `test_gone_is_rechecked_after_waiting_for_a_token`, `test_block_conflicts_are_not_fetched` | `a2d0802` | +| V14 | P2 | collector protocol | A repeated `mempoolSequence` (mempool.space re-sync; checked in its `websocket-handler.ts`) re-announced the whole mempool as new | repeated sequence = re-sync: added txids skipped and counted | `test_live.py` backpressure test (resync counters) | `a2d0802` | +| V15 | P2 | collector | A DB error on lifecycle/gap writes dropped the frame's new txids and tore down the socket; a disk-full auto-rollback went undetected; counters were incremented before commit | `sqlite3.Error` contained per write; `_tx` checks `in_transaction`; counters after commit | `test_db_error_in_frame_does_not_drop_new_txids_or_the_connection`, `test_disk_full_in_the_risk_write_does_not_count_a_phantom_fetch` | `a2d0802` | +| V16 | P2 | migrations | Two processes starting together raced on `ALTER TABLE` ("duplicate column name") | one `BEGIN IMMEDIATE` migration | `test_concurrent_migrations_do_not_collide` (deterministic interleaving) | `a2d0802` | +| V16b | P3 | reader | `LiveReader.get` read the row and its risk record in separate snapshots, so a concurrent prune could return a half-deleted transaction | one read transaction | `test_reader_get_survives_a_concurrent_prune` | `a2d0802` | +| V17 | P2 | proxy | A dripping edge held callers past the timeout; an exception stranded single-flight waiters | overall deadline; any exception becomes a clean 502 and releases waiters | `test_upstream_has_an_overall_deadline_and_errors_never_strand_waiters` | `064612f` | +| V18 | P2 | SSE | A client that never reads held its slot past the stream deadline | hard `move_on_after` deadline | `test_a_client_that_never_reads_cannot_hold_a_stream_slot` | `064612f` | +| V19 | P2 | deploy | Slow-header clients could hold the 32 uvicorn slots; non-GET reached the edge | Caddy read/idle timeouts; `GET`/`HEAD` only | systemd §9 (`caddy validate`) | `064612f` | +| V20 | P2 | token | A whitespace-padded token passed the length check; rotation needed downtime | token regex, exit 78; `CHAINWATCH_LIVE_TOKEN_NEXT` | `test_token_rotation_and_token_format`; systemd §13–14 | `064612f` | +| V21 | P2 | features, protocol | Output sum, fee = in − out and weight/size were not validated; a sequence of 2**63 raised `OverflowError` in the heartbeat task (fatal exit, restart loop) | validated; invalid input rejected; sequence outside 0 ≤ s < 2**53 ignored | `test_sum_of_outputs_above_max_money_is_malformed`, `test_fee_must_equal_inputs_minus_outputs_when_all_prevouts_are_known`, `test_huge_sequence_does_not_break_the_heartbeat` | `a2d0802` | +| V22 | P3 | status | `/v1/live/status` could echo `user:password@` from URLs and error texts | redacted | `test_status_never_shows_credentials_from_a_source_url` | `064612f` | +| V23 | P3 | install.sh | A failed token generation wrote an empty token; umask leaked to later steps; the firewall rule could land after Oracle's REJECT | checked, scoped umask, inserted before REJECT | shellcheck job; systemd §1 | `064612f` | +| V24 | P3 | supervised gate | Malformed model-card evidence raised instead of abstaining | types checked; never raises | `test_supervised_gate_rejects_empty_or_malformed_evidence` | `a2d0802` | +| V25 | P3 | performance | `risk_summary` scanned the risk table (0.48 s cold at the cap) | covering indexes, one pass: 0.10 s cold, 2 ms cached | 50k-row bench | `53f6f65` | +| V26 | P3 | CI | No job timeouts (6 h default), PR checks ran twice, no shell lint | timeouts, concurrency, shellcheck | CI | `dc8d428` | +| V28 | P1 | screening (second review, regression from V4) | Supersession ran both ways: when the official fetch failed, a mirror a day behind delisted the newest official designations (up to the mass-removal threshold, ~25 % per run) and re-listed addresses OFAC had just delisted | ranked supersession: a lower-ranked copy never closes a higher-ranked listing and never re-lists what it delisted (`skipped_delisted`); the official file is never "superseded" by its mirror, so a failing official refresh shows its real age | `test_a_lagging_mirror_never_delists_or_relists_official_listings` | this release | +| V29 | P2 | alerts (second review) | The new group keys had no migration: alerts dismissed in v0.7 came back as `new` on their next occurrence | one-time re-keying from the evidence's role during the v0.8 migration | `test_v07_alert_states_survive_the_new_group_keys` | this release | +| V30 | P3 | collector (second review) | The reload's retrospective pass ran unguarded in the heartbeat (a locked database killed the collector); after a restart the pass was skipped; matches the CLI had alerted on were counted again | guarded (`db_errors`, retried next beat); latest version per source re-screened at start-up; only new matches counted | `test_collector_retro_survives_a_locked_database_and_a_restart` | this release | +| V31 | P3 | collector (second review) | `LifecycleMemo` let `removed` override `replaced` (mempool.space sends both for a block conflict), unlike `mark_lifecycle` | replaced refines removed in both | `test_memo_keeps_replaced_when_removed_follows` | this release | +| V32 | P3 | proxy (second review) | Budget-refused failures shared the LRU with the polling answers, so a flood of distinct keys evicted them; the stream and the feed polled different keys, so the feed could look older than the stream and reset itself; `/status` was served stale for up to 60 s after the edge went down; `make_backend` accepted tokens the edge refuses | refusals not cached; one query for both; `/status` never stale; the edge's token rule | `test_refused_keys_cannot_evict_the_polling_answers_from_the_cache`, `test_event_stream_and_feed_poll_share_one_query`, `test_status_is_never_served_stale`, `test_remote_mode_requires_https_and_a_token` | this release | +| V33 | P3 | soak test | The soak's indicator refreshes replaced the whole TEST list, which the new mass-removal guard (V2) refuses: 4 of 5 refreshes failed in the 90-minute run | realistic updates (keep the list, add up to 1,000, delist a few); 40-minute re-run 17/17 | `docs/LIVE_CLOUD.md` §11 | `4501f4e` | +| V27 | P3 | demo | Generated synthetic data printed a "published hashes" mismatch warning | info message for synthetic data | — | `4cb20c1` | + +### Dashboard (`f1b552d`) + +| # | Sev | Problem | Fix | +|---|---|---|---| +| D1 | P1 | The feed could freeze silently while the badge said Connected (event stream closed, no fallback) | polling fallback, lag notice, txid dedupe, recovery after a restore | +| D2 | P2 | "No alerts" / "No findings" shown when risk or screening data was unavailable; unassessed rows looked clean | explicit unavailable states; `n/a` for unassessed rows | +| D3 | P2 | Anomaly baseline progress used a hardcoded 500 | the server's `min_reference` | +| D4 | P2 | Superseded sources counted as current; no authority, metadata version or graph coverage | labelled and shown | +| D5 | P3 | Accessibility: duplicate toggle names, no skip link or `
` landmark, very long alert lists | fixed; first 20 alerts with "show all" | +| D6 | P3 | Explorer links for mock data; replay label bug; clock skew applied inconsistently; overflow at 390 px; "-dirty" lost | fixed | + +### Research claims (`62bf8bd`) + +No published AP, interval or split changed; an independent reviewer recomputed every +headline number from the raw CSVs and saved predictions, and a scratch retrain reproduced +the live-computable XGBoost run exactly. + +| # | Sev | Problem | Fix | +|---|---|---|---| +| M1 | P2 | The feature-subset "gain share" was XGBoost's mean gain per split over all trees, including 50 after early stopping; the "mostly shape" claim rested on it | share of total gain over the trees prediction uses (`fees` 0.08 → 0.19, `size` 0.26 → 0.46); claim corrected | +| M2 | P3 | Per-step P@20 used `head(20)`, not the tie-aware repository metric | tie-aware (0.5100 → 0.5133) | +| M3 | P3 | Below-chance late ranking (LR ROC-AUC 0.31 / 0.34 on steps 43–49) not reported; "pre-registered" overstated what the commit order proves | reported; amendments section | +| M4 | P3 | A third-party count presented as local data; missingness means not labelled as per-step vs pooled | corrected | + +### Release blockers closed before approval (final v0.8.0 pass, baseline `69ec57d`) + +| # | Sev | Component | Problem (root cause) | Fix | Test / evidence | Commit | +|---|---|---|---|---|---|---| +| B1 | MEDIUM | dashboard, edge | 500 answers had no security headers: Starlette sends them from `ServerErrorMiddleware`, outside every user middleware; the edge had no 500 handler (plain text). 413 and 429 answers already had them (checked) | both 500 handlers set the headers, `cache-control: no-store` and the request id, with a JSON body without internal details | `test_internal_errors_carry_the_security_headers`, `test_edge_internal_errors_are_json_with_security_headers` (fail on `69ec57d`) | `32f5c07` | +| B2 | MEDIUM | collector | A transient detail-fetch failure was final: one 503, timeout or 429 lost the transaction | bounded retries: transient = timeout, network, 429, 5xx, a first 404 (indexing lag); permanent = malformed/oversized payload, other 4xx. At most `fetch_max_attempts` (3; capped at 10), exponential backoff with jitter (2.5–5 s, 5–10 s), never past `max_queue_age_s`, at most `queue_max/2` pending, every attempt through the same token bucket; pending retries recorded on shutdown | 6 tests in `tests/test_live_faults.py` (recovery, cap, permanent, 404 once, age limit, shutdown; fail on `69ec57d`: settings absent); soak check "retries bounded" | `32f5c07`, `6bd4f52` | +| B3 | MEDIUM | CI | `pip install -e ".[dev]"` resolved unpinned versions on every run | `requirements/dev.lock.txt`: hash-locked, universal (3.11–3.13; Linux, macOS, Windows), build backend included; CI installs it with `--require-hashes` and the package with `--no-deps --no-build-isolation` | `test_ci_installs_only_hash_locked_dependencies`; CI green on Linux and Windows | `32f5c07` | +| B4 | MEDIUM | supply chain | No dependency update automation, no vulnerability audit | Dependabot (pip, npm, GitHub Actions, Docker base images; PRs only); CI `dependency audit` job: pip-audit on the dev, serve and live locks (from its own hash lock), `npm audit --audit-level=high`; the Docker job needs it | first run: no known vulnerabilities in any lock, 0 npm vulnerabilities | `32f5c07` | +| B5 | MEDIUM | release | The public image workflow ran on every push to `main` in parallel with CI: a commit failing CI was still published | `workflow_run` after CI **succeeded** for a push to `main`, same-repository only; builds and tags exactly the tested commit; first step re-checks the CI result through the API (manual dispatch too); `packages: write` and `actions: read` only in that job | `test_image_is_published_only_after_successful_ci` (fails on `69ec57d`), actionlint + shellcheck clean | `32f5c07` | +| B6 | LOW | performance | `stats(1440)` at the cap: a per-row linear scan over the fee bins and a JSON parse of every row's flags | binary search into the bins; empty flag lists not parsed. Output identical (hash of stats for 60/240/1,440 min equals the previous code's) | p50 220 → 160 ms, p95 293 → 211 ms (50k-row DB, warm); `test_fee_histogram_binary_search_matches_the_linear_definition` | `9065d7d` | + +Final validation on `6bd4f52`: 90-minute fault-injection soak 18/18 (retries: 30 scheduled, 29 +succeeded, no transient failure stored; docs/LIVE_CLOUD.md §11), real-systemd container +test 32/32 plus reboot, CI 8/8. + +Re-measured and **not changed**: flag + fee range + sort by fee with a deep offset is +43–49 ms through the reader (the 210 ms of the earlier HTTP measurement did not reproduce +there); `sort=vsize` with a deep offset (117–134 ms) needs a full sort, and an index would +add a write-path cost for a rarely used sort, so it stays. Already in place and verified: +every action pinned to a commit (`test_every_action_is_pinned_to_a_commit`), workflow-level +`permissions: contents: read`, the image build content-reproducible (two builds, one +without cache: identical package set, application files and native libraries; image +digests differ by timestamps only). + +### Accepted or open (after v0.8.0) + +* **Open, LOW:** `restore` is refused while the collector runs but not while systemd is + about to restart it (stop both units first, as the runbook says). +* **Open, LOW (performance):** `sort=vsize` with a deep offset (~120 ms) and the 24 h stats + (~160 ms) at the cap; both are cached by the dashboard proxy. +* **Accepted:** uvicorn `limit_concurrency=32` (mitigated by Caddy timeouts); a single + 150 MB XML attribute still peaks near 470 MB (expat limitation; the source is a trusted + HTTPS host and the refresh unit has a memory cap). +* **Accepted (second review):** on an unmigrated v0.7 database the risk summary reads as + unavailable until the collector restarts and migrates (the upgrade restarts it); the SSE + outer deadline adds at most 10 s of slack, so a slow remote poll can end a stream early + (the browser reconnects); right after a reconnect the first re-sync delta of an + out-of-sync backend is still taken as new arrivals (bounded by the queue); an old + collector writing to a database already migrated by the new CLI (between `pip install` + and the restart) adds alerts without `alert_txids` rows. +* **External:** Render's real `X-Forwarded-For` hop count, real mempool.space traffic, the + Oracle VM and a 24-hour run on the public network were not available here. + +## v0.7.0 risk intelligence audit + +Problems found while building and testing the risk layers. Sources of evidence: +* the real OFAC files (official XML of 2026-01-30, mirror); +* a dashboard built against the API, which surfaced several API problems; +* the browser end-to-end and soak tests. + +None of these problems was deployed. + +| # | Sev | Component | Problem | Fix | Evidence | +|---|---|---|---|---|---| +| R1 | P1 | indicator parser | Parsing the official XML as a tree peaked at 457 MB on an 85 MB file, above the service's 400 MB cap (the real file is 122 MB), so the refresh would have been OOM-killed. A first streaming version still used 206 MB on the real file because the Locations and other list sections were never cleared | streaming parse that clears each finished record of the list sections: 16 MB peak | `test_sdn_xml_streams_from_a_file_with_bounded_memory`; real file measured | +| R2 | P1 | indicator parser | DTD/ENTITY declarations were refused only in the first 64 KB; a padded file could bypass the check | whole-file scan with overlapping chunks | `test_xml_with_dtd_or_entities_is_refused` (3 MB padding) | +| R3 | P1 | screening | Availability used the latest snapshot's retrieval time, so addresses listed long ago looked unavailable before each refresh | `available_at` = the first snapshot that contained the address | `test_screening_is_point_in_time` | +| R4 | P2 | indicator parser | An address shared by two SDN parties kept only the first party (real case: profiles 38419 and 38420) | parties merged into `details.parties`, labels joined | authentic excerpt test | +| R5 | P2 | indicator semantics | The OFAC entry date (the *party's* designation) was shown as the address listing date | `listed_on` null for OFAC; `party_designated_on` as context | `test_official_sdn_xml_parser_keeps_provenance_and_rejects_non_bitcoin` | +| R6 | P2 | anomaly detector | Default `min_reference` 200 could never reach `alpha` 0.002 (the smallest tail probability is 1/(n+1)), so no anomaly could ever be flagged | default 500; the configuration is validated | `test_detector_config_must_be_able_to_reach_alpha` | +| R7 | P2 | collector | The fetched row and its risk record were separate commits, so the event stream could deliver a row before its assessment (priority shown as null) | one transaction; risk writes in a savepoint, so a failed write keeps the observation | `test_failed_risk_write_keeps_the_observation_…`; e2e "every fetched row is assessed" | +| R8 | P3 | API | `risk_priority: null` was ambiguous; no source staleness or anomaly settings in the summary (the UI hardcoded them); retrospective alerts lacked label/programs; mirror titles repeated the source; "illicit" in layer text | `risk_assessed`, `stale`/`age_s`, settings, full retrospective evidence, source display names, the mirror carries no per-address label, wording | `test_risk_routes_…`, `test_alert_titles_…`, `test_retrospective_screening_…` | +| R9 | P3 | indicator refresh | The official source cannot be fetched from the build environment (proxy 403) | `--fallback` to the mirror; failures reported, previous version kept, exit 1 | `test_indicator_update_falls_back_and_never_breaks_on_failure` | +| R10 | P3 | address validation | OFAC files a TRON address under XBT | strict Bitcoin validation; rejected with a reason | real file: 1 rejected entry | + +Accepted, not changed: +* The alert status history (with operator notes) is CLI-only, by design. +* `available_at` is this deployment's retrieval time, so it lags OFAC's publication by up + to a day. +* Graph relations see only the sampled parents (coverage is reported). + +## v0.6.0 engineering audit (live monitor, cloud kit, research claims) + +Four independent read-only reviews (ingestion correctness against mempool's backend source, +security and API, frontend with fault injection in a browser, ML scientific claims), +followed by fixes, a real-systemd container test, a browser end-to-end test and fault-injection soak runs (6 min and 110 min). Every fixed item has a regression test or a recorded check; nothing +was deployed. Severity: P0 critical, P1 high, P2 medium, P3 low. **No P0 was found.** + +| # | Sev | Component | Problem | Root cause | Fix | Evidence | +|---|---|---|---|---|---|---| +| 1 | P1 | collector | After about 1,024 failed reconnects (~8.5 h of upstream outage) the WebSocket task died for good while the process stayed up; systemd never restarted it | `base * 2**attempt` overflows a float at attempt 1024; the call was outside the try block | exponent clamped at 30 | `test_backoff_never_overflows_after_many_failures` | +| 2 | P1 | collector | A worker or the heartbeat that hit an unexpected exception (SQLite locked or full, an out-of-range integer) died silently: the process looked alive, every new txid was dropped | tasks were only awaited at shutdown; `gather(return_exceptions=True)` hid errors | per-item exception handling (`internal_errors`); `run()` supervises the tasks, sets `fatal`, state `failed`, exit code 1 → systemd restart | `test_worker_survives_…`, `test_dead_pipeline_task_stops_…`, `test_cli_collect_exits_nonzero_on_fatal`; systemd container: 25 s exclusive lock → exit 1 → restarted | +| 3 | P1 | dashboard API (Render) | Concurrent `/v1/live/events` opens bypassed the stream cap; ~40 streams filled uvicorn's concurrency limit and `/health/ready` returned 503 (Render marks the service unhealthy) | cap checked before an `await`, counter incremented after it; no per-client cap | slot reserved synchronously, released in the response wrapper; 2 per client; 10 total (< 32) | `test_stream_slots_are_reserved_before_any_await`, `test_per_client_stream_cap_…` | +| 4 | P1 | dashboard UI | Mock data was labelled "REAL BITCOIN NETWORK DATA" whenever the status call failed or returned an unreadable body; the badge stayed "Connected" with the API unreachable | REAL was the fallback for a null status; last good status never aged | badge is REAL only when the status says so; "Status unknown" on errors or status older than 20 s; "Connected, no new data" after 2 min without observations | 13 frontend tests; Playwright before/after (API down, truncated body, server killed) | +| 5 | P1 | dashboard UI | Live feed rows were not reachable by keyboard | `onClick` on `` only | row buttons, WAI-ARIA tabs | Playwright keyboard checks | +| 6 | P1 | research docs | "Pre-registered / committed before the experiments" cannot be verified: the protocol first appears in git in the same commit as the results | pre-release history not published | wording: fixed before the runs per the author's record, not independently verifiable | docs diff; `git log -- docs/PHASE2_PROTOCOL.md` | +| 7 | P2 | remote proxy | Cache stampede (20 concurrent misses → 20 upstream calls), failures not cached, unbounded key space, whole cache cleared at 512 keys | lock released before the fetch; errors raised before caching | single flight, negative cache, LRU 256, upstream token bucket 3/s, streamed byte cap, invalid JSON → 502 | `tests/test_live_security.py` (5 tests) | +| 8 | P2 | edge API | Unauthenticated requests drained the per-IP bucket shared with the token holder (Render's egress IP is shared) | rate limit ran before auth | valid token exempt from the per-IP limit | `test_edge_rate_limit` | +| 9 | P2 | collector | Replaced/evicted/mined txids still fetched (404s waste ~20 % of the budget) | `removed`/`mined` only counted | skipped before fetch (`gone_before_fetch`); `mined` counted; `replaced` → `replacement_pairs` with documented overlap | `test_removed_or_mined_txids_are_skipped_before_fetch` | +| 10 | P2 | collector | Disconnect outages started at detection, under-reporting up to `stale_after_s` per incident | outage opened when the watchdog fired | starts at the last received message | `test_disconnect_outage_starts_at_the_last_message` | +| 11 | P2 | features | Negative or > 2^63 amounts accepted; the latter crashed the SQLite insert (finding 2) | no range checks | amounts in [0, MAX_MONEY], weight ≤ 4M, locktime/version ranges | `test_out_of_range_*` (7) | +| 12 | P2 | store | At the 50k-row cap: `stats(60)` 92 ms, fee-filtered list 69 ms, COUNT full scans | `ORDER BY fee_rate` forced a fee-index walk; no covering index | `(outcome, fee_rate)` index, sort in Python, `+column` planner hints | before/after table in LIVE_CLOUD.md §8 | +| 13 | P2 | dashboard UI | Horizontal scroll at 390 px; stale-response races (live detail, replay paging); EventSource gave up for good after an HTTP error; partial minute plotted as a drop; errors shown as "no gaps" | `1fr` grid track; effects without cancellation; no manual reconnect | `minmax(0,1fr)`; ignore-late-response guards; backoff reconnect with `?since=`; complete minutes only, gaps as breaks; per-panel error states | Playwright before/after at 390/768/1440 | +| 14 | P2 | research code | Run metadata recorded the *published* Elliptic++ hashes even for synthetic runs, so the "data changed" check could never fire | the published constant was written as the file hash | actual raw-file hashes + `matches_published` + processed fingerprint; evaluate warns on change | `tests/test_data_provenance.py` (4) | +| 15 | P2 | research docs | Misquoted or overstated numbers (43–49 range, 0.92→0.17, P@20 zero-steps, "no gain before the shift", "close to random"); headline used a sub-period instead of the primary comparison | — | corrected against `reports/`; primary pooled result first; CI-coverage caveat | docs diff (no result changed) | +| 16 | P3 | collector | HTTP-date `Retry-After` ignored; burst right after a 429 pause; no pause on 5xx; queued items not re-aged after waiting; backoff reset after one frame; token-bucket float spin; 4 MB frame cap below resync deltas; `timelocked` on non-enforced locktimes; missing status read as unconfirmed | — | each fixed | `tests/test_live_faults.py` | +| 17 | P3 | deploy | `CHAINWATCH_HOST` unvalidated (a bad value emptied the Caddyfile); moving `main` installed as root; token readable by the collector's user; no syscall filter or loopback-only rule | — | host/REF validation, `EXPECTED_SHA`, Caddyfile validated before replace, token 0600 root:root, `SystemCallFilter`, `IPAddressDeny`; exposure 3.0 → 1.3 / 1.1 | systemd container test (LIVE_CLOUD.md §11) | +| 18 | P3 | API | Hostile `Last-Event-ID` → 500; 429/413 without security headers; IPv6 rate-limit rotation within a /64; shutdown waited up to 300 s for SSE | — | strict parsing; headers on every error; /64 keys; `timeout_graceful_shutdown=10` | `tests/test_live_security.py` | +| 19 | P3 | collector | (Found by the 110-min soak) the database could end above `retention_rows` (3,026 / 3,000) | retention runs every 60 s; the process stopped between prunes | prune on clean stop; documented bound while running (cap + one minute of fetches) | `test_clean_stop_leaves_the_database_within_the_row_cap`; soak check | + +Accepted, not changed: the collector and edge API share a service user (a compromised +collector could read the edge's environment via `/proc`); `render.yaml` pulls a version tag +rather than a digest (changing it is a production change); CI installs unlocked dev +dependencies; public `/v1/live/status` passes collector error strings (no secrets). + +--- + # Phase 4 engineering audit (release readiness) An independent review of the serving layer (findings 1–15) and a release review (16–18), carried out by a separate reviewer working diff --git a/docs/CASE_STUDY.md b/docs/CASE_STUDY.md index ce2fc0d..54f21f3 100644 --- a/docs/CASE_STUDY.md +++ b/docs/CASE_STUDY.md @@ -33,7 +33,7 @@ Two properties make the naive approach misleading: | Phase | Method highlights | |---|---| | 1 | Schema validation; join on `txId` (the label file is separate); unknown class excluded from supervision; chronological split 1–29 / 30–34 / 35–49; train-only preprocessing inside the artifact; LR and XGBoost; AP, ROC-AUC, tie-aware P@K/R@K, per-step metrics; one-time test evaluation. | -| 2 | Audit of Phase 1 (all metrics reproduced exactly). Pre-registered protocol committed before any experiment. Explicit **label latency** L (labels of step u known at end of u + L). Time-causal (no look-ahead) retraining schedules (static, expanding, periodic, sliding, recency-weighted) with per-fit assertions and leakage canaries. Dev backtest for selection, confirm backtest frozen. Circular block bootstrap over time steps. Shift diagnostics: prior, covariate, class-conditional, within-period learnability, calibration. | +| 2 | Audit of Phase 1 (all metrics reproduced exactly). Protocol fixed before the Phase 2 runs (author's record; not verifiable from the published git history, where it first appears together with the results). Explicit **label latency** L (labels of step u known at end of u + L). Time-causal (no look-ahead) retraining schedules (static, expanding, periodic, sliding, recency-weighted) with per-fit assertions and leakage canaries. Dev backtest for selection, confirm backtest frozen. Circular block bootstrap over time steps. Shift diagnostics: prior, covariate, class-conditional, within-period learnability, calibration. | | 3 | Inference contract; versioned registry with hash, version and data-fingerprint checks; snapshots exported through the backtest code path; replay engine with no-look-ahead policies; FastAPI service and React dashboard; Docker and CI; latency benchmark. | ## 4. Results (real Elliptic++) @@ -51,17 +51,22 @@ Pooled AP hides a collapse: XGBoost reaches **0.917 on steps 35–42 and 0.043 o ### Phase 2: why it fails and what helps (confirm steps 35–49 are exploratory, because they were inspected in Phase 1) * **Not just fewer illicit transactions.** ROC-AUC, which does not depend on prevalence, - drops from 0.97 to 0.70. A model fitted *within* the late period reaches AP 0.81 on it + drops from 0.97 (35–42) to 0.69 (43–49) for the Phase 1 XGBoost model, and from 0.97 to + 0.70 for a past-only XGBoost fitted on steps 1–34. A model fitted *within* the late + period reaches AP 0.81 on it (a diagnostic, not deployable, because it trains on other late steps, including later ones), while the past-only model gets 0.05. Late illicit transactions are predictable from these features once same-period labels exist, but the boundary learned from the past does not transfer. This is consistent with concept or class-conditional shift; the data cannot identify its cause. -* **Retraining as labels arrive** (L = 1) raises pooled AP on 43–49 from **0.050 to - 0.458** (expanding window; +0.41 [95% CI 0.16, 0.62]) and to 0.493 with recency - weighting. Over all of 35–49 the gain is +0.085 [0.024, 0.229]. The gain on AP is - robust under the pre-registered rule; the gain on budget hits is not, because 35–42 is - at its ceiling. +* **Retraining as labels arrive** (L = 1). On the protocol's primary comparison, pooled + AP over all of 35–49, expanding retraining beats static by **+0.085 [95% CI 0.024, + 0.229]** (0.807 → 0.892). The gain is concentrated after the shift: on the 43–49 + sub-period (its boundary was chosen from Phase 1 inspection) pooled AP rises from + 0.050 to 0.458 (+0.41 [0.16, 0.62]), and to 0.493 with recency weighting. That interval + comes from a block bootstrap over only 7 steps, so its coverage is probably below 95%; + more simply, expanding beats static at all 7 late steps. The gain on AP is robust under + the protocol's rule; the gain on budget hits is not, because 35–42 is at its ceiling. * **Limits.** At L = 3 the gain shrinks to +0.05–0.07. The first steps after the regime change stay poor for every method. When unlabelled transactions compete for review slots, late-period detections at small budgets fall to about 0. @@ -119,7 +124,7 @@ Pooled AP hides a collapse: XGBoost reaches **0.917 on steps 35–42 and 0.043 o 2. **Cold start after regime change.** Test whether multi-hop graph representations transfer across regimes better than tabular features. First run a cheap control (XGBoost plus two-hop aggregates), then GraphSAGE inside the same backtest, - pre-registered with steps 43–45 as the target. A temporal GNN is not motivated, because - the graph has no edges between time steps. + pre-registered (publicly, before any run) with steps 43–45 as the target. A temporal + GNN is not motivated, because the graph has no edges between time steps. 3. **Fresh data** for an untouched holdout, for example a later release or a different chain, before making any further performance claims. diff --git a/docs/DATASET.md b/docs/DATASET.md index 9b73c0f..854e8bc 100644 --- a/docs/DATASET.md +++ b/docs/DATASET.md @@ -10,7 +10,7 @@ was computed by `chainwatch prepare` / `chainwatch eda` (see `reports/eda/`). | Repository | ("Transactions Dataset" folder) | | Paper | Elmougy & Liu, *Demystifying Fraudulent Transactions and Illicit Nodes in the Bitcoin Network for Financial Forensics*, KDD 2023. | | Hosting | CSVs are stored with Git LFS on GitHub; the authors also mirror them on Google Drive | -| Integrity | SHA-256 of each file equals the Git LFS object ID in the repository's pointer files (hard-coded in `src/chainwatch/data/download.py`, checked by `download` and recorded by `prepare`) | +| Integrity | SHA-256 of each file equals the Git LFS object ID in the repository's pointer files (hard-coded in `src/chainwatch/data/download.py`, checked by `download`). `prepare` records the SHA-256 and size of each file actually read, the published digest and `matches_published` in `manifest.json` (`manifest_version` 2); run metadata copies these plus the processed-data fingerprint. Manifests and runs from before this change recorded the published digests regardless of the files on disk, so they do not fingerprint the data. | ### Licensing and redistribution @@ -107,9 +107,15 @@ timestamps. because the raw values are not published. It is an affine transform, so tree models are unaffected and logistic regression re-standardises on the training split. It is a leak in principle but carries no label information. -3. **Aggregate features summarise neighbours.** Because all edges stay within a single - time step, a neighbour of a test transaction is always another test-period transaction. - The features use neighbour *features*, never neighbour *labels*. +3. **Aggregate features summarise neighbours.** Because all published edges stay within + a single time step, a neighbour of a test transaction in the edge list is always + another test-period transaction. According to the publisher, the features use + neighbour *features*, not neighbour *labels*. **Caveat:** the 72 aggregate features are + publisher-computed, and the neighbourhood they aggregate over is not fully documented. + They cannot be verified to use only within-step, pre-step-end information. A partial + check (not yet run): recompute one-hop aggregates of the local features from the + published edge list and measure how closely they reproduce the published aggregate + columns. 4. **Label provenance is opaque.** Labels come from Elliptic's heuristics. Illicit means linked to known illicit categories (scams, ransomware, malware, darknet markets, and so on). Licit and illicit labels are therefore not ground truth about intent, and the diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index 5274154..0d20740 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -66,9 +66,14 @@ GitHub's runners the whole training takes about 4 minutes). Render now **pulls a image**, so nothing is trained on Render, neither at build time nor at start-up. **Pipeline.** -1. [`publish-demo-image.yml`](../.github/workflows/publish-demo-image.yml) runs on every - push to `main` (and on manual dispatch). It builds the same `demo` target as CI for - `linux/amd64`. +1. [`publish-demo-image.yml`](../.github/workflows/publish-demo-image.yml) runs only after + the **CI** workflow has **succeeded for a push to `main`** (`workflow_run`), and builds + exactly the commit CI tested; a failed, cancelled or still-running CI publishes nothing. + Its first step re-checks through the API that CI succeeded for that commit (also for a + manual dispatch on `main`). CI covers the Python tests on Linux and Windows, the + dashboard, the dependency audit (pip-audit and npm audit), shellcheck and the Docker + smoke test. It builds the same `demo` target as CI for `linux/amd64` + (`tests/test_release_gate.py` keeps these conditions from regressing). 2. [`scripts/check_demo_image.sh`](../scripts/check_demo_image.sh) gates the image: - the image holds synthetic data and synthetic-trained models only (marker file, raw-file hashes that do not match the published Elliptic++ files, `data_mode: synthetic`); @@ -161,7 +166,7 @@ A deployment counts as "live" only when this script passes against its public UR | Authentication | none | Read-only API over synthetic data; no user data, no write endpoint. | | CORS | disabled | The dashboard is same-origin. | | Rate limit | 120/min per client on `/v1/*`, burst 30 | In-process token bucket; health checks exempt. | -| Client identity | `trusted_proxy_hops: 1` | The rate limiter uses the `X-Forwarded-For` entry appended by the platform proxy (counted from the right), so a client cannot change its own key by sending the header. If the platform has more proxy hops, all clients share one bucket: that is safe, but tighter than intended. Set `0` when exposing uvicorn directly. | +| Client identity | `trusted_proxy_hops: 1` (**unverified on Render**, see below) | The rate limiter and the per-client event-stream cap use the `X-Forwarded-For` entry appended by the outermost trusted proxy (counted from the right). The value must equal the real number of appending proxies. **Too high:** a client chooses its own key by sending forged entries and bypasses the 120/min limit and the 2-stream cap. **Too low:** every visitor shares one bucket, so one anonymous client sending about 2 requests/s gets every visitor a 429: a low-effort denial of service, not a "safe" setting (v0.8.1 audit). Set `0` when exposing uvicorn directly. | | Request body | 2 MB maximum (ASGI middleware, before parsing); batch size 200 | Larger requests get 413. | | Concurrency | `limit_concurrency: 32`, 1 worker | All state is in memory. | | Headers | same-origin CSP, `nosniff`, `X-Frame-Options: DENY`, `no-referrer` | | @@ -178,3 +183,24 @@ docker compose --profile real up --build # mounts data/processed and artifacts Do **not** expose this publicly. The dataset has no explicit redistribution licence (see [DATASET.md](DATASET.md)), and the API returns per-transaction features and labels. + +### Verifying `trusted_proxy_hops` on Render (do this before relying on the rate limit) + +Render's documentation does not state how many `X-Forwarded-For` entries its proxy appends, +and community reports suggest it keeps client-supplied values. No debug endpoint is added for +this; the rate limiter itself is the probe (burst 30, refill 2/s). Wait at least 20 s between +steps. + +1. **Too high?** From network A, send 40 rapid `GET /v1/info` requests, each with a different + forged header, e.g. `X-Forwarded-For: 10.9.$i.1, 10.8.$i.1`. A 429 after about 30 means + the key is not attacker-controlled; 40 × 200 means `trusted_proxy_hops` is too high. +2. **Too low?** Drain the bucket from network A (35 requests, no forged header), then within + 2 s send 3 requests from network B (e.g. a phone hotspot; compare `curl ifconfig.me`). + B gets 200: the key is per client (correct). B gets 429: the key is shared (too low). + Repeat about 5 times: Render may run several proxy instances. +3. **Optional, to read the chain:** deploy a separate, throwaway Render web service (same + plan and region, never the production one) running a few-line app that echoes + `X-Forwarded-For`; call it with `X-Forwarded-For: 192.0.2.1`. The correct value is the + position of your real IP counted from the right. Delete the service afterwards. +4. Set `trusted_proxy_hops` to that value, repeat steps 1-2 against production, and record + the result in `docs/AUDIT.md`. diff --git a/docs/EVALUATION.md b/docs/EVALUATION.md index b57bcbe..f13930f 100644 --- a/docs/EVALUATION.md +++ b/docs/EVALUATION.md @@ -36,7 +36,10 @@ This protocol was fixed before any model was trained. Changes to it are listed u | decision threshold (max F1) | no | yes | no | | reported metrics | no | yes (optimistic, since it is used for selection) | **yes, once** | -`chainwatch train` never loads test labels into any computation. `chainwatch evaluate` +`chainwatch train` uses no test labels for fitting, selection or thresholding. It is not +blind to the test period, though: it loads the full dataset, and the run metadata +records each split's row and illicit counts (so the test prevalence), and the published +EDA reports per-step prevalence for the test steps. `chainwatch evaluate` reads test data with the split and threshold **frozen in the artifact**, not the current config. It refuses to overwrite an existing test evaluation unless `--force` is given, so repeated test-set looks are an explicit, logged action. diff --git a/docs/INTERVIEW_GUIDE.md b/docs/INTERVIEW_GUIDE.md index c3ff5bc..6fbd0fa 100644 --- a/docs/INTERVIEW_GUIDE.md +++ b/docs/INTERVIEW_GUIDE.md @@ -5,15 +5,17 @@ given in brackets. If a number is not listed here, do not quote it. ## 60-second explanation -"ChainWatch asks how well a fraud-style ranking model holds up when the world changes. I +"ChainWatch asks how well an illicit-transaction ranking model holds up when the world changes. I used Elliptic++, a public dataset of about 204,000 Bitcoin transactions over 49 two-week time steps, where only 23% are labelled. With a strictly chronological evaluation, XGBoost looked strong overall (AP 0.80), but per-time-step reporting showed it collapsing after step 42: AP fell from 0.92 to 0.04, and ROC-AUC fell too, so the ranking itself -broke, not just the base rate. I then pre-registered a backtest of retraining strategies -with an explicit delay before labels arrive. Retraining as labels arrived lifted the -late-period AP to about 0.46. I report that as exploratory, because I had already seen -that period. Finally I built a FastAPI and React replay service that serves the frozen +broke, not just the base rate. I then wrote a protocol for a backtest of retraining +strategies with an explicit delay before labels arrive, before running it (that is my +own record; the published git history cannot prove the timing). Over the whole later +period, retraining as labels arrived raised AP modestly (+0.085, 95% CI 0.02–0.23); the +gain was concentrated after the shift, where AP rose from 0.05 to about 0.46. I report +all of that as exploratory, because I had already seen that period. Finally I built a FastAPI and React replay service that serves the frozen research models and reproduces their scores exactly, with a hardened synthetic-data demo in Docker and CI on Linux and Windows." @@ -29,7 +31,9 @@ in Docker and CI on Linux and Windows." 2. **Baselines.** Logistic regression got AP 0.23 and XGBoost 0.80 on test. Per-step metrics exposed the collapse after step 42. [reports/baseline_results.md] 3. **Diagnosis (Phase 2).** I separated prior shift from ranking failure: ROC-AUC - 0.97 → 0.70, and AP re-weighted to a fixed prevalence 0.92 → 0.17. A model fitted only + 0.97 → 0.69 for the Phase 1 XGBoost model (0.97 → 0.70 for a past-only model fitted + on steps 1–34), and, for that past-only model, AP re-weighted to a fixed prevalence + 0.93 → 0.18. A model fitted only on other late steps reaches AP 0.81 on the late period, while the past-only model gets 0.05. So late illicit transactions are predictable from these features, but the old boundary does not transfer. This is a diagnostic, not a deployable model. @@ -38,8 +42,11 @@ in Docker and CI on Linux and Windows." Five strategies: static, expanding, periodic, sliding window, recency-weighted. Strategy parameters are selected on steps 20–34, then frozen and confirmed on 35–49. Block bootstrap over time steps; 3 to 5 seeds. [docs/PHASE2_PROTOCOL.md] -5. **Result.** Late-period AP 0.050 → 0.458 (+0.41, 95% CI 0.16–0.62). The gain shrinks - at L = 3, and the first steps after the shift stay poor for every method. +5. **Result.** Primary comparison, pooled AP over 35–49: expanding vs static +0.085 + (95% CI 0.024–0.229). On the 43–49 sub-period (boundary chosen from Phase 1 + inspection): AP 0.050 → 0.458 (+0.41, CI 0.16–0.62, from only 7 steps, so coverage is + probably below nominal), positive at all 7 late steps. The gain shrinks at L = 3, and + the first steps after the shift stay poor for every method. 6. **Service (Phase 3).** Frozen snapshots are re-exported through the exact backtest code path; a single `FeatureStore` builds every model input; the replay engine scores step *s* with the snapshot from *s−1*. `verify-replay` re-scores 234,596 transactions and @@ -81,9 +88,10 @@ through the dataset's one-hop aggregate features. - In the backtest, a model retrained at τ only sees labels from steps ≤ τ − L. This is asserted for every fit, and **canary tests** corrupt the labels or features that should be unavailable and check that every score is bit-for-bit unchanged. -- The protocol was committed to git before any Phase 2 experiment ran. Strategy - selection happens on dev only; the confirm run refuses to start without a frozen - selection. +- The protocol was written before the Phase 2 runs by my own record, but the published + git history cannot verify that: the file first appears in the same commit as the + results. What the code does enforce: strategy selection happens on dev only, and the + confirm run refuses to start without a frozen selection. - **Residual issues (state them):** the publisher standardised features using all time steps (irrelevant for trees, a mild leak for linear models), and steps 35–49 were inspected in Phase 1, so no untouched holdout remains. @@ -92,11 +100,14 @@ through the dataset's one-hop aggregate features. What the data shows: - **Prior shift:** the illicit share of labelled transactions fell from about 0.09 to 0.025. -- **More than prior shift:** ROC-AUC (prevalence-invariant) fell to 0.70, and late - illicit transactions get a median score of 0.002 from the old model. +- **More than prior shift:** ROC-AUC (prevalence-invariant) fell to 0.69–0.73 on + 43–49, depending on which static model (Phase 1, past-only 1–34, or Phase 2 static), + and the Phase 1 model's per-step median score for late illicit transactions is + ≤ 0.008 (except step 46, which has 2 illicit). - **Learnable from later labels:** a model trained on late labels ranks the late period well (AP 0.81). -- **Calibration:** degrades (ECE 0.010 → 0.047). +- **Calibration:** degrades (ECE 0.010 → 0.047). The 0.010 is in-sample, because the + Platt calibrator was fitted on 30–34, and both are means of per-step ECE. - **Not visible in the marginals:** bulk feature distributions (median KS) do not jump at step 43. @@ -115,8 +126,8 @@ but I can only say my results are consistent with that, not confirm it. labels of steps 34–41 that the static model never saw (AP about 0.05 → about 0.25). Steps 47–49 recover to 0.49–0.99 once post-shift labels arrive. - **What it did not fix:** steps 43–45 stay poor for every method; the gain shrinks at - L = 3 (+0.05 to +0.07, some CIs include 0); and in the budget metric the pre-registered - robustness rule fails (a ceiling effect in 35–42). + L = 3 (+0.05 to +0.07; the sliding W = 10 CI includes 0); and in the budget metric the + protocol's robustness rule fails (a ceiling effect in 35–42). ### Why are unknown labels a problem? - **Volume and bias:** 77% of transactions are unlabelled, and the labelled subset is not @@ -147,7 +158,7 @@ but I can only say my results are consistent with that, not confirm it. publisher and cannot be computed for new data. ### How was it tested? -- **Python (265 tests):** schema and join, split and leakage guards, label-latency +- **Python (350+ automated tests):** schema and join, data-provenance fingerprints, split and leakage guards, label-latency canaries, schedule causality (parametrised over strategies, origins and latencies), metrics against hand-computed values (including tie-aware P@K), block bootstrap, registry integrity (tampering, version mismatch, path traversal, per-card provenance), @@ -173,8 +184,11 @@ but I can only say my results are consistent with that, not confirm it. ## Questions a senior ML engineer might ask **"Your confirm result reuses a period you had already looked at. Why should I believe it?"** -The selection was frozen on dev (steps 20–34) and committed before confirm ran. The -improvement also appears on dev (+0.16 AP, CI excludes 0). The mechanism is consistent: +The selection was frozen on dev (steps 20–34) and written to `selection.json` before +confirm ran; the confirm stage refuses to run without it, and the run timestamps are in +that order, though git does not record it. The improvement also appears on dev (+0.16 AP +for expanding, CI excludes 0; expanding has no tuned parameter, so that dev number has +no selection bias). The mechanism is consistent: the gain tracks label arrival. But you are right that it is exploratory; the honest fix is fresh data. @@ -197,7 +211,9 @@ evidence supports "use recent labels", not "down-weight old ones". **"Would you deploy this?"** Not as is. Real deployment needs features computable for new transactions, a measured label-latency process, calibration and thresholds tied to analyst capacity, and drift -monitoring. The marginal-feature drift detectors I tried would *not* have flagged step 43. +monitoring. Would a marginal-feature drift detector have flagged step 43? Probably not: +median KS against the training period shows no jump there. But no drift detector was +actually run, so that is an inference, not a measurement. **"Why no GNN?"** There are no edges between time steps, so message passing cannot carry information diff --git a/docs/LIVE_CLOUD.md b/docs/LIVE_CLOUD.md new file mode 100644 index 0000000..83ae595 --- /dev/null +++ b/docs/LIVE_CLOUD.md @@ -0,0 +1,357 @@ +# ChainWatch Live: always-on collection at $0 (deployment design) + +**Status: prepared and tested, not deployed.** No cloud resource has been created, no money +has been spent, and the production Render demo is unchanged. Nothing here claims 24/7 +reliability: that requires the 24-hour observation in §10 on the real VM. Real mempool.space +ingestion is still unverified, because the build environment's egress proxy blocks +mempool.space (docs/LIVE_MONITOR.md §7). + +## 1. Architecture + +``` +mempool.space (public) Oracle Cloud Always Free VM (Ubuntu 24.04) + wss /api/v1/ws ───────────────────────► chainwatch-collector.service (systemd, Restart=always) + GET /api/tx/:id ◄── ≤12 req/min ──────┘ │ reconnect + backoff, dedupe, bounded queue, + │ sampling, outage/gap tracking, restart recovery + ▼ + /var/lib/chainwatch/live.sqlite (WAL, ≤50k rows, ≤7 days) + │ read-only (mode=ro) + ▼ + chainwatch-live-api.service 127.0.0.1:8100 + │ bearer token, rate limit, GET-only, bounded + ▼ + Caddy :443 (Let's Encrypt via .sslip.io) + ▲ + HTTPS + Authorization: Bearer ───┘ (server-to-server; the token never reaches browsers) +Render Free web service (existing demo image, remote live mode) + /v1/live/* proxy: 2 s shared cache, single flight, ──► browser "Live monitor" tab (SSE) + cached failures, ≤3 upstream req/s + /v1/replay/* synthetic demo + research results (unchanged) +``` + +* **Separation:** + * The VM runs only `chainwatch-live` (collector, edge API, backups) from a 26-package + hash-locked set (`requirements/live.lock.txt`). There is no pandas, scikit-learn or + XGBoost, and no command that trains a model. A test checks that the VM entry points + import none of them. + * The historical research and the synthetic demo stay on Render, unchanged. +* **Always on:** + * systemd restarts each process after a crash (`Restart=always`, never giving up) and + starts it at boot. + * The collector reconnects with exponential backoff and jitter. + * Render sleeping, nobody visiting, or your computer being off does not affect + collection. +* **Secure integration:** + * The SQLite file is never reachable from the network. + * Caddy terminates TLS. + * The edge API listens only on 127.0.0.1 and requires a ≥ 32-character bearer token + (constant-time comparison). + * Render calls it server to server, and browsers only ever talk to Render. + +## 2. Provider evaluation (checked 2026-10-14; re-check before you sign up) + +### Oracle Cloud Infrastructure (OCI) Always Free: recommended, with caveats + +| Topic | Finding | Source | +|---|---|---| +| Arm compute | **Changed in 2026.** Reports say the Ampere A1 allowance for free-tier accounts was halved, from 3,000 to **1,500 OCPU-hours** and from 18,000 to **9,000 GB-hours** per month (2 OCPU / 12 GB), effective mid-2026. Oracle's own page was still showing 4 OCPU / 24 GB in cached results, and Oracle support reportedly said Pay As You Go (PAYG) accounts keep 4 / 24. **Treat 1 OCPU / 6 GB as the safe target.** ChainWatch needs far less (§8) | [InfoQ](https://www.infoq.com/news/2026/07/oracle-cloud-free-tier-limits/), [heise](https://www.heise.de/en/news/Oracle-halves-free-cloud-resources-11334516.html), [terminalbytes](https://terminalbytes.com/oracle-cloud-free-tier-changes-2026/), [Oracle docs](https://docs.oracle.com/en-us/iaas/Content/FreeTier/resourceref.htm) | +| x86 compute | 2 × VM.Standard.E2.1.Micro (1/8 OCPU, 1 GB). Also sufficient for ChainWatch | [Oracle docs](https://docs.oracle.com/en-us/iaas/Content/FreeTier/resourceref.htm) | +| ARM64 | Every locked wheel exists for aarch64 and x86-64 (CPython 3.12, manylinux): **verified** by hash-checked download of all 26 wheels for both architectures | this repo | +| Capacity | "Out of host capacity" for A1 is common. Oracle's advice is to try another availability domain or retry later. Your **home region is permanent** and Always Free compute only exists there | [Oracle FAQ](https://www.oracle.com/cloud/free/faq/) | +| Storage | 200 GB block or boot volume in total (third-party reports, not re-confirmed officially). ChainWatch needs < 1 GB of data on the 47 GB default boot volume | [fullmetalbrackets](https://fullmetalbrackets.com/blog/oci-free-tier-breakdown) | +| Bandwidth | **10 TB outbound per month** free (Oracle free-tier page). Inbound traffic is not charged. ChainWatch uses roughly 3–6 GB in and < 1 GB out per month (§8) | [Oracle free tier](https://oracle.com/at/cloud/free) | +| Sign-up | A credit or debit card for identity verification (prepaid and many virtual cards are rejected) and a phone number. The card is not charged unless you upgrade | [Oracle FAQ](https://www.oracle.com/cloud/free/faq/) and community reports | +| **Idle reclamation** | Oracle docs: an Always Free instance is idle, and **may be reclaimed**, if over 7 days its 95th-percentile CPU < 20 %, network < 20 % **and** memory < 20 % (memory applies to A1 only). **ChainWatch will be idle by this definition** (§8). Third-party sources say PAYG accounts are exempt | [Oracle docs](https://docs.oracle.com/en-us/iaas/Content/FreeTier/resourceref.htm), [Customer Connect](https://community.oracle.com/customerconnect/discussion/671904/reclamation-of-idle-compute-instances) | +| Billing risk | A free-tier-only account cannot be billed. **Upgrading to PAYG** removes reclamation and keeps Always Free resources free, but anything beyond the limits is billed to your card: a larger shape, a second boot volume, a load balancer, extra bandwidth | Oracle free tier and FAQ | + +**Do not** run artificial CPU load to dodge the idle policy. It wastes shared capacity, +works against the intent of the rule, and could breach the terms. + +You can choose between: +* **(a) Stay free-tier only:** zero billing risk. Accept that Oracle may reclaim (stop) the + VM. The recovery steps in §9 and the gap tracking make any such stop visible and short. +* **(b) Upgrade to PAYG:** reclamation stops. Protect yourself against charges with a budget + of $1 and an email alert at $0.01, and create only the resources listed in §7. + +**Recommendation: (a) first.** It cannot cost money. Move to (b) only if reclamation actually +happens and you accept the card risk. + +### Alternatives + +| Option | Zero cost? | Limitations | +|---|---|---| +| Google Cloud free tier e2-micro (us-west1/us-central1/us-east1, 30 GB disk, 1 GB egress per month) | **Probably not.** Third-party sources say an in-use external IPv4 address is billed at about $0.005 per hour (≈ $3.65 per month) and is not covered by the free tier | 0.25–2 vCPU (burst), 1 GB RAM: enough. Billing account required. [Google docs](https://cloud.google.com/free/docs/compute-getting-started), [agentdeals](https://agentdeals.dev/vendor/google-compute-engine) | +| Render background worker | No: workers have no free plan | — | +| Render free web service running the collector | No in practice: it **sleeps after 15 min idle**, which stops collection | — | +| GitHub Actions on a schedule | Free for public repositories, but **not continuous** (jobs ≤ 6 h, delayed cron) and outside the intended use of Actions | not recommended | +| A device at home (Raspberry Pi) | No cloud bill, but needs hardware and power | does not meet "computer off" | + +## 3. Infrastructure requirements (measured, §8) + +| Resource | Needed | Always Free | +|---|---|---| +| CPU | < 2 % of one core on average | E2.1.Micro (1/8 OCPU) or 1 A1 OCPU | +| Memory | about 40–95 MB collector (more with risk screening; grows with stored indicator rows, about 2 KB each) + 60 MB edge API + Caddy (≈ 40 MB) + OS | 1 GB (E2.1.Micro) is enough; 6 GB on A1 is plenty | +| Disk | ≈ 285–305 MB database at the 50,000-row cap with risk records (5.5 KB per row after VACUUM; a retention-churn simulation settled at 303 MB including a 10–12 MB freelist), 7 uncompressed daily backups ≈ 2 GB, 68 MB virtualenv | 47 GB default boot volume | +| Network | 1 outbound WebSocket and ≤ 12 HTTPS requests per minute to mempool.space (retries included); inbound 80 (Let's Encrypt HTTP-01 and the redirect) and 443 | 10 TB per month outbound | +| OS | Ubuntu 24.04 (Python 3.12, systemd 255, `caddy` in universe) | standard platform image | + +## 4. Components in this repository + +| Path | Purpose | +|---|---| +| `src/chainwatch/live/collector.py` | collector: reconnect, backoff, dedupe, sampling, bounded queue, 429 handling, restart recovery, outage and sequence-gap tracking, retention, hourly WAL checkpoint | +| `src/chainwatch/live/store.py` | SQLite schema (WAL, indexes, `outages`), retention by rows **and** age, backup API, availability calculation | +| `src/chainwatch/live/edge.py` | edge API: token auth, rate limit, health checks, no docs | +| `src/chainwatch/live/cli.py` | `chainwatch-live collect / serve-edge / backup / report` (no ML imports) | +| `src/chainwatch/serving/live_api.py` | `/v1/live/*` with a local backend (SQLite) or a remote backend (HTTPS edge proxy with cache) | +| `configs/live-cloud.yaml` | VM settings: 2 % sample, 12 requests/min, 50k rows, 7 days | +| `configs/public-demo-live.yaml` | Render dashboard in remote mode (URL and token from environment variables) | +| `requirements/live.lock.txt` | hash-locked VM dependencies (x86-64 and ARM64) | +| `deploy/oracle/*.service`, `*.timer` | systemd units: collector, edge API, daily backup, daily indicator refresh (`chainwatch-indicators`: official OFAC XML, falling back to the mirror) | +| `src/chainwatch/risk/` | risk engine run inside the collector: address screening, observed-graph relations, anomaly detector, supervised gate, alerts ([RISK_ENGINE.md](RISK_ENGINE.md)) | +| `deploy/oracle/Caddyfile.template` | HTTPS reverse proxy, everything except the edge routes answers 404 | +| `deploy/oracle/install.sh` | idempotent installer (packages, user, directories, venv, token, units, Caddy, firewall) | +| `deploy/oracle/smoke_live.sh` | post-deployment smoke test | + +## 5. Reliability features + +| Requirement | Implementation | +|---|---| +| WebSocket reconnection, exponential backoff | full-jitter backoff (1 s → 60 s; exponent clamped, so it never overflows however long the outage), reset only after 30 s of healthy stream; 90 s staleness watchdog; protocol pings every 20 s | +| No silent stalls | `run()` supervises its tasks: if the WebSocket loop, a worker or the heartbeat dies (e.g. the database cannot be written), the collector stops, records state `failed` and exits 1, so systemd restarts it. A bad single item is logged, counted (`internal_errors`) and stored as a failed row instead | +| Bounded queues, deduplication | 100-entry fetch queue (drops are counted); 200k-txid LRU; `UNIQUE(txid)` with `INSERT OR IGNORE` | +| Bounded retries | a transient detail-fetch failure (timeout, network error, HTTP 429, 5xx, or a first 404, which can be the explorer's indexing lag) is retried at most twice (`fetch_max_attempts: 3`), after 2.5–5 s and then 5–10 s (exponential backoff with jitter), never past `max_queue_age_s` and with at most half the queue pending. Every attempt draws from the same token bucket, so retries never exceed `fetch_per_minute`. Malformed or oversized payloads and other 4xx answers are final. Counters: `retries_scheduled`, `retries_succeeded`, `retries_exhausted`, `retries_dropped`; pending retries are recorded with their last error on shutdown | +| Conservative request limits | token bucket, 12 requests/min with a burst of 3, one at a time; pause on HTTP 429 for `Retry-After` (seconds or HTTP-date, no burst after the pause); 30 s pause after HTTP 5xx; txids that were removed or mined before their turn are not fetched (`gone_before_fetch`); queue age re-checked after waiting | +| Persistent state and restart recovery | SQLite on the boot volume. At start-up the collector records the time since the previous heartbeat as a `collector_down` gap, labelled "clean stop" or "unclean exit", and closes outages left open by a crash. Stored txids are not fetched again | +| Graceful shutdown | SIGTERM → final heartbeat `stopped`, open outage closed, HTTP client closed (`TimeoutStopSec=30`) | +| Crash restart / boot start | `Restart=always`, `StartLimitIntervalSec=0`, `RestartSteps`/`RestartMaxDelaySec` (10 s → 5 min); `WantedBy=multi-user.target` | +| Health metrics | heartbeat every 5 s, about 20 counters, `/health/ready` (200 only when connected with a fresh heartbeat), `chainwatch-live report` | +| Outage and gap tracking | `outages` table: `collector_down`, `disconnected` (WebSocket; starts at the last received message, so watchdog latency counts as down time), `sequence_gap`. A sequence gap is recorded when mempool's `sequence` (+1 per update, every update sent to every subscriber) jumps by more than 1 within one connection. These feed availability in `/v1/live/status` and the dashboard | +| Retention and bounded growth | ≤ 50,000 transactions (pruned every 60 s, so up to one minute of fetches, ≤ 12 rows here, above the cap while running; pruned again on a clean stop) and ≤ 7 days, 24 h of per-minute counters, 30 days of outages; hourly `wal_checkpoint(TRUNCATE)`; journald capped at 200 MB; 7 rotated backups | +| Resource caps | systemd `MemoryMax=300M` / `250M`, `CPUQuota=50%`, `TasksMax=64`; indicator refresh `MemoryMax=400M` (the 122 MB official XML is streamed: 16 MB peak Python memory measured) | +| Indicator freshness | the refresh runs daily (04:41 + up to 15 min, and 5 min after boot). A failed refresh keeps the previous version and exits 1 (visible in `systemctl --failed`); a source older than 7 days is reported `stale` in the API and the dashboard. The collector reloads new versions on its next heartbeat and raises retrospective alerts for stored transactions | +| Risk assessment cost | about 2 ms per fetched transaction with a full anomaly window and 531 indicators (§8 measurement environment); the observation and its assessment are committed together | + +## 6. Security model + +* **Network exposure:** only Caddy (TCP 80/443). SSH is protected by Oracle's key-only + default. The edge API listens on 127.0.0.1, and SQLite is a local file. +* **Authentication:** + * every `/v1/live/*` call needs `Authorization: Bearer `; + * the token is 64 hex characters generated **on the VM** by `install.sh` (`openssl rand -hex + 32`) and stored in `/etc/chainwatch/live.env` (**0600 root:root**: systemd reads it + before dropping privileges, so the service user, and with it the collector that parses + internet data, cannot read the file); + * on Render it is a secret environment variable; it is never in Git and never sent to + browsers. + * Residual risk (accepted): both services run as `chainwatch`, so a compromised collector + could read the edge process's environment through `/proc`. A separate user for the edge + API would remove this, at the cost of shared-group permissions on the SQLite WAL files. +* **Limits:** + * edge API: 240 requests/min per client for **unauthenticated** traffic (keyed on the + address Caddy appends; IPv6 by /64). The token holder is not rate limited, so floods + from a shared egress IP (Render's) cannot lock the dashboard out. 64 KB bodies, + `limit ≤ 200`, GET only, no docs or OpenAPI schema; uvicorn `limit_concurrency=32`. + * Caddy: header and body read timeouts of 10 s and a 60 s idle timeout (slow-client + connections cannot hold the 32 uvicorn slots), and only `GET` reaches the edge + routes. + * dashboard: its existing 120/min public limit; the remote backend fetches each query at + most once per 2 s (single flight for concurrent misses), caches failures for the same + period, and caps all upstream traffic at 3 requests/s (burst 20), so neither visitor + count nor varied query parameters multiply edge load. The fixed queries the dashboard + polls bypass that budget, so a visitor scanning many parameter combinations cannot + starve the dashboard; arbitrary `hours`/`window` values are snapped to a few steps, a + failed refresh serves the last good answer for up to 60 s (flagged stale), and every + upstream call has an overall deadline. + * event streams: at most 10 on Render (below its 32-connection limit) and 2 per client; + slots are reserved before any await and always released; each stream ends after 300 s, + and a hard deadline closes it even if the client never reads. +* **Sandbox:** units run as the `chainwatch` user with `ProtectSystem=strict`, + `NoNewPrivileges`, an empty capability set, `SystemCallFilter=@system-service` (minus + privileged, resource, mount and debug calls), `ProtectProc=invisible`, `RemoveIPC`, and + only `/var/lib/chainwatch` writable. The edge API may only talk to loopback + (`IPAddressDeny=any`, `IPAddressAllow=localhost`). `systemd-analyze security` exposure: + collector **1.3**, API **1.1**, backup 2.3 (all "OK"; previously 3.0 / 3.0 / 2.3). +* **Supply chain:** hash-locked pip install (`--require-hashes`); code is cloned from the + public repository at a chosen ref (validated); `EXPECTED_SHA` pins the exact commit. + Install `REF=main` with `EXPECTED_SHA=` (no v0.8 release tag exists yet; creating one is a release step for the owner). CI installs + from its own hash lock (`requirements/dev.lock.txt`) and audits all three locks + (pip-audit) and the dashboard's npm tree on every run; Dependabot proposes updates as + pull requests; the public demo image is published only after a successful CI run for + that exact commit (docs/DEPLOYMENT.md). +* **Errors:** 500 answers carry the same security headers as every other answer and a + JSON error body without internal details. +* **Installer input:** `CHAINWATCH_HOST` must be a bare hostname; the Caddyfile is rendered + to a temporary file and checked with `caddy validate` before it replaces the current one. +* **Logs:** JSON lines with no request bodies, tokens or client addresses. + +## 7. Activate it: manual steps (owner) + +**A. Oracle account** (cannot be automated; your decision on billing): +1. Sign up at oracle.com/cloud/free with a credit or debit card and phone number. Pick a home + region with available A1 capacity and, if possible, 3 availability domains. **The choice + is permanent.** +2. Optionally set a budget (Billing → Budgets, $1, alert at $0.01) as an early warning. +3. Stay on the free-tier account (§2, option a) unless you decide otherwise. + +**B. VM** (Console → Compute → Instances → Create): +1. Image **Canonical Ubuntu 24.04**. +2. Shape **VM.Standard.A1.Flex, 1 OCPU, 6 GB**. If capacity is missing, use + **VM.Standard.E2.1.Micro**. +3. Default 47 GB boot volume, public IPv4, upload your SSH public key. +4. VCN security list: add ingress TCP **80** and **443** from 0.0.0.0/0 (22 stays as is). +5. Create nothing else: no block volumes, load balancers or databases. + +**C. Install** (SSH into the VM): +```bash +IP=$(curl -s https://ifconfig.me); HOST="${IP//./-}.sslip.io" # e.g. 203-0-113-7.sslip.io +REF=main # a branch or tag (git clone --branch); after the v0.8.0 merge +SHA= # from GitHub; install.sh aborts if the checkout differs +curl -fsSLO "https://raw.githubusercontent.com/Apostal322/ChainWatch/$SHA/deploy/oracle/install.sh" +less install.sh # read it before running it as root +sudo CHAINWATCH_HOST="$HOST" REF="$REF" EXPECTED_SHA="$SHA" bash install.sh +sudo cat /etc/chainwatch/live.env # copy the token once; keep it secret +``` + +**D. Verify on the VM, then from your machine:** +```bash +systemctl status chainwatch-collector chainwatch-live-api caddy --no-pager +TOKEN= ./deploy/oracle/smoke_live.sh "https://$HOST" # from a clone of the repo +``` + +**E. Connect the dashboard** (only after D passes; this changes production): +1. Merge the pull request so that GitHub Actions publishes the new demo image. +2. Change `render.yaml` to the new image tag. +3. In the Render dashboard, set: + * `CHAINWATCH_CONFIG=/app/configs/public-demo-live.yaml` + * `CHAINWATCH_LIVE_URL=https://$HOST` + * `CHAINWATCH_LIVE_TOKEN` as a **secret**. +4. Manual Deploy. +5. Run `scripts/smoke_demo.sh` against the Render URL and open the Live monitor tab. + +## 8. Resource and usage estimates + +Measured with the real processes (`chainwatch-live collect` and `serve-edge`) against a local +mock source that announces 6 tx/s, with `configs/live-cloud.yaml` limits and a client polling +the edge API every 2 s: + +| Measure | Value | +|---|---| +| Collector CPU | 0.46 CPU-s over 600 s ⇒ **0.08 %** of one core (3,600 txids announced, 79 sampled, 78 fetched, 1 failed, 0 dropped) | +| Edge API CPU (with polling) | 2.6 CPU-s over 600 s ⇒ **0.43 %** of one core (about 560 authenticated requests) | +| Collector memory (peak RSS) | **39.4 MB** (VmHWM) | +| Edge API memory (peak RSS) | **56.6 MB** (VmHWM) | +| Container test (fresh Ubuntu 24.04, install.sh) | collector 37 MB, edge API 57 MB RSS; < 1 % CPU | +| Database at the retention cap | **283.4 MB** for 50,000 transaction rows with 47,525 risk records, 699,894 address rows and the v0.8 covering indexes (277.8 MB before them). On disk (dbstat): `risk` 97.6 MB, `tx` 72.4 MB, `tx_address` 41.6 MB plus its indexes 43.9 MB, `risk_summary_cov` 4.3 MB (the 67 MB stated earlier was the JSON payload, not disk use); 276.6 MB after VACUUM; a retention-churn simulation settles at about 303 MB. The v0.5 figure of 62.7 MB had no risk tables | +| Virtualenv on the VM | 68 MB | + +Edge API latency at the 50,000-row cap (synthetic rows, one persistent client like the +Render proxy; p50). The audit found three slow read paths; the fix is a covering +`(outcome, fee_rate)` index plus planner hints, measured before and after: + +| Request | Before | After | +|---|---|---| +| store `list` (default page, `outcome=fetched`) | 15.7 ms | 2.8 ms | +| store `list` with `min_fee_rate`, sorted by fee | 69.2 ms | 3.0 ms | +| store `stats(60)` | 91.8 ms | 14.4 ms | +| store `list` with `flag=` | 26.4 ms | 27.3 ms (unchanged: every row's flags are read) | +| HTTP `/v1/live/status`, `/transactions?limit=50`, `/stats` | — | 3.0 / 5.6 / 18.8 ms | + +v0.8 measurement over HTTP at the cap (50,000 synthetic rows with risk records, 480 alerts; +one persistent client; p50 / p95 in ms): + +| Request | p50 | p95 | +|---|---|---| +| status, transaction detail, outages | 2.4–4.1 | 3.7–5.7 | +| `/transactions` default, `limit=200`, `first_seen` offset 45,000 | 6.6–8.0 | 7.5–9.4 | +| `/stats?window=60` | 10.8 | 12.8 | +| `/risk/summary` (cached for 15 s; cold 0.48 s → **0.10 s** after the covering-index rewrite) | 2.0 | 2.9 | +| `/risk/findings`, `/risk/alerts` with `limit=200` | 8.8–13.5 | 10.3–16.2 | +| slow: `/transactions` with flag + fee range + deep offset | 209.8 | 248.5 | +| slow: `/stats?window=1440` (24 h histogram) | 254.1 | 301.9 | +| slow: `sort=vsize` with offset 100,000 | 144.8 | 161.0 | + +The slow paths are bounded (offset and window are capped, the Render proxy snaps windows to +60 / 240 / 1,440 and caches results) and acceptable at demo traffic; they are listed as +open performance work in docs/AUDIT.md. + +(A first soak run reported ~55 ms per edge request: that was the probe opening a new HTTP +client, and loading a CA bundle, per request, not the server.) + +Monthly estimates (derived, not measured on the network): +* **Requests to mempool.space:** ≤ 12 per minute ⇒ ≤ 17,300 per day ⇒ ≤ 520k per month, + plus one long-lived WebSocket. +* **Inbound traffic:** about 64-byte txids at a few per second (≈ 1–2 GB per month), plus + detail payloads of 2–5 KB × ≤ 17k per day (≈ 1–3 GB per month). +* **Outbound traffic:** dashboard polling; below 1 GB per month at demo traffic. +* **Cost:** $0 within Always Free (§2), provided you create only the resources in §7. + +## 9. Monitoring and recovery + +| Situation | What to do | +|---|---| +| Health at a glance | `curl -s https://$HOST/health/ready` (200 = connected); the dashboard shows last observation, observed share and gaps | +| Detailed state | `sudo -u chainwatch /opt/chainwatch/venv/bin/chainwatch-live --config /opt/chainwatch/app/configs/live-cloud.yaml report --hours 24` | +| Logs | `journalctl -u chainwatch-collector -u chainwatch-live-api --since -1h` | +| Process crashed | nothing: systemd restarts it within 10 s to 5 min, and the gap appears as `collector_down` | +| VM rebooted | nothing: the units and Caddy start at boot | +| VM stopped or reclaimed by Oracle | Console → Instances → Start. Data is on the boot volume, and the gap is recorded on start-up | +| mempool.space down or rate-limited | automatic backoff; `disconnected` gaps and `rate_limited` counters show it. Lower `fetch_per_minute` if 429s persist | +| Collector state `failed` / dashboard "Collector failed" | the process hit a fatal internal error (e.g. database unwritable) and exited 1; systemd restarts it. `journalctl -u chainwatch-collector \| grep "pipeline task died"` names the cause; check `df -h /var/lib/chainwatch` | +| Dashboard "Connected, no new data" | the WebSocket is up but nothing was fetched for 2 min: check the report's `failures` (429 → lower `fetch_per_minute`; `http_5xx` → mempool.space trouble) | +| Dashboard "Status unknown" | Render cannot reach the edge API: `curl https://$HOST/health/live`, then `systemctl status caddy chainwatch-live-api`, then the Render logs (`live_upstream_unavailable`) | +| Restore a backup | `sudo systemctl stop chainwatch-collector chainwatch-live-api chainwatch-indicators.timer chainwatch-backup.timer`; `sudo -u chainwatch /opt/chainwatch/venv/bin/chainwatch-live --config /opt/chainwatch/app/configs/live-cloud.yaml restore /var/backups/chainwatch/live-.sqlite` (the backup is integrity-checked; check it against its `.sha256` first with `sha256sum -c`). Restore refuses while any writer has the database open (every writer holds a shared lock on `live.sqlite.lock`: the collector, a timer-run indicator refresh or backup) or a collector heartbeat is fresh; it copies the backup into the live file through SQLite's backup API (no file is renamed) and keeps the replaced contents, including un-checkpointed WAL data, as one `live.sqlite.pre-restore-` file. A collector that systemd starts during a restore exits 75 and is retried 10 s later. Then start the units and both timers again | +| Rotate the token (no downtime) | 1. add `CHAINWATCH_LIVE_TOKEN_NEXT=` (generate with `openssl rand -hex 32`) to `/etc/chainwatch/live.env` (mode 0600) and `sudo systemctl restart chainwatch-live-api`: the edge now accepts both tokens; 2. update the Render secret to the new token and redeploy; 3. make the new token `CHAINWATCH_LIVE_TOKEN`, delete the `_NEXT` line and restart the edge again. Tokens must match `[A-Za-z0-9._~+/=-]{32,}`; a malformed or whitespace-padded token makes the edge exit 78 (systemd does not restart-loop) | +| Upgrade | Take a backup (`sudo systemctl start chainwatch-backup.service`). Then fetch the **new** installer at the pinned commit and run it: `curl -fsSLO "https://raw.githubusercontent.com/Apostal322/ChainWatch/$SHA/deploy/oracle/install.sh"` and `sudo REF=main EXPECTED_SHA=$SHA CHAINWATCH_HOST=$HOST bash install.sh` (idempotent; keeps the token and data; migrations run at start-up). The fetched commit is verified **before** anything on disk changes, and an installer that differs from the one running re-executes the new one (bash keeps running the old text when a file is replaced, so installs older than v0.8.1 ran the old installer) | +| Roll back | **Not by reinstalling an older version on the migrated database.** v0.8 rebuilt `indicator_versions`, re-keyed alerts and added tables and columns; v0.7 code then opens duplicate alerts under the old keys and loses dismissals (verified). Instead: stop the units and timers, `restore` the backup taken before the upgrade, then install the older ref with its `EXPECTED_SHA` | +| Uninstall | `systemctl disable --now chainwatch-*`; remove `/opt/chainwatch`, `/var/lib/chainwatch`, `/etc/chainwatch`; then terminate the VM in the Console | + +## 10. 24-hour reliability test plan (before any 24/7 claim) + +1. Deploy (§7 A to D) and start the clock when `smoke_live.sh` passes. +2. During the 24 hours, without manual fixes: + * hour 1: `sudo systemctl kill -s SIGKILL chainwatch-collector`; expect a restart within 15 s + and one `collector_down` gap; + * hour 2: `sudo reboot`; expect both services back and a gap equal to the reboot time; + * all day: leave it alone. +3. Every 6 hours, from your machine, run `smoke_live.sh` and save + `chainwatch-live report --hours 6`. +4. At 24 hours, run `chainwatch-live report --hours 24` and record the results. +5. **Pass criteria:** + * observed share ≥ 99 % excluding the two deliberate outages; + * every gap explained; + * last observation < 10 min old at every check; + * no OOM kills or restarts apart from the deliberate ones (`journalctl -u chainwatch-collector | grep -c Started`); + * database < 150 MB after 24 h (at most 17,280 fetches a day at 12 per minute, about + 5.7 KB per row with its risk record; about 285 MB at the 50,000-row cap), journal + < 200 MB; + * no unexpected Oracle charges. +6. Publish the report (numbers and gaps) in this file. Only then describe the system as + having run continuously for 24 hours, and say "sampled", never "complete". + +## 11. Tests actually performed (this environment) + +| Test | Result | +|---|---| +| Real systemd (Ubuntu 24.04 container booted with systemd 255 as PID 1; real `install.sh`; units pointed at a local mock by drop-ins) | **all 10 sections PASS**: install 20 s; token file 0600 root:root and unreadable by the service user; units enabled; no seccomp kills under `SystemCallFilter`; `smoke_live.sh` PASS; SIGKILL → restarted by systemd after 10 s, 15.4 s `collector_down` "unclean exit"; another process holding an exclusive SQLite lock for 25 s → edge reads continue (WAL) → collector `task heartbeat died: OperationalError: database is locked` → exit 1 → restarted; backup through `chainwatch-backup.service`; `restore` refused while running, works after stop; re-running `install.sh` keeps token and data; bad host / REF / `EXPECTED_SHA` rejected; `caddy validate` (2.6.2) on the rendered template; exposure 1.3 / 1.1 / 2.3; container reboot → all units back, 0.9 s "clean stop" gap | +| Same real-systemd test, v0.8 (commit `53f6f65`, 14 sections) | **35/35 PASS** (sections 1–10 as above, plus): 11. `chainwatch-indicators.service` with no route to the official file exits 1 and keeps the loaded list (versions 1 → 1), and every fetched row (98) has a risk record; 12. an invalid config (`retention_rows: 0`) exits 78 with `NRestarts=0`, no restart loop; 13. a whitespace-padded token makes the edge exit 78 and stay down; 14. token rotation: the current and `CHAINWATCH_LIVE_TOKEN_NEXT` tokens are both accepted. `caddy validate` passes with the new timeouts. Container reboot: both units active, timers enabled, ready, 1.0 s "clean stop" gap, integrity ok | +| Same real-systemd test, **final v0.8.0 source** (commit `6bd4f52` installed by `install.sh` from the local repository; 14 sections) | **32 checks PASS, 0 FAIL**: install 24 s; token 0600 root:root, unreadable by the service user; no seccomp kills; `smoke_live.sh` PASS; SIGKILL → restarted by systemd, recorded as `collector_down` "unclean exit"; 25 s exclusive lock → edge reads continue, collector exits 1 and is restarted; backup via `chainwatch-backup.service`, restore refused while running and works after stop; idempotent re-install keeps token and data; bad host / REF / `EXPECTED_SHA` rejected; `caddy validate`; exposure 1.3 / 1.1 / 2.3; failed indicator refresh exits 1 and keeps the list, every fetched row assessed; invalid config exit 78 (no restart loop); malformed token exit 78; token rotation. **Reboot** (container restart): both units active, timers enabled, `/health/ready` 200, 401 without or with a wrong token and 200 with the real one, 0.9 s "clean stop" gap, integrity ok | +| Fault-injection soak, 6 min, one fault every 25 s (`scripts/soak_test.py`) | **11/11 checks PASS**: REST 429 / 500 / malformed JSON / schema drift / slow, WebSocket drop / 40 s silence / 5,000-txid burst / sequence gap, collector SIGKILL, edge restart, 5 SSE clients dropped mid-stream. Recovery: WS drop 4.6 s, kill 5.6 s, edge restart 0.6 s, silence 23 s (watchdog 20 s). Edge and dashboard availability 100 % (169 probes each), integrity ok, 0 tracebacks, clean SIGTERM for every process | +| Full system in a browser (`scripts/e2e_live_browser.py`: mock → collector → SQLite → edge API with token → dashboard in remote mode → SSE → React) | **10/10 PASS**: mock source labelled (not REAL); connected; new transactions arrive live; the detail panel matches the API (txid, vsize, fee); collector SIGKILL shown as "Disconnected" after 13 s; recovery shown 10 s after restart; the gap appears in the gaps table; the Replay tab stays synthetic; 0 console errors | +| Fault-injection soak, **110 min** (6,601 s), one fault every 2 min, commit `06d59da` (`scripts/soak_test.py --minutes 110 --fault-every 120`) | 52 faults (each of the 12 kinds 4–5 times, incl. 4 collector SIGKILLs and 4 edge restarts); every recovery within 90 s (WS drop median 5.2 s, kill 5.6 s, edge restart 0.7 s, 40 s silence 22.3 s); edge and dashboard availability **99.97 %** (1 failed probe of 3,072 each, during edge restarts); SQLite integrity ok; 0 tracebacks; clean SIGTERM shutdown of every process; collector 0.23 % CPU, RSS 38 → 44 MB (peak 43.8 MB first half, 44.2 MB second half: the bounded dedupe LRU filling); edge 0.57 % CPU, 57 MB flat; queue max 61/100; 4 `collector_down`, 13 `disconnected`, 4 `sequence_gap` outages recorded. **10/11 checks passed**: the final row count was 3,026 against a 3,000 cap, because retention runs every 60 s and the run ended between prunes. Fixed afterwards: a clean stop now prunes, and the check now uses the documented bound (cap + one minute of fetches) (`test_clean_stop_leaves_the_database_within_the_row_cap`). An earlier 3-hour attempt was cut off after 17 minutes when the build container was recycled; that partial run had 0 tracebacks and integrity ok, but produced no report | +| Fault-injection soak with **risk intelligence**, **60 min** (3,602 s), one fault every 90 s, commit `ac6d4c8` (`scripts/soak_test.py --minutes 60`) | **17/17 checks PASS**. **Faults:** 38 (13 kinds, including 3 collector SIGKILLs, 3 edge restarts and 3 indicator refreshes). The refreshes used a local **TEST** list of about 12,000 mock addresses, not sanctions data. **Recovery and availability:** every recovery within 90 s (WS drop at most 5.1 s, kill at most 6.2 s, edge restart at most 1.2 s, 40 s silence 23 s); edge availability 99.88 % and dashboard 99.94 % (1,684 probes each); SQLite integrity ok; 0 tracebacks; clean SIGTERM. **Risk:** every stored fetched row had a risk record (2,160 assessed: 197 P1 source matches, 2 P3, 2 P4); 205 retrospective alerts after refreshes; 0 layer errors; 0 assessment errors; latency p50 2.9 ms and p95 4.6 ms with a full 2,000-transaction anomaly window. **Resources:** collector 0.52 % CPU and edge 0.64 % CPU; collector RSS 50 MB, rising in steps **only at indicator refreshes** (+24 MB and +28 MB, flat in between; a restart reloads it smaller). Memory scales with stored indicator rows (about 2 KB per row including the reload peak), so the real OFAC list (531 addresses) costs under 2 MB | +| Fault-injection soak, v0.8 final code, **90 min** (5,401 s), one fault every 90 s, commit `4872b7b` | **16/17 checks**. 57 faults (13 kinds, including 4 collector SIGKILLs and 4 edge restarts); every recovery within 24 s (WS drop at most 5.7 s, kill at most 5.7 s, edge restart at most 0.65 s, 40 s silence 23.8 s); edge and dashboard availability **99.96 %** (2,547 probes each); SQLite integrity ok; 0 tracebacks; clean SIGTERM; collector 0.47 % CPU, RSS peak 56.5 MB first half / 57.0 MB second half; edge 0.60 % CPU, 58.6 MB flat; queue max 91/100; every fetched row had a risk record, 0 layer errors. **Failed check: "every indicator update succeeded"** (1 of 5): each soak refresh replaced the whole TEST list, which the v0.8 mass-removal guard refuses by design ("would delist 11999 of 11999 active listings"). The soak scenario was wrong, not the code; it was changed to realistic updates and re-run (next row) | +| Fault-injection soak, v0.8 final code with realistic list updates, **40 min** (2,402 s), one fault every 60 s, commit `4501f4e` (same `src/` as `4872b7b`) | **17/17 checks PASS**. 37 faults (13 kinds, including 3 SIGKILLs, 3 edge restarts, 2 indicator refreshes); every recovery within 23 s; availability 99.91 % (1,132 probes each); integrity ok; 0 tracebacks; clean SIGTERM; collector 0.40 % CPU, RSS 67.3 → 69.1 MB (the refreshes add indicator rows); 3/3 indicator updates succeeded, 95 retrospective alerts, 151 live source matches, every fetched row assessed, 0 layer errors | +| 120-minute soak attempt, commit `53f6f65` | **no result**: the run was stopped by this environment's 2-hour task limit just before it wrote its report (output was buffered). Not counted | +| Fault-injection soak, **final v0.8.0 source**, **90 min** (5,403 s, 01:56–03:26 UTC on 2026-10-19), one fault every 90 s, commit `6bd4f52` (clean tree) | **18/18 checks PASS** (the new one: retries bounded). 57 faults (13 kinds: 5 each of REST 429 / 500 / malformed, WS drop, 5,000-txid burst; 4 each of collector SIGKILL, edge restart, schema drift, slow REST, sequence gap, 40 s silence, SSE clients, indicator update); every recovery within 25 s (WS drop at most 4.6 s, kill at most 5.6 s, edge restart 0.61 s, silence at most 24.2 s); edge and dashboard availability **100 %** (2,546 probes each); SQLite integrity ok; 0 tracebacks; clean SIGTERM (0.11–0.16 s). Memory: collector RSS peak 69.3 MB first half, 72.8 MB second half (indicator refreshes add rows); edge 58.7 / 58.6 MB. CPU 0.51 % / 0.61 %. Queue max 92/100. Risk: every fetched row assessed, 0 layer errors, 5/5 indicator updates succeeded, 327 live source matches and 197 retrospective alerts. Retries (last collector process): 722 queued, 30 retries scheduled, 29 succeeded, 0 exhausted or dropped; no 5xx or 429 failure was stored; the stored failures are all permanent (94 malformed payloads, 2 `not_found` after their one retry) | +| Real systemd, v0.8.1 (commit `3cd8148`, 39 checks incl. restore lock refusal, restore content equality, pre-restore copy, `EXPECTED_SHA` mismatch, exit 78) and fault-injection soak, **90 min** (5,401 s, 21:22–22:52 UTC on 2026-10-23, clean tree) | **39/39 PASS**; reboot: both units back, auth 401/401/200, clean-stop gap, integrity ok. Soak **18/18 checks PASS**: 57 faults, every recovery within 24 s, availability 100 %, 0 tracebacks, collector 69.3 → 72.7 MB, 32/32 retries succeeded | +| Real systemd, **final v0.8.1 source** (commit `4f091cd`: paged risk lists, setuptools 84.1.0) and a **rehearsal of the §10 procedure** against the local mock (minutes, not 24 hours) | **39/39 PASS**. Paged `/v1/live/findings` and `/alerts` on the installed edge: 401 without the token, 400 for a bad cursor, totals reported (no indicator list in the container: findings 0, rows listed as insufficient evidence). §10 hour-1 step: `systemctl kill -s SIGKILL` → restarted in ~10 s, one 15.1 s `collector_down` gap "unclean exit". Hour-2 step: container reboot → both units and timers back, auth 401/401/200, a 1.0 s clean-stop gap (a container restarts faster than a VM), `integrity_check` ok. `chainwatch-live report --hours 1` as the service user returns every field the pass criteria need. Not a 24-hour run and not network data | +| Python unit and integration tests | see the PR. Regression tests from the audit: `tests/test_live_faults.py` (20) and `tests/test_live_security.py` (13). Cloud-specific tests (`tests/test_live_cloud.py`, 24): crash and clean restart recovery, dangling outages, disconnect outage and sequence gap against a local WebSocket server, availability merging, v0.5.0 schema migration, row and age retention, WAL checkpoint, backup integrity and rotation, reliability report, edge auth (missing, wrong and malformed token), health checks, docs off, GET-only, limits, rate limit, weak token refused, dashboard to edge in remote mode (auth header, shared cache, transactions, detail, outages, stats, SSE), clean 502 when the edge rejects or is down, https-only remote URL, configs, no ML imports on the VM, lock without ML packages, systemd unit invariants | +| `systemd-analyze verify` (systemd 255, as on Ubuntu 24.04) | all 4 units OK; security exposure 1.3 / 1.1 / 2.3 ("OK") | +| `install.sh` in a fresh `ubuntu:24.04` container (no systemd or Caddy) | exit 0 in 41–55 s; user, directories and token permissions correct; no ML packages; re-run idempotent with the token kept | +| Same container, real processes against a local mock source | `smoke_live.sh` **PASS** (health, 401 ×2, status, transactions, limits, no DB/docs exposure); `kill -9` → restart → one 21 s `collector_down` gap "unclean exit"; backup OK; SIGTERM → `stopped` | +| 10-minute resource run (real processes, mock at 6 tx/s, client polling every 2 s) | collector 0.08 % CPU / 39 MB, edge 0.43 % CPU / 57 MB; 3,600 txids, 0 dropped, 0 sequence gaps (§8) | +| Dashboard in remote mode, real processes (`public-demo-live.yaml` → edge API with a 64-hex token → collector) | status `via remote collector (edge API)`; a 36 s restart gap appears in the gaps table and in the 24-hour observed share (94.7 %); SSE, detail panel and the mock-source label work; Replay tab still shows the synthetic banner; 0 browser console errors (Playwright) | +| Wheels for ARM64 and x86-64 | all 26 locked wheels downloaded with hash verification for both | +| Not tested here | real mempool.space traffic, Oracle itself (shape, network, reclamation), Caddy serving and Let's Encrypt issuance, a real VM reboot, a 24-hour run on the public network | diff --git a/docs/LIVE_FEATURE_SUBSET_PROTOCOL.md b/docs/LIVE_FEATURE_SUBSET_PROTOCOL.md new file mode 100644 index 0000000..46ca675 --- /dev/null +++ b/docs/LIVE_FEATURE_SUBSET_PROTOCOL.md @@ -0,0 +1,76 @@ +# Protocol: how much illicit-ranking signal survives with live-computable features? + +**Status: written and committed before any run of this experiment** (this file's first commit +precedes the result files under `reports/phase6/`; both are in the published history). + +## Why + +ChainWatch's live monitor applies no model (docs/RISK_DATA_FEASIBILITY.md). The feasibility +assessment found no labelled data whose features a live collector can compute, with one +partial exception: 16 of Elliptic++'s 17 "augmented" transaction features are plain +quantities a collector *can* compute from one mempool transaction and its prevouts. This +experiment measures, on historical data, how much of the Phase 1 ranking performance remains +when a model may only use those quantities. It is a **diagnostic**, not a path to a live +model. + +## Question and hypotheses + +* **Q.** On Elliptic++, what is the test-period average precision (AP) of models restricted to + live-computable features, relative to the same models with all 182 features? +* **H1.** XGBoost on the 16 live-computable features has lower pooled test AP (steps 35–49) + than XGBoost on all 182 features (Phase 1: 0.797). +* **H2.** Both collapse after step 42; the restricted model is not expected to be more robust. + Reported for 35–42 and 43–49 separately, descriptively. + +## Data and features + +* Elliptic++ transactions (`txs_features.csv`, `txs_classes.csv`, `txs_edgelist.csv`), + downloaded by `chainwatch download` and verified against the published SHA-256. Labelled + rows only (illicit vs licit); unknown is excluded, never treated as negative. +* Feature sets: + * `all`: 93 local + 72 aggregate + 17 augmented (the Phase 1 setting, re-run here). + * `augmented`: the 17 augmented features. + * `live_computable`: the augmented features **minus `out_txs_degree`**, which counts later + transactions spending this one's outputs and is unknown at observation time. +* Known mismatches with the live collector, accepted and stated: `in_txs_degree` counts + in-dataset parents within the time step (live: all parents); BTC amounts and `size` come + from 2016–2017 transactions (pre-SegWit majority; live uses vsize, 2026 traffic); the + publisher's `total_BTC` definition is not documented in detail. + +## Method (unchanged from Phase 1) + +* Chronological split: train 1–29, validation 30–34, test 35–49 (configs/default.yaml). +* Models and grids: logistic regression and XGBoost with the Phase 1 grids, selection and + early stopping on validation only, threshold by max F1 on validation. +* Preprocessing: log1p of augmented features, fitted on training rows only. +* Seed 42. Configs: `configs/subset-augmented.yaml`, `configs/subset-live.yaml`. + +## Metrics (chosen now) + +* **Primary:** pooled test AP (35–49), XGBoost, `live_computable` vs `all`. +* Secondary: test AP for 35–42 and 43–49; ROC-AUC; illicit F1 at the validation threshold; + per-step precision@20; the same for logistic regression and for `augmented`. +* Uncertainty: block bootstrap over test time steps (the repository's existing utilities), + paired between feature sets. + +## Caveats fixed in advance + +* **Not an untouched holdout.** Steps 35–49 were inspected in Phase 1, so every result is + exploratory. +* **No live validity.** Whatever the result, no model from this experiment is promoted to the + live monitor. It fails the Layer C gate by construction (`feature_schema` is not the live + schema, labels are 2016–2017 Elliptic attributions, and no live evaluation exists). +* A good restricted-feature score would mean only that simple per-transaction quantities + carried signal **for Elliptic's label definition in that era**, not that they identify + illicit activity today. + +## Commands + +```bash +chainwatch download # verified Elliptic++ CSVs +chainwatch --config configs/subset-live.yaml prepare +chainwatch --config configs/subset-live.yaml train --model xgboost +chainwatch --config configs/subset-live.yaml evaluate +# ... the same for logreg, configs/subset-augmented.yaml and configs/default.yaml +python scripts/feature_subset_report.py # comparison table + bootstrap CIs +``` diff --git a/docs/LIVE_FEATURE_SUBSET_RESULTS.md b/docs/LIVE_FEATURE_SUBSET_RESULTS.md new file mode 100644 index 0000000..543dca0 --- /dev/null +++ b/docs/LIVE_FEATURE_SUBSET_RESULTS.md @@ -0,0 +1,142 @@ +# Results: live-computable feature subset (exploratory) + +Protocol: [LIVE_FEATURE_SUBSET_PROTOCOL.md](LIVE_FEATURE_SUBSET_PROTOCOL.md), committed in +`6b16109` before any run. This report was written after the runs. All numbers come from +`reports/phase6/feature_subset/results.json`, produced by `scripts/feature_subset_report.py` +from the runs in `artifacts/runs*/` (git-ignored). The runs used the verified Elliptic++ CSVs, +seed 42, and the splits and grids unchanged from Phase 1. + +**Status: exploratory.** Steps 35–49 were inspected in Phase 1. These results do not +validate anything for live use. **No model from this experiment is promoted** (see the +end of this report). + +## Test-period results (labelled rows; unknown excluded) + +| Model | Features | AP 35–49 | AP 35–42 | AP 43–49 | ROC-AUC | F1 @ val threshold | mean P@20 per step | +|---|---|---|---|---|---|---|---| +| XGBoost | all (182) | **0.797** | 0.917 | 0.043 | 0.930 | 0.800 | 0.56 | +| XGBoost | augmented (17) | 0.610 | 0.755 | 0.034 | 0.879 | 0.603 | 0.51 | +| XGBoost | live-computable (16) | **0.646** | 0.792 | 0.028 | 0.885 | 0.639 | 0.51 † | +| LogReg | all (182) | 0.231 | 0.326 | 0.036 | 0.871 | 0.405 | 0.08 | +| LogReg | augmented (17) | 0.236 | 0.425 | 0.017 | 0.785 | 0.506 | 0.08 | +| LogReg | live-computable (16) | 0.223 | 0.399 | 0.018 | 0.787 | 0.491 | 0.07 † | + +† P@20 is tie-aware since v0.8 (0.5133 and 0.0727; `head(20)` gave 0.5100 and 0.0733). + +Prevalence (the AP of a random ranking): 0.065 for 35–49, 0.092 for 35–42 and 0.025 for 43–49. + +The re-run of the `all` setting reproduces the Phase 1 values exactly (AP 0.797, ROC-AUC 0.930, +F1 0.800). + +## Paired comparison (primary) + +ΔAP is subset minus `all`, computed on the same test transactions. The 95% intervals come +from a circular block bootstrap over test time steps (block length 3, 2,000 resamples, +seed 0). + +| Comparison | ΔAP 35–49 | 95% interval | share of resamples with Δ ≤ 0 | +|---|---|---|---| +| XGBoost: live-computable − all | **−0.151** | [−0.216, −0.089] | 1.00 | +| XGBoost: augmented − all | −0.187 | [−0.269, −0.113] | 1.00 | +| LogReg: live-computable − all | −0.008 | [−0.045, +0.058] | 0.60 | +| LogReg: augmented − all | +0.005 | [−0.041, +0.084] | 0.43 | + +## Hypotheses + +* **H1 supported.** Restricted to the 16 live-computable features, XGBoost ranks clearly + worse than with all 182 features. About 81% of the pooled AP remains + (0.646 / 0.797), well above prevalence. +* **H2 supported (descriptive).** Every model collapses from step 43 on (AP 0.017–0.043 + against a prevalence of 0.025). The restricted model is not more robust: 0.028 against + 0.043. On 43–49 the logistic models rank *worse than chance* (ROC-AUC 0.31 augmented, + 0.34 live-computable), and the XGBoost live-computable model's ROC-AUC is 0.55 with recall + 0.0 at its validation threshold. Illicit counts fall from 239 at step 42 to 24, 24, 5, 2, + 22, 36, 56 at steps 43–49 (prevalence 0.111 to 0.018); this matches the dark-market + shutdown Weber et al. (2019) report at step 43, which the data alone cannot confirm. +* Logistic regression does not differ measurably between feature sets. It is weak in every + setting, so most of the signal is non-linear. +* Dropping `out_txs_degree`, the future information, did not lower AP (0.646 against 0.610 + with it). Its absence therefore does not account for the gap to `all`. + +## Leakage and shortcut checks (XGBoost, live-computable) + +* **The missing-value pattern does not inflate test AP.** + * 324 test rows lack the augmented features, and none of them is illicit (Phase 1 noted + this pattern). The model does treat them distinctly: all get one identical score + (0.063, below the median licit score), so the pattern is learned. + * Because those rows are all negatives, it can only lower AP: complete rows give 0.6460 + against 0.6459 for all rows. +* **Validation AP of the selected model is 0.731**, below the test AP for 35–42 (0.792). + * Earlier working notes recorded validation APs of 0.97–0.98. Those values came from the + `all` grid, not from this subset. +* **Feature reliance (share of total gain, trees up to the early-stopping iteration).** + * Top features: `size` 0.46, `fees` 0.19, `num_output_addresses` 0.14, `out_BTC_min` 0.04, + `num_input_addresses` 0.04. + * Corrected in v0.8: the first version of this report published XGBoost's *mean* gain per + split over all trees, including the 50 trees after early stopping that prediction does + not use (it showed `fees` 0.08 and `num_input_addresses` 0.11). + * Every BTC-amount feature other than `fees` has a share below 0.04. + * The model mostly ranks transaction *shape* (`size` and the address counts: 0.64) and + the fee. + * Shape is exactly what changes most between 2016–2017 traffic (pre-SegWit, Elliptic's + label era) and 2026 traffic (vsize, SegWit and Taproot, batching). That gap is a reason + against transfer. + * Gain describes the model's behaviour, not causes. + +## What this does and does not show + +* It does show that simple per-transaction quantities ranked Elliptic's 2016–2017 *illicit* + label well above chance **in that era, in that dataset, before the step-43 shift**. +* It does **not** show that these quantities identify illicit activity in 2026 mempool + traffic. Five reasons: + * the labels are Elliptic's attributions; + * `size` and `in_txs_degree` are defined differently from the live features; + * the model collapses after the distribution shift at step 43; + * the test period is not an untouched holdout; + * no labelled live data exists to measure any of this. + +## Decision for Layer C + +**Rejected for promotion.** The models fail the supervised-layer gate (docs/RISK_ENGINE.md +§7): + +* their feature schema is not `live-features/2`; +* no time-separated independent evaluation on live data exists; +* the observed collapse at step 43 is the failure mode a live deployment would face. + +The live monitor's supervised layer keeps returning `NO_VALIDATED_MODEL`. What would change +this decision: + +* labels attributable to live transactions with their availability time; +* the live prevalence and label latency of those labels; +* a holdout recorded after the model is frozen; +* a pre-registered evaluation on that holdout, including calibration; +* a shadow-mode period (scores logged, never shown) whose results are reviewed; +* an external review of the label source. + +The gate (`risk/supervised.py`) only checks what a model card claims; the real safeguard is +that no loader for a live model exists (a card that passes the gate still abstains; v0.8.1 +fuzzing of malformed cards: all abstain). + +## Amendments after the runs (v0.8 independent re-audit) + +The protocol file is unchanged since its commit; these notes correct or sharpen it. + +* **What "pre-registered" can mean here.** The protocol was committed (6b16109, 10:22:52 UTC) + before the first run directory (10:23:50) and the results commit (10:31:53). That order + is visible only in this repository's history and the local file times, not to a third + party, and the hypotheses were written knowing the Phase 1 results. The bootstrap block + length, resample count and seed (3, 2,000, 0) were fixed in the report script after the + runs; the primary interval is stable for block lengths 1, 2 and 5 and other seeds + (from [−0.21, −0.10] to [−0.20, −0.085]). +* **`in_txs_degree` is not computable from one live transaction.** It equals the number of + parents present in the dataset within the same time step (true for all 202,804 rows; 27% + of rows have 0 although every transaction has inputs). It does not leak future + information (there are no cross-step edges). Dropping it costs ΔAP −0.022 + (95% [−0.075, +0.006]) in a scratch retrain. +* **`total_BTC` is resolvable:** it equals `out_BTC_total` in every row, and `fees` equals + in-total minus out-total in every row. +* **Independent recomputation:** every number in the tables above was recomputed from the + raw CSVs and saved predictions by an independent reviewer, and a scratch retrain + reproduced the XGBoost live-computable run exactly (AP 0.6459, max score difference 0.0). + diff --git a/docs/LIVE_ML_PROPOSAL.md b/docs/LIVE_ML_PROPOSAL.md new file mode 100644 index 0000000..bfa748f --- /dev/null +++ b/docs/LIVE_ML_PROPOSAL.md @@ -0,0 +1,109 @@ +# Proposal: a genuine live-data ML model (not implemented) + +Phase 5 collects live, observation-time features but **trains no model**, because live data +has no labels yet. This proposal describes how a properly evaluated model could be added. +It reuses the temporal-evaluation discipline from Phases 1–2: chronological splits, +explicit label latency, pre-registration, and a sealed holdout. + +## 1. Why the Elliptic++ models cannot be reused + +They were trained on 165 anonymised, publisher-standardised features of 2019-era +transactions, aggregated over the full graph of a two-week time step. None of these +features can be computed for a transaction seen in today's mempool, and the label +semantics ("illicit" per Elliptic's heuristics) do not transfer. Retraining is the only +honest route. + +## 2. Stage A (recommended first): a task with free, objective labels + +**Task:** for an unconfirmed transaction observed at time *t*, predict whether it confirms +within *k* blocks (for example k = 1, 3, 6), or whether it is replaced or evicted first. + +* **Labels arrive later, for free.** Re-query the collected txids after *k* blocks (or + subscribe to `mined` and `replaced` events) and store the outcome in a separate table + with its own timestamp. Features are never updated after `fetched_at`, but `fetched_at` + is not the first observation (see "Collector gaps" below), so the observation time + must be fixed explicitly. +* **The label latency is explicit:** a label for *t* becomes usable after *t + k* blocks. + This is exactly Phase 2's setting. +* **Baselines to beat:** the fee rate relative to the mempool's projected-block minimum fee + at time *t* (available from mempool.space `projected-block` data; the collector does + **not** record it yet), and logistic regression on fee rate. +* **Evaluation:** + * a rolling-origin backtest over days, with block bootstrap over time; + * calibration (reliability, ECE), because a probability of confirmation is useful only if + it is calibrated; + * analysis of fee-market regime shifts (fee spikes) as distribution shift. +* **Value:** it validates the pipeline, label joins and temporal evaluation end to end on + real data without any claims about crime. + +### Collector gaps to close before a Stage A study + +The current collector (Phase 5) was built for monitoring, not for this study: + +* **`confirmed_at_fetch` leaks the label.** It is the status at `fetched_at`, which can be + up to `max_queue_age_s` (300 s by default) after `first_seen`. For a "confirms within + *k* blocks of *t*" task, either exclude it from the features, or define *t* as + `fetched_at` (not `first_seen`) and count blocks from there. +* **No per-row feature-schema version.** Rows do not record which feature code produced + them; add a version column before collecting study data. +* **`fee_rate_outlier` is not reproducible from stored rows.** It depends on the + collector's in-memory rolling window (the last 500 fee rates), which is not persisted + and resets on restart. Exclude it, or persist the window statistic per row. +* **Retention is too short.** Defaults keep 7 days (and 20,000 rows locally, 50,000 rows + in `configs/live-cloud.yaml`); `minute_stats` keeps 24 h. A study of at least 4 weeks + needs these raised (and disk sized) for its duration. +* **Selection bias from drops.** Back-pressure drops, queue expiry and fetch failures + cluster in time (bursts, fee spikes, outages), so busy periods, the regimes of most + interest, are under-sampled. Persist per-minute drop and coverage counts for the + study period and report coverage by period. +* **No projected-block minimum fee** is recorded, so the main baseline cannot be computed + from collected data yet. + +## 3. Stage B: risk-related labels (only with careful sourcing) + +Possible label sources, all sparse, delayed and biased: + +| Source | Notes | +|---|---| +| OFAC SDN list (digital currency addresses) | public US-government data; addresses only; exposure is better expressed as a **rule** ("pays a listed address") than as a model | +| Public research datasets of ransomware payment addresses | check each licence; coverage is small and skewed toward known families | +| Public law-enforcement seizure announcements | very sparse; manual curation | +| Commercial attribution data | not zero-cost; licensing usually forbids redistribution | + +**Constraints before any model is trained:** +* **Labels are about addresses and events, not people.** No identity inference and no + wallet clustering presented as fact. +* **Positives are rare and found late.** Report precision at an analyst review budget + (as in Phase 2) and the base rate. Never report accuracy. +* **Unknown is not negative.** Unlabelled transactions are excluded or modelled as + positive-unlabelled data, the same rule as for Elliptic++'s "unknown" class. +* **Graph features need more API calls** (k-hop ancestors), which conflicts with the + zero-cost, rate-limited design. A self-hosted node with an indexer (mempool or electrs + on own hardware) would be needed. That is local and still free, but it is new + infrastructure, so it needs a separate decision. + +## 4. Protocol (applies to both stages) + +1. Freeze the feature set and code version and **pre-register** the splits, metrics and + decision rules before looking at the outcomes, and publish that protocol (a + timestamped commit or registry entry) so its timing can be verified. +2. Collect at least 4 weeks of observations. Reserve the **last week as a sealed holdout** + that is not inspected until the final evaluation. This avoids repeating Phase 1, where + the test period became exploratory. +3. Use rolling-origin evaluation with explicit label latency, report confidence intervals + from a time-block bootstrap, and include the negative results. +4. Publish a model card: data window, coverage (sample rate, fetch failures), known + biases, intended use, and "not for decisions about individuals". +5. Train offline, locally or in CI on GitHub's runners. **Never train on the Render + Free instance.** Serve only frozen artifacts through the existing registry pattern + (provenance and hashes), preferably in a pickle-free format. + +## 5. Stop conditions + +Do not ship a model if: +* it does not beat the fee-rate baseline outside the holdout's confidence intervals; +* its calibration error exceeds the agreed bound; +* label coverage is too small for stable estimates (for Stage B, fewer than about 100 + positive events in the holdout). + +Report the outcome either way. diff --git a/docs/LIVE_MONITOR.md b/docs/LIVE_MONITOR.md new file mode 100644 index 0000000..a0872a4 --- /dev/null +++ b/docs/LIVE_MONITOR.md @@ -0,0 +1,219 @@ +# Live Bitcoin monitor (Phase 5 MVP) + +A zero-cost pipeline that observes **real** Bitcoin mempool transactions through the public +mempool.space API, extracts observation-time features, stores a bounded window in SQLite +and streams it to a "Live monitor" tab. It is a data-engineering foundation for future +live-data ML. **It does not detect fraud and applies no model.** + +## 1. Operating modes + +| Mode | Data | Enabled by | Where | +|---|---|---|---| +| Historical research | Elliptic++ (real, 2019-era, anonymised features) | `configs/default.yaml` + your local download | replay tabs | +| Synthetic demo | random data in the Elliptic++ schema | `configs/demo.yaml`, `configs/public-demo.yaml` | replay tabs, public Render demo | +| Live Bitcoin monitor | real mempool observations from mempool.space | `configs/live.yaml` only (`live.enabled: true`) | "Live monitor" tab, `/v1/live/*` | + +* Live mode is **off** in every config except `configs/live.yaml`, including the public + demo. When it is off, every `/v1/live/*` route answers 404 `live_disabled`, and the tab + explains how to run it locally (tested in `tests/test_live_api.py`). +* The API process **never** contacts mempool.space. It only opens the collector's SQLite + file read-only (`mode=ro`). Collection is a separate process that you start explicitly. +* Labelling: + * replay tabs keep the synthetic banner; + * the live tab shows **REAL BITCOIN NETWORK DATA** only when the collector's source host is + `mempool.space`; + * any other source (for example `scripts/mock_mempool.py`) is shown as **LOCAL MOCK / + CUSTOM SOURCE: not real network data**. +* No Elliptic++ model is applied to live data. Those models use 165 anonymised features + that cannot be computed for new transactions (`docs/INFERENCE_CONTRACT.md`). + +## 2. Data source: verified contract + +mempool.space (and docs.mempool.space) is blocked from the environment where this was +built, so the contract was checked in **mempool's open-source backend** (`mempool/mempool`, +commit `4cf96d2`, 2026-10-13). The files used were: +* `backend/src/api/websocket-handler.ts`; +* `backend/src/mempool.interfaces.ts`; +* `backend/src/api/bitcoin/esplora-api.interface.ts`; +* the API docs data in `frontend/src/app/docs/api-docs/api-docs-data.ts`; +* the sample `nginx.conf`. + +| Item | Contract | +|---|---| +| WebSocket | `wss://mempool.space/api/v1/ws` | +| Subscribe | `{"track-mempool-txids": true}` (documented as the low-bandwidth substitute for `track-mempool`) | +| Event | `{"mempool-txids": {"sequence": int, "added": [txid], "removed": [txid], "mined": [txid], "replaced": [{"replaced": txid, "by": txid}]}}`, sent on mempool updates to subscribed clients; other keys may share a frame | +| Keepalive | the server answers `{"action": "ping"}` with `pong`. The collector relies on WebSocket protocol pings (20 s) plus a 90 s staleness watchdog | +| Server-side drops | the server terminates clients that send oversized messages or read too slowly (`MAX_BUFFERED_AMOUNT`) | +| Details | `GET https://mempool.space/api/tx/{txid}` (Esplora schema): `txid, version, locktime, size, weight, fee, vin[{txid, vout, prevout{value, scriptpubkey_type}, sequence, witness}], vout[{value, scriptpubkey_type, scriptpubkey_address?}], status{confirmed, block_height?, block_time?}` | +| Rate limits | not published for the public instance. The sample `nginx.conf` in the repository limits the API zone to **200 requests/min per IP** and returns **429** above it. The collector defaults to **30 requests/min** and pauses on 429 for `Retry-After` (60 s if the header is absent) | + +Unsupported assumptions avoided: +* there is no historical backfill; +* full transaction streams (`track-mempool`) are not used; +* the collector does not assume every announced transaction can be fetched. A 404 + (evicted, replaced or not yet indexed) is recorded as a failed observation. + +## 3. Pipeline + +``` +mempool.space WS ─► parse + validate txids ─► dedupe (LRU 200k) ─► sample (hash < p) + (reconnect: exp. backoff + full jitter, │ + 90 s staleness watchdog, pings) ▼ + bounded queue (200; drop newest when full, skip > 300 s old) + │ + N=2 workers ─► token bucket (30/min, burst 5; 429 ⇒ pause) ─► GET /api/tx + │ (10 s timeout) + features + rule-based flags ─► SQLite (WAL, INSERT OR IGNORE, 20k rows) + │ + FastAPI (read-only) ─► /v1/live/* + SSE ─► React "Live monitor" tab +``` + +| Concern | Mechanism (`src/chainwatch/live/collector.py`) | +|---|---| +| Reconnection | exponential backoff with full jitter (1 s base, 60 s cap), reset after a working stream | +| Health | `connected` / `reconnecting` / `disconnected` state, last message time, sequence, reconnect count; heartbeat to SQLite every 5 s. The API reports `disconnected` when the heartbeat is older than 15 s | +| Graceful shutdown | SIGINT/SIGTERM set a stop event; tasks are cancelled, the final state `stopped` and the counters are flushed, and the HTTP client is closed | +| Timeouts | 15 s WebSocket handshake, 10 s per REST request | +| HTTP 429 | `rate_limited` counter, token bucket paused for `Retry-After` (capped at 600 s), the observation is stored as failed and not retried (no amplification) | +| Backpressure | bounded `asyncio.Queue`; when it is full, new txids are counted as `dropped_backpressure` | +| Sampling | deterministic SHA-256 hash of the txid below `sample_rate` (default 5%): reproducible and independent of fee or arrival order | +| Idempotency | dedupe LRU plus `store.has(txid)` before fetching plus `UNIQUE(txid)` with `INSERT OR IGNORE` (safe across restarts) | +| Memory | bounded dedupe set, queue, fee-rate window (500), at most 25 stored outputs and input references per transaction; SQLite retention of 20k rows and 24 h of per-minute counters | +| Metrics | received, duplicates, already stored, invalid txids, malformed frames, not sampled, queued, dropped, expired, gone before fetch, fetched, failed, not found, rate limited, timeouts, malformed payloads, upstream (5xx) errors, internal errors, removed, mined, replacement pairs, connects, reconnects, stale reconnects, sequence gaps | +| Counter semantics | From mempool's backend source: `removed` lists every txid that left the mempool in one poll (replacements, conflicts, evictions, expiry) but **not** mined ones; `mined` arrives with each block; each `replaced` pair's old txid is also in `removed`, and one old txid can appear in several pairs (A→B, then A→C and B→C). So `removed` and `replacement_pairs` overlap and are not separate outcomes: equal counts in a short window without a block simply mean every removal was a replacement. Removed or mined txids still queued are not fetched (`gone_before_fetch`) | + +## 4. Features (`src/chainwatch/live/features.py`) + +Only information available when the details are fetched is used, and nothing is +back-filled after that moment: +* `confirmed_at_fetch` is the status at fetch time; +* `first_seen` is the time this collector first received the txid (not the network's + first-seen time). + +| Group | Fields | +|---|---| +| Identity and timing | `txid`, `first_seen`, `fetched_at`, `confirmed_at_fetch` | +| Size and fee | `size`, `weight`, `vsize` (= ⌈weight/4⌉, BIP141), `fee`, `fee_rate` (sat/vB) | +| Structure | `version`, `locktime`, `locktime_kind` (none/height/time), `n_inputs`, `n_outputs`, `n_parent_txs`, `segwit`, `input_types`, `output_types` | +| Values | `output_values` (first 25), `max_output_value`, `output_value_total` (**includes change; not a payment amount**), `input_value_total` (only when every prevout value is known) | +| Signals | `rbf_signal` (BIP125: some input sequence ≤ 0xfffffffd; under full-RBF node policies replaceability does not depend on it), `n_op_return`, `n_dust_outputs` (< 546 sat, a heuristic) | +| Relationships | `input_refs` (`parent_txid:vout`, first 25): observable spends only. **No wallet clustering, ownership or identity inference** | + +**Rule-based indicators** (`INDICATORS`): `rbf_signal`, `high_fan_out` (≥ 50 outputs), +`consolidation` (≥ 50 inputs into ≤ 2 outputs), `dust_output`, `op_return`, `timelocked`, +`nonstandard_version` (not 1/2/3), and `fee_rate_outlier` (≥ 10× the rolling median of the +last 500 fetched, needing at least 20 values). They describe observable properties. They +are not risk scores, fraud predictions or probabilities, and they say nothing about +legality. + +## 5. API (read-only; `src/chainwatch/serving/live_api.py`) + +| Route | Returns | +|---|---| +| `GET /v1/live/status` | connection state, collector heartbeat and counters, coverage, source URL and whether it is the public mempool.space service, indicator descriptions | +| `GET /v1/live/transactions` | paged list; `limit≤200`, `sort` ∈ {id, first_seen, fee_rate, fee, vsize, n_inputs, n_outputs}, `order`, `min_fee_rate`, `max_fee_rate`, `flag`, `outcome` ∈ {fetched, failed, all} | +| `GET /v1/live/transactions/{txid}` | full features, explorer link, flag descriptions; 400 on a malformed txid, 404 if not observed | +| `GET /v1/live/stats?window_minutes=` | per-minute counters, fee-rate and vsize quantiles, fee-rate histogram, flag counts, failure reasons | +| `GET /v1/live/findings` | assessed transactions with a finding (P1–P4), newest first, one page at a time: `limit≤200`, `type` ∈ {source_match, relation, anomaly, insufficient_evidence}, `authority`, `priority`, `max_priority`, `since`/`until` (evaluated at, epoch seconds) or `hours≤720`, `cursor` (from `page.next_cursor`; `before_id` still accepted). `insufficient_evidence` lists assessments that are not findings. Details: [RISK_ENGINE.md §9](RISK_ENGINE.md#paged-findings-and-alert-queue) | +| `GET /v1/live/alerts` | the investigation queue, one page at a time: `limit≤200`, `status` ∈ {open, new, under_review, dismissed, resolved, insufficient_evidence}, `type` ∈ {source_match, retrospective, relation, anomaly}, `authority`, `priority`, `max_priority`, `since`/`until` or `hours` (last seen), `sort` ∈ {triage, newest}, `cursor`. Read-only | +| `GET /v1/live/events` | SSE: `tx` per new observation (with `id:`, resumable through `Last-Event-ID` or `?since=`) and `status` every 5 s. At most 20 streams, each closed after 300 s (browsers reconnect) | + +## 6. Run it locally (no paid resources) + +```bash +pip install -e ".[dev]" +(cd frontend && npm ci && npm run build) +chainwatch --config configs/demo.yaml demo-setup # synthetic replay tabs (once) +chainwatch --config configs/live.yaml live-collect # terminal 1: real mempool data +chainwatch --config configs/live.yaml serve # terminal 2: http://127.0.0.1:8000 +``` + +* **Bounded live check:** `chainwatch --config configs/live.yaml live-collect --duration + 120 --max-fetches 20 --db /tmp/check.sqlite`. It prints the counters; `received > 0` and + `fetched > 0` mean real ingestion worked. +* **Offline UI development** (labelled as a mock in the UI): + 1. run `PYTHONPATH=src python scripts/mock_mempool.py`; + 2. point `live.ws_url` at `ws://127.0.0.1:8999/api/v1/ws` and `live.rest_base` at + `http://127.0.0.1:8999/api` in a copy of `configs/live.yaml`. + +## 7. Verification status + +| Check | Result | +|---|---| +| Unit and integration tests (local mocks) | protocol, malformed frames, features, Bitcoin semantics, dedupe, sampling, backoff, token bucket, 429, backpressure, idempotent storage and retention, read-only reader, reconnection after a server drop, stale-stream reconnect, unreachable-server backoff, end-to-end WS → REST → SQLite, all `/v1/live` routes, SSE ordering, resume and client cap, mode isolation, frontend helpers | +| End-to-end with real processes and a **local mock** source | collector CLI → SQLite → `serve` → dashboard (§8) | +| **Real mempool.space ingestion** | **not verified.** From the build environment, every WebSocket attempt was refused by the egress proxy (`InvalidProxyStatus: proxy rejected connection: HTTP 403`); 0 real txids were received and 0 details fetched. The collector then backed off and stopped cleanly. Run the bounded live check above on a normal internet connection to verify | + +### Real-network verification checklist (still to be run; v0.8.1) + +The build environment's egress proxy refuses mempool.space (HTTP 403 on 2026-10-23 as well), +so the current risk pipeline has only run against the local mock. On a normal connection +(Windows machine or the VM), run a bounded, polite check with the shipped limits: + +```bash +DB=data/live/real-check.sqlite +chainwatch-live --config configs/live.yaml indicators update --source ofac-sdn --fallback ofac-sdn-mirror --db $DB +chainwatch-live --config configs/live.yaml collect --force --duration 3600 --db $DB +chainwatch-live --config configs/live.yaml report --hours 1 --db $DB > real-check-report.json +chainwatch-live --config configs/live.yaml alerts list --db $DB > real-check-alerts.json +``` + +Record, from the final `collect` output (counters) and the report: + +| What | Counter / field | +|---|---| +| Received txids / sampled / queued | `received`, `not_sampled`, `queued` | +| Enrichment attempts, successes, failures | `fetched`, `failed`, `not_found`, `rate_limited`, `timeouts`, `upstream_errors`, `malformed_payloads` | +| Retries | `retries_scheduled`, `retries_succeeded`, `retries_exhausted`, `retries_dropped` | +| Assessed records | `risk_assessed`, `risk_errors`, `layer_errors` | +| Source matches / relations / anomalies | `screening_matches`, `graph_relations`, `anomalies_strong`, `anomalies_notable` | +| Unavailable assessments | feed rows with `risk_state` `insufficient_evidence` or `failed` | +| Coverage | `availability` and `outages` in the report (`sequence_gap` includes re-sync stretches) | + +Pass criteria: real txids received, at least one detail fetched and assessed, every fetched +row with a risk record, no traceback, a clean stop. The anomaly layer needs 1,000 fetched +transactions before it reports anything (`INSUFFICIENT_BASELINE` until then: about 83 +minutes at 12 fetches per minute; at the local config's rate, less). A successful run shows +that the pipeline works on real observations; it says nothing about fraud-detection +accuracy, and a source match is a listing, not proof of wrongdoing. + +## 8. Measurements (local mock, not mempool.space) + +`scripts/live_load_test.py`, 180 s, mock announcing **20 tx/s** (above typical mainnet +volume). These measurements used the earlier 10% sample rate; the default is now 5%: + +| Measure | Result | +|---|---| +| Announced → sampled | 3,600 → 357 (9.9% at `sample_rate` 0.1) | +| Outgoing REST requests | 94 in total; **max 34 in any 60 s window** (cap: 30/min + burst 5) | +| Backpressure | 61 sampled txids dropped (queue full); none expired | +| Memory | peak RSS 33.8 MiB for the whole Python process (+1.8 MiB during the run) | +| SQLite | 2.4 MB, mostly WAL pre-allocation, for 94 rows | +| Reconnects / errors | 0 / 0 | + +At 10% sampling, announcements above about 5 tx/s exceed the 30/min budget. That is why +the default sample rate is now **5%** (about 18 requests/min at 6 tx/s). Real mainnet rates +were not measured here; check the `received` and `dropped` counters in `/v1/live/status`. + +## 9. Known limitations + +* **Partial coverage by design:** only transactions announced while the collector is + connected, only a hash sample of them, and only those still fetchable. Statistics + describe this sample, not the network. +* **Single public source:** mempool.space availability, its view of the mempool and its + unpublished rate limits all apply. Results can differ from another node's mempool. +* `first_seen` is the collector's receipt time. Network-wide first-seen time is + unavailable. +* **Replacements and confirmations after the fetch are not tracked** (by design, so that + no post-observation information leaks into features). `removed`, `mined` and `replaced` + events are counted, and used only to skip fetching txids that already left the mempool. +* **Prevout-derived fields** depend on the REST payload. Values that are missing make + `input_value_total` unknown. +* **Indicator thresholds are conventions** (dust 546 sat, fan-out 50, …), not tuned or + validated. +* **No labels exist for live data**, so no model can be evaluated yet + (`docs/LIVE_ML_PROPOSAL.md`). +* SQLite with one writer suits one collector. Several collectors would need a different + store. A single always-on hosted collector, with an authenticated edge API in front of + the file, is described in [LIVE_CLOUD.md](LIVE_CLOUD.md). diff --git a/docs/PHASE2_PROTOCOL.md b/docs/PHASE2_PROTOCOL.md index 2bac42e..734b42c 100644 --- a/docs/PHASE2_PROTOCOL.md +++ b/docs/PHASE2_PROTOCOL.md @@ -1,8 +1,14 @@ # Phase 2 protocol: temporal robustness and adaptive retraining -**Status: written and committed before any Phase 2 experiment was run.** The git history -of this file is the record of what was decided in advance. Any later change is listed -under "Deviations" at the end, with its reason. +**Status: written before the Phase 2 runs, according to the author's record. This +repository cannot verify that timing.** The pre-release history was not published: the +file first appears in commit `7caf60f`, the same commit that adds the Phase 2 results, +and the result directories it describes (`dev_L1_20261012-213405`, +`confirm_L1_20261012-222153`) carry earlier timestamps than that commit. Read +"pre-registered" in these documents as "fixed before the runs (author's record, not +independently verifiable)". Changes the author made after the runs started are listed +under "Deviations" at the end, with their reasons. A future study should publish its +protocol (for example as a tagged commit or a timestamped registry entry) before running. ## 0. Audit of Phase 1 (summary) @@ -33,8 +39,15 @@ Methodological weaknesses that Phase 2 must address or document: ## 1. Prediction-time assumptions * **Features.** All features of transactions in step *s*, including neighbourhood - aggregates within *s*, become available at the end of step *s*. That is when step *s* - is scored. There are no cross-step edges, so no future structure enters. + aggregates within *s*, are assumed to be available at the end of step *s*. That is + when step *s* is scored. The published edge list has no cross-step edges, so the edges + we use carry no future structure. **Caveat:** the 72 aggregate features were computed + by the publisher over a neighbourhood that is not fully documented; they cannot be + verified to use only within-step, pre-step-end information. A partial check is + possible: recompute one-hop aggregates (mean, max, min, std of the local features over + in- and out-neighbours) from the published edge list and test how closely they match + the published aggregate columns. A close match would support the within-step reading; + a poor match would leave the provenance open. This check has not been run. * **Publisher standardisation.** Local and aggregate features were standardised by the publisher using all 49 steps. For XGBoost this leaks nothing: standardisation is a strictly increasing per-feature map, and histogram tree splits are invariant to such @@ -90,7 +103,8 @@ column subsampling only. They measure training stochasticity, not data uncertain prevalence is 0.109, the Phase 1 training prevalence); mean per-step AP; P@K and R@K per step for K ∈ {10, 20, 50, 100}; detections when ranking **all** transactions with unknowns as non-detections (a conservative lower bound); per-step detection rate; -sub-period results (35–42 versus 43–49); fit time and number of fits. +sub-period results (35–42 versus 43–49; the 42/43 boundary was taken from the Phase 1 +per-step results, that is, from inspecting the test period); fit time and number of fits. **Selection rule (dev):** within each family, choose the parameter with the highest seed-averaged pooled AP on dev. Ties within 0.002 go to the cheaper option (fewer fits, @@ -112,6 +126,11 @@ then the larger window or longer half-life). The selection is written to * With only 15 scored steps and a regime change inside the confirm period, intervals will be wide. A difference is called **robust** only if its 95% interval excludes 0 in both the dev and confirm backtests and the sign holds in both sub-periods of confirm. +* Caveat on the dev half of this rule (added after the runs): for periodic, sliding and + recency the dev interval is computed for the parameter that won the dev selection, so + it is subject to a winner's curse (the selected parameter's dev effect is biased + upward). Static and expanding have no tuned parameter and are not affected. The confirm interval is the + meaningful half of the rule; the dev half is a weaker check than it looks. ## 6. Distribution-shift diagnostics @@ -137,8 +156,9 @@ Computed by `chainwatch shift`, using the Phase 1 static model and the data: ## Deviations -All deviations are listed here. None of them changed a pre-registered metric, split, -strategy grid, selection rule or seed set. +All deviations the author recorded are listed here. According to that record, none of +them changed a pre-specified metric, split, strategy grid, selection rule or seed set +(see the status note at the top: this cannot be checked from the published history). 1. **Time-proxy features (not pre-registered; exploratory).** The first shift-diagnostic run produced a domain-classifier AUC of 1.000 for *every* step, including steps inside @@ -157,7 +177,7 @@ strategy grid, selection rule or seed set. first and last steps. Block length and resample count are as pre-registered. 3. **Implementation-only changes:** a vectorised, exact pooled-AP computation for bootstrap replicates (tested against explicit concatenation), and a configurable - confirm sub-period boundary (`confirm_split_after: 42`, the pre-registered 35–42 / - 43–49 split). + confirm sub-period boundary (`confirm_split_after: 42`, the 35–42 / 43–49 split + fixed before the Phase 2 runs, itself chosen from the Phase 1 per-step results). 4. **Operational:** the first shift-diagnostic run was killed by a 2-hour tool time limit and was re-run in full. diff --git a/docs/PORTFOLIO.md b/docs/PORTFOLIO.md index d8bb311..ab87474 100644 --- a/docs/PORTFOLIO.md +++ b/docs/PORTFOLIO.md @@ -9,25 +9,26 @@ business impact**; do not add any. - Built a leakage-guarded temporal ML pipeline (Python, scikit-learn, XGBoost) on 204k Bitcoin transactions from the Elliptic++ dataset. Per-time-step evaluation exposed a post-shift collapse (AP 0.92 → 0.04) that a pooled metric (AP 0.80) hid. -- Designed and pre-registered a rolling-origin backtest of 5 retraining strategies with - explicit label latency and block-bootstrap confidence intervals. Retraining as labels - arrive raised late-period AP from 0.05 to 0.46 (+0.41, 95% CI 0.16–0.62); reported as - exploratory, together with negative results. +- Designed a rolling-origin backtest of 5 retraining strategies with explicit label + latency and block-bootstrap confidence intervals, with the protocol written before the + runs. Retraining as labels arrive raised pooled AP over test steps 35–49 by +0.085 + (95% CI 0.024–0.229), mostly after the regime change (late-period AP 0.05 → + 0.46); reported as exploratory, together with negative results. - Shipped a FastAPI and React/TypeScript replay service that reproduces research predictions exactly (234,596 scores, max deviation 0.0), backed by a provenance-checked - model registry, TreeSHAP explanations, 261 automated tests, CI on Linux and Windows, and + model registry, TreeSHAP explanations, 350+ automated tests, CI on Linux and Windows, and a hardened Docker demo (read-only, non-root, rate-limited, hash-locked dependencies). Shorter variants: - "Temporal-drift study and replay service for illicit Bitcoin transaction ranking (XGBoost, FastAPI, React, Docker); exact research-to-serving reproducibility." - "Found and quantified a regime-change failure (AP 0.92 → 0.04) with leakage-safe - backtesting; retraining under label delay recovered AP to 0.46 (exploratory)." + backtesting; retraining under label delay recovered late-period AP to 0.46 (exploratory)." ## GitHub repository description (≤ 350 characters) > Leakage-aware ranking of illicit Bitcoin transactions under temporal distribution shift -> (Elliptic++): pre-registered retraining backtests with label latency, plus a FastAPI + +> (Elliptic++): protocol-first retraining backtests with label latency, plus a FastAPI + > React replay service that reproduces research scores exactly. Synthetic Docker demo. Topics: `machine-learning`, `distribution-shift`, `concept-drift`, `temporal-validation`, @@ -39,22 +40,23 @@ Topics: `machine-learning`, `distribution-shift`, `concept-drift`, `temporal-val ChainWatch is my end-to-end ML engineering project on the public Elliptic++ Bitcoin dataset. I designed a leakage-safe chronological evaluation and found that a strong XGBoost model (AP 0.80 overall) collapsed after a regime change (AP 0.92 → 0.04). I then -pre-registered a backtest of retraining strategies under delayed labels: retraining -recovered late-period AP to 0.46, which I report as exploratory because no untouched -holdout remained. I shipped the research models as a FastAPI and React replay service whose -scores match the research predictions exactly (234,596 of them), with 265 tests, CI on -Linux and Windows, a hardened Docker demo on synthetic data, and a security review that -found and fixed 18 issues. The project taught me to treat evaluation design, label +wrote a protocol for, and ran, a backtest of retraining strategies under delayed labels: +retraining improved pooled AP modestly over the whole later period and recovered +late-period AP to 0.46, which I report as exploratory because no untouched holdout +remained. I shipped the research models as a FastAPI and React replay service whose +scores match the research predictions exactly (234,596 of them), with 350+ automated +tests, CI on Linux and Windows, a hardened Docker demo on synthetic data, and a security +review that found and fixed 18 issues. The project taught me to treat evaluation design, label availability and training/serving consistency as engineering problems, not afterthoughts. ## Portfolio website summary -**ChainWatch: what happens to a fraud-style model when behaviour changes?** +**ChainWatch: what happens to an illicit-transaction ranking model when behaviour changes?** ChainWatch is a three-phase project on the public Elliptic++ Bitcoin dataset. First, I built a strictly chronological evaluation that never treats unlabelled transactions as legitimate. It showed that a strong XGBoost model, which looks good on average, collapses -after a regime change in the data. Second, I pre-registered and ran a backtest of +after a regime change in the data. Second, I wrote a protocol for, and ran, a backtest of retraining strategies that only use labels available at prediction time. Retraining recovered much of the lost ranking quality, but only once new labels arrived, and less when labels were slower. Third, I turned the research models into a replay application: @@ -73,16 +75,18 @@ holdout, labels are heuristic, and the system does not score live transactions. much that matters. - **Method:** chronological evaluation with leakage guards; distribution-shift diagnostics (prior, covariate, class-conditional, within-period learnability); a - pre-registered rolling-origin backtest with label latency, multiple seeds and a - time-step block bootstrap. + rolling-origin backtest, with its protocol written before the runs, label latency, + multiple seeds and a time-step block bootstrap. - **Findings:** XGBoost AP fell from 0.92 to 0.04 after a regime change. Ranking quality - itself dropped (ROC-AUC 0.97 → 0.70), not just prevalence. Retraining as labels arrived - raised late-period AP to 0.46 (exploratory). There was no gain before the shift, and - the gain shrank with slower labels. + itself dropped (ROC-AUC 0.97 → 0.69), not just prevalence. Retraining as labels arrived + raised pooled AP by +0.085 over steps 35–49 and late-period AP to 0.46 (exploratory). + Before the shift the picture was mixed: +0.16 AP on the dev steps 20–34, but only + +0.008 to +0.016 on 35–42, where the static model was already near its ceiling. The + gain shrank with slower labels. - **Engineering:** FastAPI service with a versioned, provenance-checked model registry; exact research-to-serving reproducibility (234,596 scores); React/TypeScript dashboard; - 265 tests including leakage canaries; CI on Linux and Windows; hardened Docker demo on - synthetic data. + 350+ automated tests including leakage canaries; CI on Linux and Windows; hardened + Docker demo on synthetic data. - **Stack:** Python, pandas, scikit-learn, XGBoost, FastAPI, pydantic, React, TypeScript, Recharts, Docker, GitHub Actions. diff --git a/docs/RELEASE_READINESS.md b/docs/RELEASE_READINESS.md index 1573322..cbefeb4 100644 --- a/docs/RELEASE_READINESS.md +++ b/docs/RELEASE_READINESS.md @@ -107,7 +107,7 @@ Verified before pushing (commands in §6): guide. Until the repository with that name exists, the CI badge shows as broken. - **Description:** > Leakage-aware ranking of illicit Bitcoin transactions under temporal distribution - > shift (Elliptic++): pre-registered retraining backtests with label latency, plus a + > shift (Elliptic++): retraining backtests with label latency, plus a > FastAPI + React replay service that reproduces research scores exactly. Synthetic > Docker demo. - **Topics:** `machine-learning`, `distribution-shift`, `concept-drift`, diff --git a/docs/RESULTS.md b/docs/RESULTS.md index e2f7da1..545322e 100644 --- a/docs/RESULTS.md +++ b/docs/RESULTS.md @@ -55,7 +55,11 @@ For XGBoost with all features: | 35 to 42 | 914 | 0.092 | 0.917 | 0.852 | | 43 to 49 | 169 | 0.025 | **0.043** | **0.018** | -After step 42, every model is close to random. The timing coincides with the regime +After step 42, every model degrades sharply, though not uniformly to chance. For +XGBoost/all, per-step AP is 0.007–0.049 at steps 43, 44, 45 and 47 (prevalence +0.004–0.026), and 0.18–0.23 at steps 46, 48 and 49 (prevalence 0.003–0.12), against +0.77–0.99 at steps 35–42; per-step ROC-AUC on 43–49 is 0.62–0.94 +(`reports/baseline_per_time_step.csv`). The timing coincides with the regime change that Weber et al. (2019) observed in the original Elliptic data and attributed to a dark-market shutdown; our data cannot confirm that cause. Better feature sets do not help, because all six models collapse together. This motivated the Phase 2 question of @@ -72,8 +76,8 @@ trend but do not establish one. ### 5. Investigation-budget view With 20 reviews per two-week window, XGBoost/all averages a precision of 0.56 across the -15 test steps. It is near 1.0 for steps 35 to 42 and near 0 afterwards (mean per-step -P@20 for LR/all: 0.08). +15 test steps. It is 1.0 at every step from 35 to 42 and 0.00–0.25 afterwards (0 at +three of the seven steps: 43, 45 and 47). Mean per-step P@20 for LR/all is 0.08. ### 6. Latency All models score a transaction in single-digit milliseconds in-process (p50 2 to 6 ms diff --git a/docs/RISK_DATA_FEASIBILITY.md b/docs/RISK_DATA_FEASIBILITY.md new file mode 100644 index 0000000..4167401 --- /dev/null +++ b/docs/RISK_DATA_FEASIBILITY.md @@ -0,0 +1,341 @@ +# Risk data feasibility: sources, labels, licences and the supervised-learning decision + +**Research summary for ChainWatch's risk intelligence** (2026-10-14). It decides what each +detection layer can honestly be built on: + +| Layer | Decision | Basis | +|---|---|---| +| A. Source-backed screening | **Build**: exact address matches against OFAC SDN (official XML; a third-party nightly extraction as fallback) | public-domain, versioned, verified on the real 2026-01-30 file (section 3) | +| B. Behavioural anomalies | **Build**, unsupervised and interpretable; no labels needed or claimed | docs/RISK_ENGINE.md section 6 | +| C. Supervised risk model | **Not feasible for live scoring** with any legitimate public data today. Offline diagnostic only (docs/LIVE_FEATURE_SUBSET_PROTOCOL.md) | decision gate, section 2 | + +Evidence tags: **[local]** checked from this repository's build environment by downloading the +data (via raw/media.githubusercontent.com); **[search]** from search-result snippets of the +cited page (Kaggle, UCI, Zenodo, arXiv, elliptic.co, treasury.gov and chainabuse were not +reachable from the build environment); **unverified** where no source confirmed a claim. +Re-check licences and terms before relying on them. + +Researched on 2026-10-14 for two uses: (A) exact-address risk screening, and (C) a supervised +classifier whose features ChainWatch can compute for **live, sampled mempool transactions** at +observation time. The live features are those in `src/chainwatch/live/features.py`: one +Esplora tx JSON gives fee, vsize/weight, fee rate, n_in/n_out, input/output script types, +output values, prevout addresses/values, locktime, nSequence/RBF, OP_RETURN and dust counts, +and parent txids. There is no address history, no multi-hop graph and no clustering. + +How to read the evidence tags: +* **[local]** I downloaded and checked the data myself from this sandbox, via raw/media.githubusercontent.com. +* **[search]** The claim comes from a web-search snippet of the cited page. Kaggle, UCI, Zenodo, arXiv, elliptic.co, treasury.gov and chainabuse were unreachable by curl, and WebFetch could not resolve them. +* **unverified** No source confirmed the claim. + +## 1. Comparison matrix + +| Source | What is labelled | Level | Ground truth from | Timestamps | Unknown class? | Features reproducible from public chain at prediction time? | Live-compatible with ChainWatch's sampled mempool features? | Licence / MIT-repo use | Size / compute | Known biases | +|---|---|---|---|---|---|---|---|---|---|---| +| **Elliptic (2019)** [E1–E5] | tx illicit / licit | tx | Elliptic's attribution of tx to entities (scams, malware, ransomware, darknet...) vs licit services, details unpublished [E3] | 49 anonymised ~2-week steps, no dates [E4] | **Yes**, 77% unknown (4,545 illicit, 42,019 licit of 203,769) [E3] | **No.** 165 anonymised, standardised features (local + 1-hop aggregates); construction not disclosed and reverse-engineered only partially by third parties [E5] | **No** | Kaggle lists **CC BY-NC-ND 4.0** [search, E1]: non-commercial, no derivatives. **Download by user only; commit nothing** | 203,769 nodes / 234,355 edges [E3]; Elliptic's own CSV size unverified (Elliptic++'s superset txs_features.csv is 694.8 MB [local]); laptop-scale | Regime shift at step 43 (attributed to darknet-market closures, AML tightening and the 2018–19 bear market [E5, arXiv 2604.19514]): ChainWatch measured AP 0.917 → 0.043 (README). Split leakage reported [E5]. Labels are one vendor's heuristic. 2016–2017 era, no SegWit/Taproot | +| **Elliptic++ (git-disl, KDD'23)** [P1–P3] | tx (as Elliptic) **plus wallet addresses** illicit / licit / unknown | tx + address | tx labels from Elliptic; address labels derived from them (method in paper, unverified here) | 49 steps; address features include `first/last_block_appeared_in` (block heights, e.g. 439,586–485,959 in sample rows) [local] | **Yes.** Actors: 14,266 illicit, 251,088 licit, 557,588 unknown (822,942 addresses) [local, P1] | tx: **No** (Elliptic's anonymised features + 17 raw augmented). Address: **partly**: 56 interpretable features (BTC sent/received, fees, lifetimes, tx counts) with **real addresses** [local], but computed over the dataset's tx subset and time window, not the full chain | **No** for tx. Address features would need full address history (many API calls), which the sampled collector does not have | **No LICENSE file** (raw LICENSE 404, [local]); inherits Elliptic's terms. **Download by user only** (ChainWatch already does this, docs/DATASET.md) | LFS sizes [local]: txs_features 694.8 MB, wallets_features 606.5 MB, AddrAddr edges 200.6 MB, wallets_classes 30.4 MB (SHA-256 4e5132c9…); ~1.6 GB total; laptop-scale with care | As Elliptic. **Only `1…`/`3…` addresses, 0 bech32** [local], so script-type distribution differs entirely from 2026 mempool. **2 OFAC-listed addresses are in Elliptic++ labelled *unknown*** (`19D1iGzDr7FyAdiy3ZZdxMd6ttHj1kj6WW`, `1EYitrwBYNWuTBcjZFbEUdqHppe2raLpaF`) [local]: unknown ≠ licit | +| **Elliptic2 (Elliptic + MIT-IBM, 2024)** [L1–L3] | connected subgraphs "suspicious" (laundering-like) vs licit | **subgraph** of Elliptic address clusters | Elliptic's proprietary attribution / clustering [L1] | Unverified whether usable dates are released | Background graph is unlabelled | **No.** Nodes are Elliptic's proprietary clusters; cluster→address mapping and clustering cannot be reproduced (unverified whether addresses are released) | **No** | Kaggle reportedly **CC BY-NC-ND 4.0** [search, L2]. **Download by user only** | 49.3 M nodes, 196 M edges, 121,810 labelled subgraphs (119,092 licit, 2,718 suspicious) [search, L3]; ~26 GB [search]; needs a large-RAM box or graph DB | One vendor's labels; 2.2% positives; subgraph task does not map to single-tx scoring | +| **BitcoinHeist (UCI 526)** [H1–H2] | address-day rows: ransomware family vs "white" | address × 24 h window | Montreal, Princeton, Padua ransomware studies [H1] | Year + day-of-year per row (2009–2018) [H1] | **Yes, de facto**: authors say they "do not know if all white addresses are in fact not related to ransomware" [H1] | **Partly.** income, neighbors, weight, length, count, loop are defined on a daily graph with edges < 0.3 BTC filtered [H1]; recomputable only with a full-chain daily graph (BlockSci/node), not from one tx | **No.** Needs the full 24 h graph around the address, and "length"/"loop" need multi-hop chains | **CC BY 4.0** [search, H1]. Could be committed with attribution, but 2.9 M rows is too big; download by user | 2,916,697 rows, 10 cols [H1]; laptop-scale. Ransom/white split ~41 k / 2.88 M (unverified exact) | ≤2018; heavy Locky/CryptoLocker skew; 4 addresses with conflicting labels [search, H3]; the 0.3 BTC filter defines the population | +| **Paquet-Clouston, Haslhofer, Dupont (2019)** [R1–R3] | ransomware payment addresses (seed + expanded clusters) | address (seed); cluster (expanded) | APWG feed, VirusTotal user, blogs, news [local, R1] | Paper analyses payments 2013–mid-2017 [R2]; seed CSV has no dates [local] | No negatives at all (positives only) | Seed addresses: yes as **exact matches**. Expansion uses multi-input clustering in GraphSense [R1] | Only as an **exact-match list** (A), not as model training data | Zenodo **CC BY 4.0** [search, R3]. GitHub repo has no LICENSE (404) [local]. A CC BY seed list could be committed with attribution, but bundling stale ransomware addresses has little value | 7,222 seed rows, 67 families [local]; Zenodo ~113 MB [search] | **97.5% Locky (7,038) from APWG** [local]. 11 strings are not Bitcoin mainnet (`2c…`, `N…`) [local]. 2016–2017 only | +| **BABD-13 (Xiang et al., IEEE TIFS 2024)** [B1–B3] | address behaviour type (13 classes: exchange, mining pool, gambling, mixer, darknet, ...) | address | **WalletExplorer** labels via its API [local, B2] | Collected Jul 2019 – May 2021 [search, B3]; partial ledger at heights 600,000–605,999 [B2] | Not a risk label set; no "illicit vs licit" ground truth | **Partly.** 148 statistical/structural features (amount, degree, time, local subgraph) [B2], recomputable only with each address's full history plus a 2-hop subgraph | **No.** Needs address history + subgraph per address | Kaggle licence **unverified**; WalletExplorer labels have no licence (unverified). Download by user only | 544,462 addresses [search, B3]; feature extraction needs a full graph (graph-tool) | Labels = WalletExplorer heuristic clusters of large services circa 2019–2021; reported 93–97% accuracy reflects that easy service-type task [search] | +| **OFAC SDN digital-currency addresses** (section 3) | addresses of sanctioned parties | address (linked to party/entity) | US Treasury legal designation | Party designation date; per-address addition date **not** given (must be inferred from snapshots) [local] | n/a (lists positives only; non-exhaustive, FAQ 562) | Yes: exact string | **Yes for (A)**: exact match on prevout/output addresses | **Public domain** (17 U.S.C. §105). An excerpt **may be committed**; fetch the current list at runtime | 517 XBT addresses / 56 parties (2026-01-30) [local]; 532 lines in mirror today [local] | Top-5 parties = 56% of addresses (Hydra 117) [local]; 1 TRON address under XBT; shared and duplicate addresses; removals happen | +| **Chainabuse (TRM Labs)** (section 4) | community scam reports per address/URL | address (report) | user reports; `checked` by moderators, `trusted` contributors, confidence score [search] | Report dates (API `since`/`before`) [search] | Unverified reports are explicitly "not spam" but "use with caution" [search] | Exact string only | **On-demand lookup only**: 10 calls/month on a standard key [search] | Proprietary API; site ToS: personal non-commercial use [search]. **Nothing may be committed**; BYO key | Unknown total; no bulk export [search] | Reporter self-selection; spam; scam-type skew; possibly removed reports | +| **Ransomwhere (Cable)** [W1–W3] | ransomware payment addresses + payments | address (+ tx payments) | crowdsourced reports with ransom-note screenshot, manually reviewed; plus "Showing the Receipts" set (family low-confidence) [local, W1] | Payment tx dates (USD at day rate) [local, W1] | Positives only; many payments family-unlabelled [W1] | Exact string; payments are on-chain txs | Only as an **exact-match list** (A) | Site: "entirely publicly available", addresses published after 90 days [local, W1]; Zenodo DOI 10.5281/zenodo.6512122 v1.1.0 (2024); **licence unverified**; site code MIT [local]. Prefer download by user until licence confirmed | ~10 k addresses / $278 M in one snapshot; >$1 B later [search, W2]; small JSON | Self-reported victims; big-game families; mostly pre-2023 [search] | +| **Bitcoin Abuse (historical)** [X1–X2] | community abuse reports | address | user reports, little verification | report dates | n/a | Exact string | Exact match only | Merged into Chainabuse (2023); no official dump today; old CSV feeds only in a deprecated XSOAR integration [search]. **Do not use third-party dumps** (ToS/provenance unknown) | Unknown | Heavy sextortion-spam skew (unverified); unverifiable | +| **Bartoletti et al. Ponzi (2018)** [Z1] | Bitcoin Ponzi-scheme addresses | address | manual analysis of known schemes [Z1] | ≤2017 | No | Features need address history | No | Release location/licence **unverified** | ~30 schemes (unverified) | Tiny, old | +| **WalletExplorer labels** (via BABD) | service clusters (exchanges, pools, markets) | cluster/address | multi-input heuristic + naming by the site author | ≤2021 (site largely static, unverified) | Most addresses unlabelled | Clustering not reproducible exactly | No | No licence (unverified); scraping terms unknown. **Do not commit** | Large | Heuristic; dated | + +### Citations for the matrix +* E1 https://www.kaggle.com/datasets/ellipticco/elliptic-data-set [search] +* E2 Weber et al. 2019, https://arxiv.org/abs/1908.02591 +* E3 PyG docstring (counts, label semantics), https://raw.githubusercontent.com/pyg-team/pytorch_geometric/master/torch_geometric/datasets/elliptic.py [local] +* E4 ChainWatch docs/DATASET.md (time-step semantics, 93 local + 72 aggregate features) +* E5 Šafář et al., "The Enemy of Reproducibility is Opacity: What's Inside the Elliptic Bitcoin Dataset (and Why It Is Wrong)", DFRWS USA 2026, https://dfrws.org/?p=20997 [search]: reverse-engineered features, train/test leakage. Also https://arxiv.org/pdf/2604.19514 [search]: an RF on raw features beats GNNs under a leakage-free inductive protocol, and a sharp illicit-rate drop in steps 43–49 (that paper reports step 46 with 3 illicit out of 960 labelled; the verified Elliptic++ files used here have 2 illicit out of 712 labelled at step 46). +* P1 https://raw.githubusercontent.com/git-disl/EllipticPlusPlus/main/README.md [local] +* P2 LFS files at https://media.githubusercontent.com/media/git-disl/EllipticPlusPlus/main/Actors%20Dataset/wallets_classes.csv and `wallets_features.csv` [local; header and rows inspected] +* P3 https://doi.org/10.1145/3580305.3599803 +* L1 https://arxiv.org/abs/2404.19109 +* L2 https://www.kaggle.com/datasets/ellipticco/elliptic2-data-set [search] +* L3 https://dl.acm.org/doi/pdf/10.1145/3677052.3698635 [search] +* H1 https://archive.ics.uci.edu/dataset/526/bitcoinheist+ransomware+address+dataset [search] +* H2 https://www.ijcai.org/proceedings/2020/0612.pdf +* H3 https://git.disroot.org/shelldweller/ransomware/raw/commit/b1c41d674ce6c15cf2bfd40d6eb6e4011a8be29e/Detecting_Bitcoin_Ransomware.pdf [search] +* R1 https://raw.githubusercontent.com/behas/ransomware-dataset/master/README.md, plus `data/seed_addresses.csv` via media.githubusercontent.com [local] +* R2 https://arxiv.org/abs/1804.04080; J. Cybersecurity 5(1) tyz003, https://doi.org/10.1093/cybsec/tyz003 [search] +* R3 https://zenodo.org/records/1238041 [search] +* B1 https://www.kaggle.com/datasets/lemonx/babd13 +* B2 https://raw.githubusercontent.com/Y-Xiang-hub/Bitcoin-Address-Behavior-Analysis/main/README.md [local] +* B3 https://arxiv.org/pdf/2204.05746; https://doi.org/10.1109/TIFS.2023.3347894 [search] +* W1 https://raw.githubusercontent.com/cablej/ransomwhere/main/docs/index.html [local] +* W2 https://arxiv.org/pdf/2205.05028 and https://arxiv.org/html/2408.15420 [search] +* W3 https://zenodo.org/records/6512123 [search] +* X1 https://pam2024.cs.northwestern.edu/pdfs/paper-92.pdf [search] +* X2 https://xsoar.pan.dev/docs/reference/integrations/bitcoin-abuse [search] +* Z1 https://arxiv.org/pdf/1803.00646 [search] + +Not assessed in depth: HBTBD (https://www.mdpi.com/2076-3417/13/15/8766) and commercial +attribution feeds. Commercial licences typically forbid redistribution and ML training (for +example, Nansen's API terms, https://nansen.ai/legal/api [search]). + +## 2. Decision gate + +**Question:** can ChainWatch meaningfully train a supervised classifier for real-time scoring of +the features of its live, sampled mempool transactions? + +**Answer: No, not for risk or illicit labels, with any legitimate public data available +today.** Exact-address screening (A) is feasible and should be built. A supervised risk +classifier (C) on live features fails on all of the points below at once, and each one alone +would be disqualifying. + +1. **No labelled source shares ChainWatch's feature space.** + * Elliptic and Elliptic++ transaction features are anonymised, standardised and built from a 1-hop graph inside two-week windows. Their construction is undisclosed and reportedly leaky [E5], so they cannot be computed for a new mempool transaction. ChainWatch's own docs already state this (`docs/LIVE_ML_PROPOSAL.md` §1). + * Elliptic2 runs on proprietary clusters. + * BitcoinHeist and BABD features need daily or full address histories and multi-hop subgraphs, which a sampled single-tx Esplora collector does not have. + * The only overlap is a handful of raw tx attributes: Elliptic++'s 17 augmented features (fees, size, number of inputs/outputs, BTC in/out stats). +2. **The labels are about addresses or entities, while the live object is a transaction.** + * OFAC, Ransomwhere, Paquet-Clouston, Chainabuse and BABD label addresses. + * Turning them into transaction labels ("pays a listed address") makes the label a deterministic function of the screened address. A model trained on it learns the lookup, so it is better implemented as the rule (A). +3. **Positives are tiny and concentrated in a few entities. This is a shortcut and leakage risk.** + * OFAC has 517 XBT addresses over 56 parties, and 5 parties hold 56% of them [local]. + * The Paquet-Clouston seed is 97.5% one family (Locky) [local]. + * Any random split puts the same entity's addresses, and their wallet software's fingerprints (script type, fee policy, change pattern), on both sides. The model then learns *which wallet* sent the transaction rather than illicitness. Splitting grouped by entity leaves roughly 10–50 effective positive groups, too few for a stable estimate. +4. **"White" or unknown is not negative.** + * The BitcoinHeist authors say so explicitly [H1]. + * Elliptic and Elliptic++ have 77% and 68% unknown labels respectively. + * Two OFAC-sanctioned addresses sit in Elliptic++ labelled *unknown* [local]. + * Treating unlabelled mempool traffic as negatives would give an unknown, non-random label-noise rate. PU-learning cannot rescue this without a known labelling mechanism. +5. **Temporal and population shift.** + * Every labelled dataset ends by 2021 (most by 2018–2019), and Elliptic++ contains 0 bech32 addresses [local]. + * The 2026 mempool is dominated by SegWit and Taproot, and the OFAC XBT list has 0 Taproot addresses [local]. + * Even inside Elliptic, a strong model collapses from step 43: ChainWatch measured AP 0.917 → 0.043, and an independent study reports a sharp drop in illicit rate after step 43 [E5]. +6. **Licences.** + * Elliptic and Elliptic2 are reportedly CC BY-NC-ND [search], and Elliptic++ has no licence. Their data cannot be shipped in an MIT repo, and a model trained on them can at most be shared with care (NC, no derivatives). + * Chainabuse is proprietary, with personal non-commercial use and 10 calls a month. +7. **No live ground truth arrives later.** Unlike confirmation outcomes (Stage A in `LIVE_ML_PROPOSAL.md`), illicit labels for sampled transactions arrive rarely, years late (for example, an OFAC address was added in 2026 to a party designated in 2018 [local]), and selectively. A live evaluation set therefore cannot be built either. + +**Consequences for ChainWatch:** +* (A) **Build exact-address screening**, with OFAC as the source of record and Ransomwhere/Paquet-Clouston as optional CC BY lists after licence confirmation. Chainabuse is an on-demand BYO-key lookup. +* Report hits as "listed by on " and never as a score. +* Keep the live monitor model-free for risk. +* The only defensible live supervised task remains the label-free-of-crime Stage A (confirmation within *k* blocks). + +### Defensible OFFLINE-only experiment (does NOT validate live scoring) + +**Elliptic++ transactions, restricted to the features ChainWatch can also compute.** +* Train on the 17 augmented raw features only: degree, fees, size, number of input/output addresses, BTC in/out min/max/mean/median/total. +* Use the same chronological splits as Phase 1/2 (train ≤34, test 35–49, with steps 43–49 reported separately), labelled rows only. +* *Superseded by the protocol committed before the runs* ([LIVE_FEATURE_SUBSET_PROTOCOL.md](LIVE_FEATURE_SUBSET_PROTOCOL.md)): it drops `out_txs_degree` (it counts later transactions) and uses the Phase 1 splits (train 1–29, validation 30–34). +* Compare against the full 182-feature model. + +This measures how much signal survives when the features are restricted to quantities a +mempool collector could observe. It does not show that the signal transfers to 2026 traffic +or to other label definitions, because labels, era and population all differ. + +Optional add-on: **BitcoinHeist** with *grouped-by-family* and *chronological (by year)* +splits, AP/precision@k only, and white treated as unlabelled (PU evaluation). This would +quantify how much "ransomware detection" on that benchmark is family memorisation. + +Both are research curiosities to report as negative or diagnostic results. Neither may feed +the live score. + + +## 3. OFAC SDN digital-currency addresses + +Researched on 2026-10-14. "Verified locally" means I checked it against the authentic +`sdn_advanced.xml` copy described in section 3. "Search summary" means the claim comes from a +web-search result snippet for the cited URL. From this sandbox, `ofac.treasury.gov`, +`treasury.gov` and `sanctionslistservice.ofac.treas.gov` could be reached neither by curl +(proxy 403) nor by WebFetch (DNS failure), so I could not open those pages myself. + +### 1. Official download path + +| What | URL | Evidence | +|---|---|---| +| Legacy URL (still used by most open-source tools) | `https://www.treasury.gov/ofac/downloads/sanctions/1.0/sdn_advanced.xml` | Used by OpenSanctions' production crawler config ([us_ofac_sdn.yml](https://raw.githubusercontent.com/opensanctions/opensanctions/main/datasets/us/ofac/us_ofac_sdn.yml), `data.url`) and by [0xB10C's tool](https://raw.githubusercontent.com/0xB10C/ofac-sanctioned-digital-currency-addresses/main/README.md) | +| Sanctions List Service (SLS) export | `https://sanctionslistservice.ofac.treas.gov/api/PublicationPreview/exports/SDN_ADVANCED.XML` | data.gov catalog entry ([catalog.data.gov](https://catalog.data.gov/dataset/specially-designated-nationals-sdn-list-advanced-xml-file-standard), search summary) | +| SLS download endpoint | `https://sanctionslistservice.ofac.treas.gov/api/download/sdn_advanced.xml` (it is said to answer with a short-lived signed redirect) | Third-party guides only ([compliapi](https://compliapi.com/data-sources/ofac-sdn-advanced-xml), [sanctionslookup](https://sanctionslookup.com/learn/ofac-sanctions-list-service-api)). **Unverified against an OFAC page.** | +| XSD | `https://sanctionslistservice.ofac.treas.gov/api/PublicationPreview/exports/ADVANCED_XML.xsd` | Verified locally: it is the `xsi:schemaLocation` in the authentic file's root element | +| Human-readable SLS page | https://ofac.treasury.gov/sanctions-list-service | [search result](https://ofac.treasury.gov/sanctions-list-service) | + +* **SLS launched on 2024-05-06.** The old links keep working through redirects to SLS-hosted files ([OFAC recent action 20240506_33](https://ofac.treasury.gov/recent-actions/20240506_33), search summary). +* **The SLS host rejects requests that have no `User-Agent` header** (HTTP 403). OFAC published a technical notice about this ([20240516_44](https://ofac.treasury.gov/sdn-list-data-formats-data-schemas/ofac-technical-actions-in-reverse-chronological-order/20240516_44), search summary). A downloader must send a User-Agent and follow redirects. +* **The namespace and schema location of `SDN_ADVANCED.XML` changed** during the SLS rollout ([20240507_44](https://ofac.treasury.gov/recent-actions/20240507_44), search summary). +* **Update cadence: there is no fixed schedule.** OFAC says the list is "frequently updated" and that names are added or removed "as necessary and appropriate" ([FAQ 20](https://ofac.treasury.gov/faqs/20), search summary). Changes are announced under [Recent Actions](https://ofac.treasury.gov/recent-actions). How often users download is their own risk decision ([FAQ topic 1641](https://ofac.treasury.gov/faqs/topic/1641/print), search summary). In practice OpenSanctions crawls every 2 hours (`schedule: "0 */2 * * *"` in [us_ofac_sdn.yml](https://raw.githubusercontent.com/opensanctions/opensanctions/main/datasets/us/ofac/us_ofac_sdn.yml)), and 0xB10C regenerates its lists nightly at 00:00 UTC ([README](https://raw.githubusercontent.com/0xB10C/ofac-sanctioned-digital-currency-addresses/main/README.md)). +* **Licensing.** The file is a work of the U.S. Government, and such works have no copyright protection ([17 U.S.C. §105](https://www.law.cornell.edu/uscode/text/17/105)). data.gov lists the dataset as unrestricted (search summary). USA.gov notes that federal sites can also carry third-party material ([usa.gov/government-copyright](https://www.usa.gov/government-copyright)), which does not apply to OFAC's own list data. **A small excerpt may therefore be committed to an MIT repository**, with attribution and with a note that it is a dated snapshot that is not for compliance use. +* **Semantics.** OFAC's address listings "are not likely to be exhaustive" ([FAQ 562](https://ofac.treasury.gov/faqs/562)). Each address is its own entry with a currency label, up to 256 characters ([FAQ 563](https://ofac.treasury.gov/faqs/563)). OFAC's own search tool matches IDs exactly ([FAQ 594](https://ofac.treasury.gov/faqs/topic/1641/print)). Unlisted addresses in the same wallet as a listed address may still carry sanctions risk ([virtual currency guidance](https://ofac.treasury.gov/media/913571/download?inline=)). All four were checked through search snippets only. ChainWatch does no clustering, so it can only report exact-address hits. + +### 2. Exact structure (ADVANCED_XML), verified on the 2026-01-30 file + +Namespace (default namespace, no prefix): +`https://sanctionslistservice.ofac.treas.gov/api/PublicationPreview/exports/ADVANCED_XML` +(the same value appears in 0xB10C's `NAMESPACE` constant in +[generate-address-list.py](https://raw.githubusercontent.com/0xB10C/ofac-sanctioned-digital-currency-addresses/main/generate-address-list.py)). +The root element is ``. The file uses CRLF line endings. +Its top-level children appear in this order: `DateOfIssue`, `ReferenceValueSets`, `Locations`, +`IDRegDocuments`, `DistinctParties`, `ProfileRelationships`, `SanctionsEntries`, +`SanctionsEntryLinks`. + +```xml + + 2026 + 1 + 30 + + + + + Digital Currency Address - XBT + + Program Block + SDN List + + + + + + + + + Khorashadizadeh + Ali + ... + + + + 149w62rY42aZBox8fGcmqNsXUzSStKeq8C + + + + + + + + + 20181128 + + ... + + CYBER2 +``` + +(Abbreviated with `...`. Every element name, attribute and ID shown is copied from the fixture. +The complete XBT Feature is at lines 265–271 of `tests/fixtures/ofac/sdn_advanced_excerpt.xml`.) + +XPaths (namespace prefix `s`), checked against both the full file and the excerpt: + +* XBT feature id: `s:ReferenceValueSets/s:FeatureTypeValues/s:FeatureType[.='Digital Currency Address - XBT']/@ID` gives `344`. Resolve the id **by its text**, as 0xB10C does, and do not hard-code 344. +* Addresses: `s:DistinctParties/s:DistinctParty/s:Profile/s:Feature[@FeatureTypeID=$id]/s:FeatureVersion/s:VersionDetail/text()` +* Primary name: `s:Profile/s:Identity/s:Alias[@Primary='true']/s:DocumentedName/s:DocumentedNamePart/s:NamePartValue`. A name has several parts; their order follows `NamePartGroup`/`NamePartTypeID` (for example 1520 = last name, 1521 = first name in this file). A party can also have several `DocumentedName`s in different scripts. +* Designation: `s:SanctionsEntries/s:SanctionsEntry[@ProfileID=$profile]`. Within it, `s:EntryEvent/s:Date/{Year,Month,Day}`, and the programme codes are in `s:SanctionsMeasure[@SanctionsTypeID=]/s:Comment`. OpenSanctions resolves `SanctionsTypeID` to "Program" before it reads `Comment` ([ofac_advanced.py](https://raw.githubusercontent.com/opensanctions/opensanctions/main/datasets/us/ofac/ofac_advanced.py), `extract_sanctions_measure_name`). It also filters on `ListID` to separate "SDN List" from non-SDN lists. + +### 3. Fixture: `tests/fixtures/ofac/sdn_advanced_excerpt.xml` (authentic, trimmed) + +* **Source copy:** `https://media.githubusercontent.com/media/keithrozario/sanctions-checker/main/sdn_advanced.xml`, which is the Git LFS object behind [keithrozario/sanctions-checker `sdn_advanced.xml`](https://github.com/keithrozario/sanctions-checker). The LFS pointer at commit `c092957464c85b526e2e1134edade85a272af8a0` (2026-02-09, message "updated"; the date comes from the GitHub commits page via WebFetch) gives `oid sha256:9ada1b25ec51909b25ddb37c04d6ca22425a8202d406aa92d21e467aee662928`, `size 122273646`. The downloaded file's SHA-256 matches that oid exactly. `DateOfIssue` is **2026-01-30**. The repo has no LICENSE file (raw `LICENSE` returns 404), but the content is OFAC's public-domain list, so no repo licence is needed for an excerpt of it. +* **Profiles kept:** + * 26137, Khorashadizadeh Ali, CYBER2, entry date 2018-11-28, 1 P2PKH address. This is the earliest XBT-party entry date in the file, shared with 26138. + * 38665, Task Force Rusich, RUSSIA-EO14024, entry date 2022-09-15, 2 bech32 v0 addresses. + * 45404, Wang Mingming, ILLICIT-DRUGS-EO14059, entry date 2023-10-03. It has 3 entries filed as XBT, one of them the TRON address `TUCsTq7TofTCJRRoHk6RvhMoS2mJLm5Yzq`. This makes it a ready-made negative test. +* **How it was cut:** I wrote `the research script excerpt_sdn.py (not in the repository)`. The script copies whole elements byte-for-byte (CRLF kept) and drops other elements whole. It self-checks that every retained element line occurs verbatim in the source. Retained: the XML declaration, the root start tag, `DateOfIssue`, the 3 `DistinctParty` elements, their 3 `SanctionsEntry` elements, and the `ReferenceValueSets` entries whose IDs those elements reference, plus all 18 "Digital Currency Address - *" FeatureTypes. Changed: an XML comment stating the provenance was added after the declaration. `Locations`, `IDRegDocuments` and `ProfileRelationships` are emptied (the country `Location`s alone were about 50 KB), so `LocationID` references dangle. +* **Size:** 32,951 bytes. Parsed results: + * all 6 XBT entries come out with names, entry dates and programmes; + * ChainWatch's existing `parse_ofac_sdn_advanced` (run read-only) returns 5 records and rejects the `T...` entry. On the full file it returns 516 records with 1 rejection. +* **Other candidates I checked and rejected:** + * [cylon56/ofac-naughtylist tests/fixtures/sample_sdn_advanced.xml](https://raw.githubusercontent.com/cylon56/ofac-naughtylist/main/tests/fixtures/sample_sdn_advanced.xml) is constructed, not authentic. It uses BIP-173's example address `bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh` and writes `DateOfIssue` as attributes, which is wrong. + * [bitnob/ofac-address-feed testdata](https://raw.githubusercontent.com/bitnob/ofac-address-feed/main/internal/ofac/testdata/sdn_advanced_sample.xml) is constructed ("EVIL CORP"). + * [sscodings/SIH_2 docs/research/ofac_sample.xml](https://raw.githubusercontent.com/sscodings/SIH_2/main/docs/research/ofac_sample.xml) contains real values but was re-serialised by ElementTree (`ns0:` prefixes) and has no `SanctionsEntries`. + * [GENERALBYTESCOM/batm_public ofac_sdn_advanced.xml](https://raw.githubusercontent.com/GENERALBYTESCOM/batm_public/master/server_extensions_extra/src/test/resources/ofac_sdn_advanced.xml) is authentic (2021-01-19) but pretty-printed and has no XBT addresses. +* **Supporting data:** a research JSON (not in the repository) has all 519 XBT rows from the full file, with profile, name, programmes, entry dates and address type. `the research script analyze_sdn.py (not in the repository)` regenerates it. + +### 4. Counts in the 2026-01-30 file (verified locally) + +* 519 XBT `VersionDetail`s, 517 unique strings, across 56 profiles (27 entities, 29 individuals by PartySubTypeID 3/4). All are on `ListID=1550` (SDN List). +* By type: + * 202 P2PKH and 178 P2SH. All pass base58check with version 0x00 or 0x05. + * 138 bech32 v0, all valid checksums. + * 0 Taproot. + * 1 TRON-format address. +* **Concentration:** + * Hydra Market has 117 addresses (23% of all XBT entries). + * Blender.io and Wang Yunhe (911 S5) have 46 each. + * The top 5 parties hold 56% of all addresses. + * 21 parties have a single address. +* **Programmes over the 56 parties:** + * CYBER2 25 + * ILLICIT-DRUGS-EO14059 13 + * RUSSIA-EO14024 6 + * ELECTION-EO13848 5 + * DPRK3 4 + * SDNTK, SDGT 3 each + * others 1–2 +* **Party entry year (counted by address):** + * 2018: 2 + * 2019: 11 + * 2020: 38 + * 2021: 64 + * 2022: 227 + * 2023: 36 + * 2024: 59 + * 2025: 82 +* **Compared with the current mirror** ([0xB10C lists branch](https://raw.githubusercontent.com/0xB10C/ofac-sanctioned-digital-currency-addresses/lists/sanctioned_addresses_XBT.txt), fetched 2026-10-14): 532 lines, made of 208 `1…`, 177 `3…`, 146 `bc1…` and 1 `T…`. Since 2026-01-30, 16 addresses were added and 1 was removed (`17a5bpKvEp1j1Trs4qTbcNZrby53JbaS9C`). + +### 5. Data-quality pitfalls (each verified locally unless cited) + +1. **Non-Bitcoin addresses filed under XBT.** `TUCsTq7TofTCJRRoHk6RvhMoS2mJLm5Yzq` (profile 45404, Feature 65924) is a TRON address. It decodes as a *checksum-valid* base58check string with version byte 0x41 (TRON mainnet), so a validator that checks only the checksum accepts it. Validate the version byte (0x00/0x05) and the bech32 HRP `bc`, then reject and log the entry rather than silently dropping it. The mirror list carries it too. +2. **One address listed under two parties.** `1H939dom7i4WDLCKyGbXUp3fs9CSTNRzgL` appears under both 38419 (Khatibi Aghada) and 38420 (Nikaeen Ravari). A map keyed by address keeps only the first party. ChainWatch's current parser does this (`if addr not in records`), so it loses profile 38420. Store a list of listings per address. +3. **Duplicates within one party.** `3F6bbvS1krsc1qR8FsbTDfYQyvkMm3QvmR` appears twice under Blender.io (37070). +4. **`EntryEvent` date is the party's designation date, not the date the address was added.** + * MESRI Behzad (24003) was designated on 2018-03-23 (CYBER2) and has *no* XBT feature in the 2026-01-30 file. + * Yet `12aNKp2iDKuhEde2YfPdd4DFGenRUTKupL` sits under that profile in a later file: it is in the SIH_2 sample (Feature 96516) and in today's mirror. + * Treating `listed_on` as the address's listing date would therefore backdate the label by about 8 years. + * For point-in-time correctness, use **the first snapshot (by `DateOfIssue`/retrieval time) that contains the address**. +5. **Removals happen** (one XBT address removed between January and October 2026). Screening and any label set must be versioned per snapshot, and must not be a monotonic "ever listed" set. +6. **The mirror list has no provenance per address.** The 0xB10C TXT has no party, programme, date or snapshot hash. It is fine as a convenience source, but the official XML is the source of record. The mirror author disclaims any warranty on completeness or correctness ([README](https://raw.githubusercontent.com/0xB10C/ofac-sanctioned-digital-currency-addresses/main/README.md)). +7. **Programme codes.** Take `Comment` only from `SanctionsMeasure`s whose `SanctionsTypeID` resolves to "Program". Other measure types (directives, "Block") exist ([OpenSanctions](https://raw.githubusercontent.com/opensanctions/opensanctions/main/datasets/us/ofac/ofac_advanced.py)). A profile can have several `SanctionsEntry`s (several lists), and a dict keyed by `ProfileID` keeps only the last one. +8. **Format traps.** + * `DateOfIssue` uses child elements, not attributes. + * The namespace changed in May 2024 (see above). + * The file is about 122 MB with CRLF line endings. ChainWatch's comment "~100 MB in 2026" understates it. A full ElementTree parse took a few seconds here but uses roughly 1–2 GB of RAM (not measured precisely); `iterparse` with element clearing is safer for a cloud container. + * Bech32 is case-insensitive and base58 is case-sensitive, so canonicalise before exact matching. +9. **Coverage is tiny and entity-specific.** There are 517 addresses for 56 parties. FAQ 562 says the listings are non-exhaustive. Most listed addresses are reused, legacy-type addresses from 2018–2022 cases, and the list has 0 Taproot addresses, while a live 2026 mempool contains many. Exact-match screening is meaningful; using these addresses as ML positives is not (see datasets.md, Decision gate). + + +## 4. Chainabuse (optional, bring-your-own-key provider; not implemented) + +Researched on 2026-10-14. From this sandbox, `api.chainabuse.com`, `docs.chainabuse.com`, +`docs.trmlabs.com` and `chainabuse.com` were blocked for curl (proxy 403) and could not be +resolved by WebFetch. **Every item below therefore comes from web-search snippets of the +cited pages. Re-read each page before relying on it.** "Unverified" means that no source +confirmed the point. + +### Facts + +| Topic | Finding | Source | +|---|---|---| +| Operator | Chainabuse is run by TRM Labs. TRM acquired Bitcoinabuse.com (announced 2023-10-11), and Bitcoinabuse's earlier reports were merged into Chainabuse. | [GlobeNewswire](https://www.globenewswire.com/news-release/2023/10/11/2758400/0/en/TRM-Labs-Acquires-Bitcoinabuse-com.html); [TRM launch blog](https://www.trmlabs.com/resources/blog/announcing-the-launch-of-chainabuse-the-multi-chain-scam-reporting-tool-that-empowers-crypto-users-against-fraud) | +| Base URL / endpoints | `https://api.chainabuse.com/v0`. `GET /v0/reports` takes an `address` filter (the screening use case). `GET /v0/reports/{reportId}` returns one report. Reporting is also possible (POST). | [Get Reports](https://docs.chainabuse.com/reference/reports-1); [Get Single Report](https://docs.chainabuse.com/reference/report); [Screening addresses](https://docs.chainabuse.com/docs/get-reports-parameters) | +| Auth | **HTTP Basic, with the user's or organisation's own API key.** The docs show the key as the username, with the key or empty as the password. Any account generates a key under Profile → Settings → API key. **Yes, an integration needs the user's own key.** | [Authentication](https://docs.chainabuse.com/docs/getting-started) | +| Rate limits / quota | Standard key: **10 calls per month**, at most 50 reports per call. Partner access: at most 5,000 calls per hour. | [Request limits and rate](https://docs.chainabuse.com/docs/getting-started-2-1) | +| Pricing | No public price list was found. Partner and Pro access go through `hello@chainabuse.com`, and law-enforcement access through a partner form. **Unverified.** | [TRM-hosted API docs](https://docs.trmlabs.com/guides/chainabuse/welcome-to-chainabuse-api) | +| Query params | Documented: `address`, `chain`, `category`, `orderByField` (date), `orderByDirection`, `before`/`since` (date thresholds), `page` (at most 50 per page). `perPage`/`includePrivate` were **unverified**. | [Screening addresses](https://docs.chainabuse.com/docs/get-reports-parameters) | +| Verification status | `checked` means moderators, including blockchain-intelligence experts, verified the report (green badge). `trusted` means the reporter is a pre-vetted Trusted Contributor (blue badge). An unverified report "does not mean it is spam" but should be "used with caution". Each report has a confidence score that can be filtered on, and the docs say they cannot guarantee 100% accuracy. Flagged spam is reviewed and removed. | [Spam detection and reports accuracy](https://docs.trmlabs.com/guides/chainabuse/verifying-the-accuracy-of-reported-information); [FAQ](https://chainabuse.com/en/faq/GENERAL) | +| Withheld fields | Evidence, geolocation and contact details are not in the public API. They go only to pre-vetted partners through Chainabuse Pro, depending on the reporter's opt-in. | [TRM-hosted API docs](https://docs.trmlabs.com/guides/chainabuse/welcome-to-chainabuse-api) | +| API licence | Listed as "Proprietary API". | [docs.trmlabs.com](https://docs.trmlabs.com/guides/chainabuse/welcome-to-chainabuse-api) | +| Website ToS | Users get a limited, non-sublicensable right to use Chainabuse Content for **personal, non-commercial purposes**, and TRM reserves all other rights. I did **not** find explicit clauses on scraping, bulk download, redistribution or ML training: **unverified**, read the PDF before any bulk use. | [Terms of Use PDF](https://chainabuse.com/ChainAbuse_TermsofUse.pdf) | +| Bulk / historical snapshots | No official bulk export or historical dump was found. Researchers report that the merged service "is no longer making its full database freely available". The API is restrictive, rate-limited and uses a different categorisation. Old BitcoinAbuse "Forever/30 days" CSV feeds appear only in a **deprecated** XSOAR integration. | [PAM 2024 paper](https://pam2024.cs.northwestern.edu/pdfs/paper-92.pdf); [LiU thesis](https://liu.diva-portal.org/smash/get/diva2:1828499/FULLTEXT01.pdf); [XSOAR BitcoinAbuse (Deprecated)](https://xsoar.pan.dev/docs/reference/integrations/bitcoin-abuse) | +| Ransomwhere link | Ransomwhere lists Chainabuse as a partner. | [ransomwhere docs/index.html](https://raw.githubusercontent.com/cablej/ransomwhere/main/docs/index.html) | + +### What follows for ChainWatch + +1. **Optional, off by default, BYO key.** Read the key from an env var or secret, never ship one, and never send it anywhere except `api.chainabuse.com` over HTTPS with Basic auth. +2. **The quota rules out live per-transaction screening on a standard key.** 10 calls a month cannot cover a sampled mempool (tens of addresses per transaction). The realistic uses are: + * an analyst clicks "look up this address" on demand; + * a partner key, with ChainWatch enforcing a client-side budget and per-address caching with a TTL. + Count and display the remaining quota. +3. **Report the result as an allegation, not a label.** + * Show the number of reports, `checked` and `trusted` counts, categories and the latest report date, with a link to the report. + * Default to showing all reports while visually separating unverified ones. Optionally offer a "checked-only" filter. + * Never derive a risk score from report counts. Counts are easy to manipulate and are biased toward visible scams. +4. **Do not persist or redistribute.** + * Commit no Chainabuse data (no fixtures with real responses) to the MIT repo; use synthetic response fixtures in the documented shape. + * Cache locally only for as long as the user's ToS allows. Treat bulk harvesting and ML training as **not permitted unless TRM grants it in writing**: the website ToS limits content use to personal, non-commercial purposes, and the API is proprietary. +5. **Point-in-time.** Store `retrieved_at` with each lookup result. Reports can be removed (spam review), so a past result cannot be reproduced later. + diff --git a/docs/RISK_ENGINE.md b/docs/RISK_ENGINE.md new file mode 100644 index 0000000..c3fcf82 --- /dev/null +++ b/docs/RISK_ENGINE.md @@ -0,0 +1,322 @@ +# ChainWatch Risk Intelligence: contracts and design + +The live monitor assesses every fetched transaction with three **separate** layers and +never blends them into one score: + +| Layer | Produces | Means | Never means | +|---|---|---|---| +| A. Source-backed screening | `SCREENING_MATCH` with evidence (address, role, source, version, reference) | an enabled source (e.g. OFAC SDN) lists an address the transaction spends from or pays to | proof of fraud or of who controls the funds; a sanctions listing is a legal designation | +| A'. Observed-graph relation | `RELATION_FOUND` with the path `listed address -> parent tx -> this tx` | within this collector's sampled observations, the transaction spends an output of a transaction that spent from a listed address | ownership, common control or culpability; unobserved parents are not checked | +| B. Behavioural anomaly | `ANOMALY` (`notable`/`strong`) with per-measurement explanations | measurements in the tail of recently sampled traffic | wrongdoing: batch payouts, consolidations and CoinJoins are all unusual and legitimate | +| C. Supervised model | `NO_VALIDATED_MODEL` for every transaction | no model is validated for live data (docs/RISK_DATA_FEASIBILITY.md) | it never falls back to the historical Elliptic++ models | + +Code: `src/chainwatch/risk/`. Tests: `tests/test_risk.py`. Data decisions: +[RISK_DATA_FEASIBILITY.md](RISK_DATA_FEASIBILITY.md). + +## 1. Event-time model (point-in-time correctness) + +| Time | Field | Set when | Used for | +|---|---|---|---| +| Blockchain event | `status.block_time` (Esplora; not stored as a feature) | a block confirms the tx | nothing in scoring | +| First observation | `first_seen` (tx row, record `observed_at`) | the collector receives the txid on the WebSocket | ordering, latency | +| REST enrichment | `fetched_at` | the details are fetched (up to `max_queue_age_s` later) | features are computed at this time | +| Feature computation | = `fetched_at` (features carry `schema_version`) | immediately after the fetch | | +| Indicator availability | `indicators.available_at` = the `retrieved_at` of the first snapshot that contained the address; `removed_at` = retrieval of the first snapshot without it | `chainwatch-live indicators update` | screening at T uses only listings with `available_at <= T < removed_at` | +| Source publication | `indicator_versions.published_at` (e.g. OFAC `DateOfIssue`), `details.party_designated_on` | parsed from the source | shown as context only: OFAC's date belongs to the *party*, not to when an address was added | +| Evaluation | `evaluated_at` (record) | the engine assesses the tx | all layers use this instant | +| Lifecycle | `tx.lifecycle`, `lifecycle_at`, `replaced_by` | later `mined` / `removed` / `replaced` WebSocket events | display only; **never** a feature, and past records are never rewritten | +| Retrospective match | alert `retrospective = true` | a later snapshot lists an address of an earlier observed tx | a separate alert; the original record keeps what was known then | +| Supervised labels | none exist | | | + +Guarantees and their tests: +* Screening ignores listings not yet available or already removed at `evaluated_at` + (`test_screening_is_point_in_time`). +* The anomaly reference window contains only transactions fetched **before** the scored one + (`test_anomaly_reference_window_excludes_the_scored_and_later_transactions`; the collector + calls `score` before `update`, and a restart rebuilds the window from stored rows ordered + by `fetched_at`). +* Retrospective screening never changes a stored record + (`test_retrospective_screening_does_not_rewrite_history`). +* Lifecycle events update state columns only + (`test_collector_screens_relates_and_tracks_lifecycle`). + +Approximation stated plainly: `available_at` is when *this deployment* fetched a snapshot, +which is later than OFAC's publication by up to the refresh interval (daily). Replaying +history with snapshots fetched today would be optimistic; only snapshots retrieved at the +time reflect what was known. + +## 2. Indicator sources + +| Source id | What | Licence | Per-address provenance | +|---|---|---|---| +| `ofac-sdn` | official `sdn_advanced.xml` (~122 MB), parsed as a stream | US government work, public domain | party names (all parties if several), SDN profile ids, programmes, party designation date | +| `ofac-sdn-mirror` | third-party nightly extraction of the XBT addresses (github.com/0xB10C/...) | data public domain; tool MIT | none (addresses only) | + +Each snapshot is versioned by the SHA-256 of its content (`indicator_versions`) and **diffed +against the active listings**: new addresses become available at its retrieval time, missing +ones are closed. Content that reverts to an earlier version therefore re-lists what that +version listed (v0.7 treated a previously seen hash as "unchanged"). Nothing to change and the +same content as the source's latest version only refreshes `checked_at` (freshness). + +* **Refusals.** A snapshot with no valid address, or one that would delist more than 25% of + this source's own active listings (beyond 5), is refused (`SnapshotRejected`): an error + page, a truncated download or a schema change must not silently empty the list. + Superseding a lower-ranked copy's extra rows does not count (v0.8.0 counted it, so a + mirror with extra rows blocked every later official refresh), except for a first + official snapshot, which is measured against the copy it replaces. A snapshot dated + (`published_at`) before the source's stored version, such as a stale CDN edge or an old + file, is refused too. The CLI then tries the fallback; `--allow-mass-removal` and + `--allow-older` accept a checked exception. A refused primary followed by a successful + fallback exits **3**, so the refresh unit shows as failed and someone looks. A percentage + guard can still be worn down by repeated 25% removals on consecutive days. +* **One list, two channels, ranked.** `ofac-sdn` (rank 0) and `ofac-sdn-mirror` (rank 1) + share the authority `ofac-sdn`. An official snapshot also closes the mirror listings it + does not have, so the fallback copy cannot keep a delisted address alive. The mirror, + which may be days behind, **never** closes an official listing and never re-lists an + address the official file delisted or superseded (each closure records the closing + version in `closed_by`; reported as `skipped_delisted`); it can only add addresses the + official list has not dealt with yet. The price: an address re-designated while the + official fetch keeps failing is missed until the official file lists it (the official + source then shows as stale). Screening reports one match per + authority and address (the official file preferred, for its party metadata). A mirror + older than the official file is reported `superseded_by`, not stale; the official file is + never superseded by its mirror, so a failing official refresh shows its real age. +* A source not refreshed for `indicator_max_age_days` (default 7) is reported **stale**. + Before the first snapshot, screening returns `SCREENING_DATA_UNAVAILABLE`, never "no match". +* The mirror is a third-party extraction, not an authoritative copy: on 2026-01-30 it listed + 531 addresses against 516 valid ones in the official file (16 added, 1 removed between the + two). Every record shows which source matched. + +External data is untrusted: content is parsed (never evaluated), only UTF-8 is accepted (a +UTF-16 document could hide a DOCTYPE from the byte scan), DTDs and entities are refused anywhere +in the file, sizes are capped (400 MB, and 10,000 addresses per party), every finished record +is freed while streaming, downloads are HTTPS-only on every redirect hop, and every address is validated +(base58check version 0x00/0x05; bech32/bech32m with HRP `bc`). Invalid entries are rejected +with a reason; for example OFAC files a TRON address under XBT. + +Verified on the real 2026-01-30 file: 516 valid addresses, 56 parties, 1 rejected entry, 24 s, +16 MB peak Python memory. A byte-identical public-domain excerpt is the test fixture +`tests/fixtures/ofac/sdn_advanced_excerpt.xml`. + +## 3. Live feature schema `live-features/2` + +All values are computed from one Esplora transaction at `fetched_at`; amounts are integer +satoshis in [0, MAX_MONEY]; anything outside the documented ranges is a malformed payload. + +| Feature | Unit / type | Null when | Notes | +|---|---|---|---| +| `size`, `weight`, `vsize` | bytes, weight units, vbytes | never | vsize = ceil(weight/4) (BIP141) | +| `fee`, `fee_rate` | sat, sat/vB | never | fee from the payload | +| `n_inputs`, `n_outputs`, `n_parent_txs` | counts | never | | +| `input_value_total` | sat | any prevout value missing | | +| `output_value_total`, `max_output_value`, `output_values[:25]` | sat | never | sums include change: **not a payment amount** | +| `n_dust_outputs`, `n_op_return`, `max_equal_value_outputs`, `n_output_types` | counts | never | equal-value groups ignore dust | +| `rbf_signal`, `segwit`, `locktime_enforced`, `coinbase` | bool | never | RBF: an input sequence <= 0xfffffffd | +| `version`, `locktime`, `locktime_kind` | int, int, none/height/time | never | | +| `confirmed_at_fetch` | bool | status missing | state at fetch time; **not** an input to any layer | +| `input_types`, `output_types` | counts per script type | never | | +| `input_refs[:25]` | `txid:vout` | never | observable spends; no ownership inference | + +Addresses are extracted separately for screening (`features.extract_addresses`, up to 500 +per side) and stored in `tx_address`. Scripts without an address (P2PK, bare multisig, +OP_RETURN, non-standard) and missing prevouts are counted in the screening `coverage`. + +## 4. Screening outcomes + +`SCREENING_MATCH` (direct: input = "spends from", output = "pays to"), +`NO_KNOWN_SCREENING_MATCH` (only the enabled sources; not proof of legitimacy), +`SCREENING_DATA_UNAVAILABLE` (no source loaded at T), `INSUFFICIENT_INFORMATION` (no +address could be screened). Each result lists the sources with version, last check, age and +staleness, and the coverage counts. + +## 5. Observed-graph relations + +Distance 2 only: a parent transaction **observed by this collector** that spent from an +address listed *at the child's evaluation time*. The parents' stored input addresses are +screened again (a listing added after the parent was assessed counts; a delisting does too), +at most 200 parents per transaction, one relation per (parent, address, authority). +Coverage (`parents`, `parents_checked`, `parents_observed`) is reported, because the sample +sees only a few percent of parents. No clustering, no multi-hop search, no address reuse +inference. A relation that only appears after the child was assessed is not raised +retrospectively. + +## 6. Behavioural anomalies (`robust-tail/3`) + +Eight measurements: fee rate (both tails), vsize, inputs, outputs, sum of outputs, dust +outputs, largest equal-value output group, output script-type count. For each, the empirical +tail probability `p = (#reference >= x + 1)/(n + 1)` against the previous `window` = 2,000 +fetched transactions, plus a robust z-score. A measurement is flagged when `p <= 0.002` and +`|z| >= 3`; `strong` = flagged measurements in **two or more evidence groups**: size (vsize, +inputs, outputs), fee, value, output shape (dust, equal values, script mix). vsize is close to +a linear function of the input and output counts, so robust-tail/2 counted one unusual +count twice: on realistic correlated noise that was about 1.2 priority-3 alert groups per +hour at 12 fetches per minute (v0.8.1 audit). robust-tail/1 also counted one value outside +the reference range, which with a small window is true of every flag. `alpha` is per +measurement: with eight measurements about 3–4 × alpha of transactions get at least one flag +under the null (at most 8 × alpha). After a few similar extreme transactions enter the +window, later ones are no longer flagged until they leave it (masking). Fewer than 1,000 reference transactions gives +`INSUFFICIENT_BASELINE`: the two-sided fee test needs `2/(n+1) <= alpha`, and the +configuration is validated (alpha in (0, 1), finite `min_z`, `min_reference <= window`). On the +VM (12 fetches per minute) a fresh install needs about 83 minutes to build the baseline; a +restart rebuilds it from stored rows of the current feature schema. The score is `-log10(p)`: rarity in recent traffic, +not a probability of anything illicit. Cost: about 2–4 ms per assessment with a full window +(p50 2.5 ms, p95 4.1 ms measured for the detector alone on the audit machine; hardware +dependent). The reference window is updated only after the record is committed. + +`scripts/anomaly_study.py` replays a collected database and compares this detector with +IsolationForest and fixed rules (alert volume, hourly stability, sensitivity, drift, +agreement, CPU), and shows that known-benign shapes (batch payout, consolidation, +CoinJoin-like) are flagged: anomalies are leads for review, nothing more. **No study results +on real traffic exist yet**; the build environment cannot reach mempool.space. + +## 7. Supervised layer gate + +A model is used only if its card states the live `feature_schema`, `validated_for_live: true`, +an evaluation with a time-separated independent holdout, pre-registered primary metrics and +the label source, and the artifact hash matches. No model passes; the layer abstains with +`NO_VALIDATED_MODEL`. The offline feature-subset experiment +([LIVE_FEATURE_SUBSET_PROTOCOL.md](LIVE_FEATURE_SUBSET_PROTOCOL.md)) cannot pass it by +construction. Its results ([LIVE_FEATURE_SUBSET_RESULTS.md](LIVE_FEATURE_SUBSET_RESULTS.md)): +on Elliptic++ test steps 35-49, XGBoost on the 16 live-computable features reaches AP 0.646 +against 0.797 with all 182 features (paired difference -0.151, 95% interval [-0.216, -0.089]). +Like every model it collapses after step 42 (AP 0.028). Exploratory and rejected for +promotion. + +## 8. Review priority and alerts + +`priority` is ordinal and documented as "not a probability of wrongdoing": +1 source match, 2 observed-graph relation, 3 strong anomaly, 4 notable anomaly, none. +`insufficient_evidence` is true when screening could not run (no source, no screenable +address, error) **and** the anomaly layer had no baseline or failed. + +Alerts are raised for priorities 1–3 and grouped: `screening:::
`, +`relation::
`, `anomaly::`, and for retrospective +matches `retro:::
`. A repeat of the same transaction is ignored +(`alert_txids` remembers every transaction an alert counted; the API shows the latest 50). +Alerts still `new` expire 90 days after their last occurrence (this bounds the hourly anomaly +groups); alerts a person acted on (dismissed, under review, resolved, insufficient +evidence) are kept with their notes. An alert can outlive the transactions it names +(retention keeps about 3 days at the cap): its latest evidence stays in the alert. +The upgrade from v0.7 re-keys existing alerts (`screening::
` and the like) +to these keys, using the role in their latest evidence, so dismissed and resolved states +carry over. + +Retrospective screening runs when a snapshot is stored (CLI), again when the collector +loads it, and for each source's latest snapshot when the collector starts (a snapshot +stored while it was down). A database error in the collector's pass is counted +(`db_errors`) and retried on the next heartbeat; it never stops the collector. Matches an +earlier pass already alerted on are not counted again. Only listings still in force are +used: a listing closed since (delisted, or superseded by the official file) is not "now +listed" (v0.8.0 re-ran closed ones at every collector start). In each pass, every stored +transaction that involves a newly available address and whose own record has no match for +it under the same authority gets a retrospective alert. That covers +transactions observed before the listing and those assessed in the seconds between the +snapshot being stored and the collector loading it. Only retained rows (the retention window) +can be screened retrospectively. A repeat of a +dismissed alert is counted as `suppressed` (no new notification). A repeat of a resolved +alert reopens it. Statuses: `new`, `under_review`, `dismissed`, `resolved`, +`insufficient_evidence`. Changes are logged in `alert_events`. Over HTTP the queue is +**read-only**: statuses are changed on the collector host with +`chainwatch-live alerts set-status --id N --status S --note "..."`. The status history +(`alert_events`, including operator notes) is deliberately not served over HTTP; read it with +`chainwatch-live alerts history --id N`. No external notification is sent anywhere. + +## 9. Failure isolation and operations + +* Each layer runs in its own guard: an exception becomes `status: ERROR` plus an entry in + `errors`, and the other layers still report. A failure to assess or store a record is + counted (`risk_errors`), the observation is kept, and an all-`ERROR` record labelled + "Assessment failed (not evaluated)" is stored in its place (v0.8.0 left no record, so the + row looked exactly like risk being off). The transaction's addresses are saved in their + own savepoint first, so a later retrospective pass can still find it. +* An observation and its risk record (addresses, record, alerts) are committed in one SQLite + transaction; the risk writes sit in a savepoint, so a failed write rolls back only them. + Readers and the event stream therefore never see a fetched row whose assessment is + pending. List rows carry `risk_assessed` and (v0.8.1) `risk_state`: `finding`, + `no_finding`, `insufficient_evidence` (no screening data and no anomaly baseline: shown + as "?"), `failed` ("err") or `not_assessed` ("n/a"), so "nothing found" is never shown + for a transaction whose screening could not run. +* Indicators are refreshed daily by `chainwatch-indicators.timer` (official XML, falling back + to the mirror). A failed refresh keeps the previous version and exits 1; a refused + official snapshot exits 3 even when the mirror succeeded. The + collector reloads its screening index when a new version appears (checked every heartbeat) + and screens the transactions it assessed meanwhile retrospectively. +* If the risk engine cannot be built at start, the collector still collects and reports + `risk_unavailable`; rows are then marked not assessed. +* API: `/v1/live/risk/summary` (per-source `age_s` and `stale` by the collector's + `indicator_max_age_days`; the anomaly `min_reference`, `window` and `alpha`; alert counts + are all-time, marked `alerts_by_status_scope`), `/v1/live/findings` (with + `insufficient_evidence` and `errors`), `/v1/live/alerts`, and `risk` + `lifecycle` in + `/v1/live/transactions/{txid}`. All are read-only, token-protected on the + edge API, and proxied with the same cache and limits as the other live routes. + +### Paged findings and alert queue + +Until v0.8.1 the dashboard loaded the 50 newest findings and the first 200 alerts; anything +older could not be reached from the UI. Both lists are now filtered and paged on the server +(`src/chainwatch/risk/persistence.py`: `findings_page`, `alerts_page`). + +* **Responses** keep their list (`findings` / `alerts`) and add `page`: `total` (rows + matching the filters), `next_cursor` (null on the last page), `limit`, `available` + (false when the collector database has no risk tables) and the filters applied. +* **Filters, findings:** `type` (source_match = P1 screening match, relation = P2, anomaly = + P3/P4, insufficient_evidence), `authority` (the publisher: the official OFAC file and + its mirror are one authority), `priority` / `max_priority`, and a time range on the + evaluation time. `insufficient_evidence` returns assessments with no priority, no + screening data and no anomaly baseline; they are not findings and never appear in the + findings list; a failed assessment is in neither. Priority or source filters together + with it are a 400. +* **Filters, alerts:** `status` (`open` = new or under review), `type` (live source + matches and **retrospective** matches are separate types; relation; anomaly), + `authority` (from the immutable group key, so keys written before v0.8 that name a + source id are included), `priority` / `max_priority`, and a time range on the last + occurrence. +* **Order and cursors.** Findings are ordered by observation id, newest first: the key is + immutable, so a row never moves; rows stored while someone pages appear on the first + page only. Alerts default to triage order (open first, priority, last seen, then id); + `sort=newest` orders by creation. Cursors are keyset positions (an opaque string for + alerts, bound to its sort order), not offsets: an unchanged row is never skipped or shown + twice. In triage order an alert whose sort key changes between two requests (a new + occurrence, a status change) moves to its new place, which can be on a page already + passed; the UI says so. +* **Consistency.** The total and the page are read in one SQLite read transaction, so they + describe the same state even while the collector commits. +* **Bounds.** `limit` ≤ 200 (the dashboard uses 25), cursors ≤ 200 characters, time bounds + validated (`nan`, ±inf, out-of-range: 422; an empty range: 400). Ids, totals and the + page's keys come from covering indexes (`risk_findings_cov`, `alerts_queue_cov`); full + rows are read for the page only. The `authority` filter reads the stored record of P1/P2 + rows only. +* **Remote proxy.** The dashboard validates filters and cursors itself (a bad request is + a 400 there, never forwarded), snaps `hours` to the cached steps and forwards the rest. + The unfiltered first page bypasses the proxy's upstream budget like the other polled + routes. An edge API from before paging ignores unknown parameters: the dashboard then + shows unfiltered first pages with "total not reported" and refuses filtered requests + (502, "upgrade the collector") rather than mislabelling rows. +* **CLI:** `chainwatch-live alerts list --limit N` lists any number in triage order and + accepts `--status open`. + +Measured with `scripts/bench_risk_pages.py` on constructed data (50,000 assessed +observations, the retention cap, of which 6,582 findings; 30 repetitions, read-only +connection as on the edge; local container, not the VM): + +| Query (page of 25 unless noted) | 50k alerts p50 / max (ms) | 2k alerts p50 / max (ms) | +|---|---|---| +| findings, first page / page 101 | 2.3 / 3.3 · 1.5 / 1.7 | 1.4 / 2.3 · 1.6 / 1.9 | +| findings, type filter / time range | 1.0–1.9 / ≤ 2.3 | 1.0–1.9 / ≤ 2.3 | +| findings, authority filter | 20.0 / 22.3 | 19.2 / 23.3 | +| findings, page of 200 | 3.6 / 4.3 | 3.4 / 4.1 | +| alerts, triage first page / page 101 | 9.9 / 15.5 · 12.2 / 19.4 | 1.2 / 1.4 | +| alerts, open / retrospective / newest | 5.5 / 8.7 / 1.8 (max ≤ 10) | ≤ 1.1 (max ≤ 2.0) | +| alerts, authority filter | 26.4 / 45.8 | 1.8 / 2.2 | +| alerts, page of 200 | 13.8 / 16.7 | 3.3 / 4.4 | + +50,000 alerts is a stress case (a realistic queue holds hundreds to a few thousand groups). + +## 10. Not claimed + +* No fraud detection, no fraud probabilities, no labels of people or organisations. +* No complete coverage: a sample of the public mempool.space view, with gaps recorded. +* No address clustering, so wallets that are not listed address by address are not found. +* No validated supervised model. +* No real-traffic results for the anomaly layer yet (the pipeline exists; the data must come + from a running collector). diff --git a/docs/TEMPORAL_ROBUSTNESS.md b/docs/TEMPORAL_ROBUSTNESS.md index 1c886f2..53cd500 100644 --- a/docs/TEMPORAL_ROBUSTNESS.md +++ b/docs/TEMPORAL_ROBUSTNESS.md @@ -6,17 +6,24 @@ investigation budgets? **Short answer.** The collapse after step 42 is mainly a **stale-model problem**, not an unlearnable one. A model fitted on recent labels ranks late-period transactions well, -while the model fitted on the past does not. Retraining as labels arrive raises pooled AP -on steps 43–49 from 0.05 to 0.42–0.49, and the gain is consistent across seeds, -strategies and bootstrap schemes. It shrinks with longer label latency and cannot help -the first steps after the change, before any new labels exist. Steps 35–49 were inspected -in Phase 1, so every number on that period is **exploratory**. +while the model fitted on the past does not. Over the whole confirm period 35–49, the +protocol's primary comparison, retraining as labels arrive raises pooled AP from 0.807 +to 0.892 (expanding; ΔAP +0.085 [0.024, 0.229]). The gain is concentrated after the +shift: on steps 43–49 (a sub-period whose boundary was chosen from Phase 1 inspection) +pooled AP rises from 0.05 to 0.39–0.49 for the four selected strategies (expanding 0.46), +and the direction is consistent across seeds, strategies and bootstrap schemes. That +sub-period has only 7 steps, so its intervals are imprecise. The gain shrinks with longer +label latency and cannot help the first steps after the change, before any new labels +exist. Steps 35–49 were inspected in Phase 1, so every number on that period is +**exploratory**. Every number in this report comes from generated files. The main sources are [`reports/phase2/backtest/README.md`](../reports/phase2/backtest/README.md), [`reports/phase2/shift/summary.json`](../reports/phase2/shift/summary.json) and -[`reports/phase2/audit.json`](../reports/phase2/audit.json). The pre-registered protocol, -with its list of deviations, is [PHASE2_PROTOCOL.md](PHASE2_PROTOCOL.md). +[`reports/phase2/audit.json`](../reports/phase2/audit.json). The protocol, with its list +of deviations, is [PHASE2_PROTOCOL.md](PHASE2_PROTOCOL.md). It was fixed before the runs +according to the author's record; the published git history cannot verify this (see its +status note), so "pre-registered" below means "fixed before the runs (author's record)". --- @@ -40,7 +47,7 @@ metrics with plain scikit-learn. the period, which is the very information Phase 1 excluded by dropping `Time step`. §4.3 tests whether this matters. It does not, materially. -## 2. Setup (pre-registered) +## 2. Setup (fixed before the runs; author's record) * **Prediction-time model.** Each step is scored at its end. A label from step *u* becomes available at the end of step *u + L*. **Primary analysis L = 1**; sensitivity L = 3. @@ -73,14 +80,14 @@ expanding). The optimum may lie beyond the grid. The grid was not extended after | aspect | evidence | interpretation | |---|---|---| | **Prior shift**, P(y) | Illicit share of labelled transactions: 0.109 (steps 1–29), 0.168 (30–34), 0.092 (35–42), **0.025 (43–49)**; per step it ranges from 0.003 to 0.36 | Large, and it lowers AP mechanically. | -| …but not only prior shift | Static model ROC-AUC (prevalence-invariant): 0.97 on 35–42, **0.70** on 43–49. AP standardised to prevalence 0.109: 0.92 versus **0.17** | Ranking quality itself collapses. | +| …but not only prior shift | Past-only XGBoost (labels of steps 1–34, the within-period diagnostic's "past" model): ROC-AUC (prevalence-invariant) 0.97 on 35–42, **0.70** on 43–49; AP standardised to prevalence 0.109: 0.93 versus **0.18**. Other "static" models agree: Phase 1 XGBoost/all (labels 1–29) ROC-AUC 0.97 → **0.69** (`audit.json`); Phase 2 backtest static (refit at step 34, L = 1) 0.97 → **0.73**, standardised AP 0.93 → 0.19 | Ranking quality itself collapses. | | **Covariate shift**, P(x) | A step-level domain classifier separates *every* step from steps 1–29 with AUC ≈ 1.0, even with the time proxies removed (per-step minimum 0.997, period means 0.9985–0.99997). Period means of the median per-feature KS against steps 1–29 lie between 0.075 and 0.094 for local and aggregate features in every period, with **no jump at step 43** | Each step is identifiable from its features, so domain AUC cannot measure *how much* shift matters (a negative result for this diagnostic). Bulk marginal shift does not coincide with the collapse. | -| Missingness | Labelled missing-feature rate: 0.6% (1–29), 1.0% (30–34), **2.9% (35–42)**, 1.0% (43–49) | Peaks before the collapse, not during it. Not an explanation. | +| Missingness | Labelled missing-feature rate, mean of per-step rates: 0.6% (1–29), 1.0% (30–34), **2.9% (35–42)**, 1.0% (43–49); pooled over rows: 0.58%, 1.17%, **2.34%**, 1.35% | Peaks before the collapse, not during it. Not an explanation. | | **Class-conditional shift**, P(x\|y) | Per-class domain classifiers are saturated as well (AUC ≥ 0.99) | Uninformative at this resolution. | -| **Signs of concept shift**, P(y\|x) | On 43–49, the past-only model scores AP 0.053 (ROC 0.70). A leave-one-step-out model fitted only on *other late steps* scores **AP 0.811** (ROC 0.98). Past plus late scores 0.753, worse than late alone. On 35–42 all three models are similar (0.92 / 0.95 / 0.95) | Late illicit transactions are **predictable from these features**, but not by the boundary learned from the past, and adding past data slightly hurts. This fits concept shift, or class-conditional shift into regions the training data never covered. The data cannot separate the two, and no causal claim is made. (LOSO uses later steps, so this is diagnostic only.) | +| **Signs of concept shift**, P(y\|x) | On 43–49, the past-only model (labels 1–34) scores AP 0.053 (ROC 0.70). A leave-one-step-out model fitted only on *other late steps* scores **AP 0.811** (ROC 0.98). Past plus late scores 0.753, worse than late alone. On 35–42 all three models are similar (0.92 / 0.95 / 0.95) | Late illicit transactions are **predictable from these features**, but not by the boundary learned from the past, and adding past data slightly hurts. This fits concept shift, or class-conditional shift into regions the training data never covered. The data cannot separate the two, and no causal claim is made. (LOSO uses later steps, so this is diagnostic only.) | | **Scores** | Median static score of illicit transactions is ≥ 0.994 on every step from 35 to 42, and ≤ 0.008 on steps 43–49 except step 46 (2 illicit) | Late illicit transactions look licit to the old model. | -| **Calibration** (Platt fitted on 30–34) | ECE 0.010 (30–34), 0.018 (35–42), 0.047 (43–49), reaching 0.138 at step 49; mean predicted 0.029 against observed 0.118 at step 49 | Calibration degrades and the model under-predicts late. | -| **Budgets** | Static P@20 per step averages 1.00 on 35–42, and on 43–49 it is between 0.00 and 0.25 (0 at four of seven steps) (see `static_model_by_step.csv`) | The operational failure is total, not just a metric artefact. | +| **Calibration** (Phase 1 XGBoost/all, Platt fitted on 30–34) | ECE 0.010 (30–34, **in-sample**: the calibrator was fitted on these steps), 0.018 (35–42), 0.047 (43–49), reaching 0.138 at step 49; mean predicted 0.029 against observed 0.118 at step 49. Period ECE and Brier values are means of per-step values, not pooled | Calibration degrades and the model under-predicts late. | +| **Budgets** | Phase 1 XGBoost/all P@20 per step is 1.00 at every step of 35–42, and on 43–49 it is between 0.00 and 0.25 (0 at three of seven steps: 43, 45, 47) (see `static_model_by_step.csv`) | The operational failure is near-total, not just a metric artefact. | Weber et al. (2019) attribute the regime change after step 43 in the original Elliptic data to the shutdown of a dark market. Our data are consistent with a change in what @@ -105,7 +112,15 @@ Seed standard deviation of pooled AP is ≤ 0.003 on dev and confirm overall, an on 43–49. Training stochasticity is negligible next to temporal uncertainty. On steps 35–42 the gains are small: +0.008 to +0.016 AP, with the CIs of expanding, -recency h = 10 and sliding W = 10 touching 0. +recency h = 10 and sliding W = 10 including or touching 0 (periodic f = 2: +0.008 +[0.001, 0.014]). + +Per step, all four selected strategies beat static at every one of the seven steps +43–49 (seed means, `per_step_confirm.csv`). For expanding this gives an exact one-sided +sign test p = 1/128 ≈ 0.008; this is a descriptive check on an exploratory period, not +a pre-specified test. The 43–49 intervals come from a block bootstrap over only 7 steps +(block length 3), which has few distinct resamples, so their coverage is probably below +the nominal 95%. ### 4.2 Investigation budgets (confirm 43–49; seed means) @@ -123,7 +138,8 @@ transactions: **Important caveat.** When **all** transactions are ranked, with the unknown class competing for the same budget and counted as misses, every strategy finds **0–2** known -illicit transactions at K = 10–20 per step in 43–49, and 14–20 at K = 50. The top of the +illicit transactions *in total* over steps 43–49 with K = 10–20 reviews per step. At +K = 50 the retrained strategies find 14–20 in total and static finds 0.4. The top of the ranking is dominated by unlabelled transactions. They could be unlabelled illicit activity or false positives; the dataset cannot tell. Labelled-only budget metrics therefore overstate deployable value. @@ -131,7 +147,7 @@ therefore overstate deployable value. On 35–42, all strategies find 366–368 of 373 possible at K = 50: a ceiling, with no room to differ. -### 4.3 Pre-registered robustness verdicts (protocol §5) +### 4.3 Robustness verdicts (protocol §5) | strategy | pooled AP | hits@50 | |---|---|---| @@ -143,7 +159,12 @@ to differ. "Robust" means the 95% CI excludes 0 with the same sign in dev and confirm, and both confirm sub-periods share that sign. For hits@50, the rule fails only because the 35–42 difference is 0.0 to −0.8 at the ceiling described above. That is a ceiling effect, not -a reversal. The rule is reported as pre-registered and was not relaxed. +a reversal. The rule is reported as specified in the protocol and was not relaxed. +Two cautions: the dev half of the rule is evaluated on the parameter that won the dev +selection, so for periodic, sliding and recency its dev interval carries a +winner's-curse bias (static and expanding have no tuned parameter; for every strategy +the confirm interval is the more informative half); and the sub-period sign check rests on the 43–49 boundary, +which was chosen from Phase 1 inspection. ### 4.4 Sensitivity @@ -155,9 +176,13 @@ a reversal. The rule is reported as pre-registered and was not relaxed. [0.016, 0.191], recency h = 10 +0.059 [0.012, 0.159], and sliding W = 10 +0.048 [−0.003, 0.160]. **The value of adaptation depends on how quickly labels arrive.** * **Time-proxy ablation (exploratory).** Removing the five clock-like features changes - pooled AP by at most ±0.004 overall. On 43–49 it is unchanged for static (0.050) and - slightly lower for the adaptive strategies (−0.020 to −0.038, every CI including 0 or - touching it). The clock features neither cause the collapse nor drive the recovery. + pooled AP by at most ±0.004 overall. On dev it *raises* pooled AP slightly for every + strategy (+0.001 to +0.004; the CIs exclude 0 except expanding, whose CI touches 0). + On confirm overall it changes pooled AP by at most 0.002 (every CI includes 0). On + 43–49 it is unchanged for static (0.050) and lower for the adaptive strategies (−0.020 + to −0.038, every CI including 0 or touching it). The proxies were identified from + features of steps ≤ 34, which includes the dev-scored steps. The clock features + neither cause the collapse nor drive the recovery. ### 4.5 Per-period behaviour and failure cases @@ -196,9 +221,12 @@ reason to stay static. step is identifiable from its features, with or without the time proxies, so it cannot rank how much the shift matters. KS statistics show no change in bulk marginal shift at the collapse. A drift detector built on feature marginals would - probably not have warned about step 43. -2. **Removing time-proxy features did not help**, and slightly hurt the adaptive models - late. + probably not have warned about step 43, though no such detector was actually run. +2. **Removing time-proxy features made little difference.** It gave a small but + consistent gain on dev (+0.001 to +0.004 pooled AP, CIs excluding or touching 0), no + change on confirm overall, and lower point estimates for the adaptive models on 43–49 + (−0.020 to −0.038, CIs including or touching 0). The proxies were selected using + steps ≤ 34, so the dev comparison is not fully independent of that choice. 3. **No strategy improves meaningfully over static on 35–42**, where the static model is already near its ceiling. 4. **Recency weighting is not reliably better than plain expanding retraining.** The @@ -206,7 +234,7 @@ reason to stay static. overlap heavily. No paired recency-versus-expanding test was pre-registered, so no difference is claimed. Short half-lives (h = 2) had lower pooled AP than expanding in every period. -5. **The budget-metric gains are not robust** under the pre-registered rule (a ceiling +5. **The budget-metric gains are not robust** under the protocol's rule (a ceiling effect), and they mostly disappear when unlabelled transactions compete for review slots. 6. **Calibration** was diagnosed, not fixed. Recalibration under prior shift is open. @@ -251,7 +279,8 @@ schedule, not the architecture, drives the temporal gains. expanding-window, L = 1 backtest and bootstrap. Compare it first against a cheaper control, XGBoost plus multi-hop graph features (for example two-hop aggregates and neighbour-score propagation). Pre-register steps 43–45 as the primary target and a new -holdout rule. Alternatives that the evidence supports at least as strongly: label +holdout rule, and publish that protocol (a timestamped commit or registry entry) before +any run, so that its timing can be verified. Alternatives that the evidence supports at least as strongly: label latency and labelling strategy (active or prioritised labelling to shorten effective L), and recalibration under prior shift. diff --git a/frontend/index.html b/frontend/index.html index 57cb3b8..ef71b74 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -3,7 +3,7 @@ - ChainWatch replay + ChainWatch
diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 80bd973..3b0bbd8 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "chainwatch-dashboard", - "version": "0.4.1", + "version": "0.8.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "chainwatch-dashboard", - "version": "0.4.1", + "version": "0.8.1", "dependencies": { "d3-force": "3.0.0", "react": "18.3.1", @@ -20,7 +20,7 @@ "@vitejs/plugin-react": "4.7.0", "typescript": "5.6.3", "vite": "6.4.4", - "vitest": "4.1.11" + "vitest": "4.1.12" } }, "node_modules/@babel/code-frame": { @@ -1407,16 +1407,16 @@ } }, "node_modules/@vitest/expect": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.11.tgz", - "integrity": "sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw==", + "version": "4.1.12", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.12.tgz", + "integrity": "sha512-vFlTt+YEu9WBpNjdGayNmlMVzrWPi1+sv853/7t2FU7hpO5gAFBKHzQmkCq5Xjpr+evegF2994LQT3hF3mRlqQ==", "dev": true, "license": "MIT", "dependencies": { "@standard-schema/spec": "^1.1.0", "@types/chai": "^5.2.2", - "@vitest/spy": "4.1.11", - "@vitest/utils": "4.1.11", + "@vitest/spy": "4.1.12", + "@vitest/utils": "4.1.12", "chai": "^6.2.2", "tinyrainbow": "^3.1.0" }, @@ -1425,13 +1425,13 @@ } }, "node_modules/@vitest/mocker": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.11.tgz", - "integrity": "sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==", + "version": "4.1.12", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.12.tgz", + "integrity": "sha512-fKShNpKZzupWZuY0z7egydvL0sqW4INEZBEExMBMAa6izlENEVHwoXgdaTCaBZ5fwlr4xf2o1wXC83n9RpO+NA==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/spy": "4.1.11", + "@vitest/spy": "4.1.12", "estree-walker": "^3.0.3", "magic-string": "^0.30.21" }, @@ -1452,9 +1452,9 @@ } }, "node_modules/@vitest/pretty-format": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.11.tgz", - "integrity": "sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw==", + "version": "4.1.12", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.12.tgz", + "integrity": "sha512-XW9O8+Mxx4VpCtkYdMJLZQQwsVryP9wk7cPKDxtXFfwSak6yRh5+2fep/Y0XF/ElBvJHq8bcYdi6aeuai0opZA==", "dev": true, "license": "MIT", "dependencies": { @@ -1465,13 +1465,13 @@ } }, "node_modules/@vitest/runner": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.11.tgz", - "integrity": "sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw==", + "version": "4.1.12", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.12.tgz", + "integrity": "sha512-NKlVKCr5QnCe8jijdMnmkpHHU+WTqiLFR6G0pHji9uRjXK9xJl1k1nTw6F3pOOj2PDcsDt2GKQMI7wIsaT491w==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/utils": "4.1.11", + "@vitest/utils": "4.1.12", "pathe": "^2.0.3" }, "funding": { @@ -1479,14 +1479,14 @@ } }, "node_modules/@vitest/snapshot": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.11.tgz", - "integrity": "sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog==", + "version": "4.1.12", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.12.tgz", + "integrity": "sha512-ko1y1Qgb/slzQ9mr+b89Cuqud8WG1TKtsPD8r7ZUBdvVOGt85Af2HwCqHujrhwJq95hs/9RM7fcAPg57o1vlzw==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/pretty-format": "4.1.11", - "@vitest/utils": "4.1.11", + "@vitest/pretty-format": "4.1.12", + "@vitest/utils": "4.1.12", "magic-string": "^0.30.21", "pathe": "^2.0.3" }, @@ -1495,9 +1495,9 @@ } }, "node_modules/@vitest/spy": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.11.tgz", - "integrity": "sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==", + "version": "4.1.12", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.12.tgz", + "integrity": "sha512-RGq9x4JNGNTZHEJxvN0oSiJjeSCExm0n2gZKKJZHY9cX5AVA6M7VJILBT3ZJ/tJ/0J9uWT7fETV9/btoi//vSg==", "dev": true, "license": "MIT", "funding": { @@ -1505,13 +1505,13 @@ } }, "node_modules/@vitest/utils": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.11.tgz", - "integrity": "sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==", + "version": "4.1.12", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.12.tgz", + "integrity": "sha512-Q3awXrwOfEV+qc3WmO5ONyE0yO7Q1gQ9/oyHxGLZ/pl7N3NO/ZztqQwKLuwMkV+CA1JYSIeO3gkHnRDIo4AVaA==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/pretty-format": "4.1.11", + "@vitest/pretty-format": "4.1.12", "convert-source-map": "^2.0.0", "tinyrainbow": "^3.1.0" }, @@ -2564,19 +2564,19 @@ } }, "node_modules/vitest": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.11.tgz", - "integrity": "sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw==", + "version": "4.1.12", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.12.tgz", + "integrity": "sha512-5eWdz2yb3ajxWF3C8C4TjkXl7FGm3n2E/VlazALrQHzK7nYMSGFnCZto0bbPNl77AwkOZVLk0YnBAejUu0NiWA==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/expect": "4.1.11", - "@vitest/mocker": "4.1.11", - "@vitest/pretty-format": "4.1.11", - "@vitest/runner": "4.1.11", - "@vitest/snapshot": "4.1.11", - "@vitest/spy": "4.1.11", - "@vitest/utils": "4.1.11", + "@vitest/expect": "4.1.12", + "@vitest/mocker": "4.1.12", + "@vitest/pretty-format": "4.1.12", + "@vitest/runner": "4.1.12", + "@vitest/snapshot": "4.1.12", + "@vitest/spy": "4.1.12", + "@vitest/utils": "4.1.12", "es-module-lexer": "^2.0.0", "expect-type": "^1.3.0", "magic-string": "^0.30.21", @@ -2604,12 +2604,12 @@ "@edge-runtime/vm": "*", "@opentelemetry/api": "^1.9.0", "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", - "@vitest/browser-playwright": "4.1.11", - "@vitest/browser-preview": "4.1.11", - "@vitest/browser-webdriverio": "4.1.11", - "@vitest/coverage-istanbul": "4.1.11", - "@vitest/coverage-v8": "4.1.11", - "@vitest/ui": "4.1.11", + "@vitest/browser-playwright": "4.1.12", + "@vitest/browser-preview": "4.1.12", + "@vitest/browser-webdriverio": "^4.1.11", + "@vitest/coverage-istanbul": "4.1.12", + "@vitest/coverage-v8": "4.1.12", + "@vitest/ui": "4.1.12", "happy-dom": "*", "jsdom": "*", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" diff --git a/frontend/package.json b/frontend/package.json index 3a464f4..7c53359 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,7 @@ { "name": "chainwatch-dashboard", "private": true, - "version": "0.4.1", + "version": "0.8.1", "type": "module", "scripts": { "dev": "vite", @@ -22,6 +22,6 @@ "@vitejs/plugin-react": "4.7.0", "typescript": "5.6.3", "vite": "6.4.4", - "vitest": "4.1.11" + "vitest": "4.1.12" } } diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index fd11299..794ce5a 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,34 +1,94 @@ -import { useEffect, useState } from "react"; +import { useCallback, useEffect, useRef, useState, type KeyboardEvent } from "react"; import { api, type Info } from "./lib/api"; +import { shortCommit } from "./lib/format"; import ReplayView from "./components/ReplayView"; import PerformanceView from "./components/PerformanceView"; import ModelsView from "./components/ModelsView"; import AboutView from "./components/AboutView"; +import LiveView from "./components/LiveView"; -const TABS = ["Replay", "Performance", "Models & experiments", "Limitations"] as const; +const TABS = ["Replay", "Performance", "Models & experiments", "Limitations", "Live monitor"] as const; type Tab = (typeof TABS)[number]; +const slug = (t: Tab) => t.toLowerCase().replace(/[^a-z]+/g, "-"); +// the tab lives in the URL hash, so reload and back/forward keep it +const tabFromHash = (): Tab => TABS.find((t) => `#${slug(t)}` === window.location.hash) ?? "Replay"; export default function App() { const [info, setInfo] = useState(null); const [error, setError] = useState(null); - const [tab, setTab] = useState("Replay"); - + const [tab, setTabState] = useState(tabFromHash); + // Live monitor stays mounted after its first visit (hidden when another tab is active): + // remounting it on every switch fired 7 requests and a new event stream each time, which + // ordinary tab switching turned into 429s against the per-client limit + const [liveVisited, setLiveVisited] = useState(tab === "Live monitor"); + const tabRefs = useRef<(HTMLButtonElement | null)[]>([]); + const setTab = useCallback((t: Tab) => { + setTabState(t); + if (window.location.hash !== `#${slug(t)}`) window.history.pushState(null, "", `#${slug(t)}`); + }, []); + useEffect(() => { + // only a tab's own hash switches tabs: skip links (#main, #findings-h) must not + const onHash = () => { + const t = TABS.find((x) => `#${slug(x)}` === window.location.hash); + if (t) setTabState(t); + }; + window.addEventListener("hashchange", onHash); + window.addEventListener("popstate", onHash); + return () => { + window.removeEventListener("hashchange", onHash); + window.removeEventListener("popstate", onHash); + }; + }, []); useEffect(() => { + if (tab === "Live monitor") setLiveVisited(true); + }, [tab]); + + const loadInfo = useCallback(() => { + setError(null); api.info().then(setInfo).catch((e) => setError(String(e.message ?? e))); }, []); + useEffect(loadInfo, [loadInfo]); + + useEffect(() => { + document.title = `${tab} · ChainWatch`; + }, [tab]); + + // WAI-ARIA tabs: arrow keys / Home / End move between tabs (automatic activation). + const onTabKey = (e: KeyboardEvent, i: number) => { + const n = TABS.length; + const j = + e.key === "ArrowRight" ? (i + 1) % n + : e.key === "ArrowLeft" ? (i - 1 + n) % n + : e.key === "Home" ? 0 + : e.key === "End" ? n - 1 + : null; + if (j === null) return; + e.preventDefault(); + setTab(TABS[j]); + tabRefs.current[j]?.focus(); + }; - const synthetic = info?.data_mode === "synthetic"; + const live = tab === "Live monitor"; + const syntheticData = info?.data_mode === "synthetic"; + const synthetic = syntheticData && !live; return (
+ Skip to content

ChainWatch

- Historical replay of illicit-transaction risk ranking on Elliptic++ - {info && ( + + {live + ? "Live Bitcoin mempool monitor" + : syntheticData + ? "Replay of risk ranking on synthetic demo data (Elliptic++ schema)" + : "Historical replay of illicit-transaction risk ranking on Elliptic++"} + + {info && !live && ( {synthetic ? "SYNTHETIC DEMO DATA" : "Elliptic++ · historical replay"} )} - {info && label latency L = {info.label_latency_steps} step} + {info && !live && label latency L = {info.label_latency_steps} step}
{synthetic && (
@@ -37,25 +97,46 @@ export default function App() { experiments” come from committed reports on the real dataset.
)} -
- Replay of a published, historical dataset: not live blockchain monitoring. Scores rank - transactions by similarity to past illicit labels. They are not verdicts and not calibrated - probabilities. “Unknown” transactions are unlabelled, never assumed licit. -
- {error &&

API unavailable: {error}

} -
); diff --git a/frontend/src/components/AboutView.tsx b/frontend/src/components/AboutView.tsx index 40a8e2b..3cc7a4b 100644 --- a/frontend/src/components/AboutView.tsx +++ b/frontend/src/components/AboutView.tsx @@ -6,7 +6,11 @@ export default function AboutView({ info }: { info: Info }) {

What this application is

A replay of a published, historical research dataset (Elliptic++: Bitcoin transactions from - 49 time steps of roughly two weeks each). For each step it shows how a frozen model snapshot + 49 time steps of roughly two weeks each). + {info.data_mode === "synthetic" && ( + This deployment serves synthetic demo data with the Elliptic++ schema, not the dataset + itself: every replay number describes that synthetic data. + )} For each step it shows how a frozen model snapshot would have ranked that step's transactions, using only labels available at the time (label latency L = {info.label_latency_steps}). It is not real-time blockchain monitoring.

diff --git a/frontend/src/components/LiveView.tsx b/frontend/src/components/LiveView.tsx new file mode 100644 index 0000000..8c62e37 --- /dev/null +++ b/frontend/src/components/LiveView.tsx @@ -0,0 +1,829 @@ +import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { Bar, BarChart, CartesianGrid, Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts"; +import { ApiError, type Info } from "../lib/api"; +import { revealIfStacked } from "../lib/dom"; +import { + ago, + applyRecentPage, + confirmedLabel, + connectionView, + eventsUrl, + explorerHref, + FEED_LAG_S, + feedLag, + filterSort, + formatDuration, + formatSat, + liveApi, + maxRowId, + mergeFeed, + OUTAGE_LABEL, + outageDuration, + reconnectDelay, + relatedExplorerHref, + shortTxid, + sourceBadge, + throughputSeries, + utcStamp, + type FeedFilter, + type LiveDetail, + type LiveRow, + type LiveStats, + type LiveStatus, + type Outage, + type SortKey, + type ThroughputPoint, +} from "../lib/live"; +import { + authoritiesOf, + NO_ALERTS_FILTER, + NO_FINDINGS_FILTER, + PAGE_SIZE, + priorityByTxid, + riskApi, + riskState as riskStateOf, + type Alert, + type AlertsFilter, + type Finding, + type FindingsFilter, + type PageInfo, + type PriorityLevel, + type RiskSummary, +} from "../lib/risk"; +import { useNow } from "../lib/useNow"; +import { Tile } from "./common"; +import { + InvestigationQueue, + PriorityLegend, + PriorityMarker, + RecentFindings, + RiskAssessment, + RiskOverview, + type DataKind, + type ListState, + type PageAction, +} from "./RiskPanels"; + +const SORTS: Record = { + newest: "Newest first", + fee_rate: "Fee rate (high first)", + vsize: "Virtual size (large first)", + n_outputs: "Outputs (most first)", + fee: "Absolute fee (high first)", +}; + +const STATUS_POLL_MS = 5000; +const STATS_POLL_MS = 15000; +const RISK_POLL_MS = 15000; +/** Fallback for the event stream: poll the newest rows while it is not open or the feed lags. */ +const FEED_POLL_MS = 15000; +/** Feed priorities learnt from loaded findings pages (for rows the stream sent unassessed). */ +const PRIORITY_MEMORY = 2000; + +type PageFetch = (f: F, cursor: string | null) => Promise<{ items: T[]; page?: PageInfo }>; +const fetchFindings: PageFetch = (f, c) => + riskApi.findingsPage(f, PAGE_SIZE, c).then((r) => ({ items: r.findings ?? [], page: r.page })); +const fetchAlerts: PageFetch = (f, c) => + riskApi.alertsPage(f, PAGE_SIZE, c).then((r) => ({ items: r.alerts ?? [], page: r.page })); + +/** One server-paged list: filter, cursor stack (page k = cursors[k]) and the loaded page. + * The latest request wins; a filter or page change clears the rows first, so rows are never + * shown under a filter or page they do not belong to. `reload` refreshes the current page. */ +function usePagedList(initial: F, fetchPage: PageFetch) { + const [list, setList] = useState>({ items: null, info: null, page: 0, error: null, busy: false }); + const [filter, setFilterState] = useState(initial); + const ref = useRef({ filter: initial, cursors: [null] as (string | null)[], info: null as PageInfo | null, seq: 0 }); + const reload = useCallback(async () => { + const r = ref.current; + const seq = ++r.seq; + const page = r.cursors.length - 1; + try { + const res = await fetchPage(r.filter, r.cursors[page]); + if (seq !== r.seq) return; + // an older collector API answers without page details: one unpaged list, total unknown + const info = res.page ?? { limit: PAGE_SIZE, total: null, next_cursor: null, available: true }; + r.info = info; + setList({ items: res.items, info, page, error: null, busy: false }); + } catch (e) { + if (seq !== r.seq) return; + setList((l) => ({ ...l, error: describeRiskError(e), busy: false })); + } + }, [fetchPage]); + const navigate = useCallback((cursors: (string | null)[]) => { + ref.current.cursors = cursors; + setList((l) => ({ items: null, info: l.info, page: cursors.length - 1, error: null, busy: true })); + void reload(); + }, [reload]); + const setFilter = useCallback((f: F) => { + ref.current.filter = f; + setFilterState(f); + navigate([null]); + }, [navigate]); + const onPage = useCallback((a: PageAction) => { + const { cursors, info } = ref.current; + if (a === "first") navigate([null]); + else if (a === "prev" && cursors.length > 1) navigate(cursors.slice(0, -1)); + else if (a === "next" && info?.next_cursor) navigate([...cursors, info.next_cursor]); + }, [navigate]); + return { list, filter, setFilter, onPage, reload }; +} + +// Recharts' default tooltip is white with inherited text colour: unreadable in dark mode. +const TOOLTIP = { + contentStyle: { + fontSize: 12, + background: "var(--surface)", + border: "1px solid var(--border)", + borderRadius: 6, + color: "var(--ink)", + }, + labelStyle: { color: "var(--ink-2)" }, + itemStyle: { color: "var(--ink)" }, +} as const; +const AXIS_TICK = { fill: "var(--muted)", fontSize: 11 }; + +const errText = (e: unknown) => (e instanceof Error ? e.message : String(e)); +const num = (v: number | string | null | undefined) => (typeof v === "number" ? v : null); + +function describeRiskError(e: unknown): string { + if (e instanceof ApiError && e.status === 404) return "not available on this server (older version without risk intelligence)"; + return errText(e); +} + +type LiveProblem = { noData: true } | { noData: false; text: string }; + +function describeLiveError(e: unknown): LiveProblem { + if (e instanceof ApiError && e.code === "live_no_data") return { noData: true }; + return { noData: false, text: `Live API unavailable: ${errText(e)}` }; +} + +function SourceBadge({ status }: { status: LiveStatus | null }) { + const b = sourceBadge(status); + const cls = b.kind === "real" ? "real" : b.kind === "mock" ? "synthetic" : "unknown"; + return {b.text}; +} + +/** Re-renders each second (staleness depends on the clock); nothing else does. */ +function ConnectionBadge(props: { + status: LiveStatus | null; + statusAt: number | null; + apiError: boolean; + noData: boolean; + refreshing: boolean; +}) { + const now = useNow(); + const v = connectionView(props.status, { + now, statusAt: props.statusAt, apiError: props.apiError, noData: props.noData, refreshing: props.refreshing, + }); + return ( + <> + +