From a4ea181f919ca833a5f8a1b1c02b129b8253c2c7 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 14 Oct 2026 02:23:58 +0000 Subject: [PATCH 01/67] Phase 5: live Bitcoin mempool monitor MVP (v0.5.0) Opt-in, zero-cost pipeline from the public mempool.space API to a "Live monitor" tab, isolated from the historical research and the synthetic demo. - chainwatch live-collect (src/chainwatch/live/): WebSocket track-mempool-txids -> validated, deduplicated (bounded LRU), hash-sampled txids -> bounded queue -> token-bucket-limited REST detail fetches (timeouts, HTTP 429 Retry-After pause) -> observation-time features + rule-based indicators -> SQLite (WAL, idempotent, bounded retention). Exponential backoff with jitter, staleness watchdog, graceful shutdown, metrics. - Read-only /v1/live/{status,transactions,transactions/{txid},stats,events} with SSE; 404 live_disabled unless live.enabled (only configs/live.yaml); the API never contacts mempool.space; non-mempool.space sources are labelled as mock data. - Live monitor tab: connection state, throughput and fee-rate charts, filterable feed, detail panel with explorer links; real, synthetic and mock data labelled separately. - Bitcoin semantics: output sums include change (never a payment amount); input references are observable spends only (no ownership inference). No Elliptic++ model is applied to live data. - API contract verified against mempool's open-source backend (commit 4cf96d2); real ingestion could not be verified here (egress proxy returns 403 for mempool.space). - Tests: 44 new Python tests with local WebSocket/REST mocks, frontend helper tests; scripts/live_load_test.py, scripts/mock_mempool.py; docs/LIVE_MONITOR.md, docs/LIVE_ML_PROPOSAL.md. render.yaml stays on the 0.4.1 demo image; no research result changed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014FbdkMvyfPtk41mcHA7eR7 --- .gitignore | 1 + CHANGELOG.md | 25 ++ README.md | 51 +++- configs/live.yaml | 13 + docs/INTERVIEW_GUIDE.md | 2 +- docs/LIVE_ML_PROPOSAL.md | 83 ++++++ docs/LIVE_MONITOR.md | 182 ++++++++++++ docs/PORTFOLIO.md | 4 +- frontend/package-lock.json | 4 +- frontend/package.json | 2 +- frontend/src/App.tsx | 29 +- frontend/src/components/LiveView.tsx | 292 +++++++++++++++++++ frontend/src/lib/api.ts | 1 + frontend/src/lib/live.test.ts | 49 ++++ frontend/src/lib/live.ts | 173 +++++++++++ frontend/src/styles.css | 17 ++ pyproject.toml | 2 +- scripts/live_load_test.py | 99 +++++++ scripts/mock_mempool.py | 85 ++++++ src/chainwatch/__init__.py | 2 +- src/chainwatch/cli.py | 38 +++ src/chainwatch/config.py | 53 +++- src/chainwatch/live/__init__.py | 6 + src/chainwatch/live/collector.py | 413 +++++++++++++++++++++++++++ src/chainwatch/live/features.py | 178 ++++++++++++ src/chainwatch/live/protocol.py | 111 +++++++ src/chainwatch/live/store.py | 304 ++++++++++++++++++++ src/chainwatch/serving/app.py | 4 + src/chainwatch/serving/live_api.py | 207 ++++++++++++++ tests/live_fixtures.py | 102 +++++++ tests/test_live.py | 387 +++++++++++++++++++++++++ tests/test_live_api.py | 193 +++++++++++++ 32 files changed, 3079 insertions(+), 33 deletions(-) create mode 100644 configs/live.yaml create mode 100644 docs/LIVE_ML_PROPOSAL.md create mode 100644 docs/LIVE_MONITOR.md create mode 100644 frontend/src/components/LiveView.tsx create mode 100644 frontend/src/lib/live.test.ts create mode 100644 frontend/src/lib/live.ts create mode 100644 scripts/live_load_test.py create mode 100644 scripts/mock_mempool.py create mode 100644 src/chainwatch/live/__init__.py create mode 100644 src/chainwatch/live/collector.py create mode 100644 src/chainwatch/live/features.py create mode 100644 src/chainwatch/live/protocol.py create mode 100644 src/chainwatch/live/store.py create mode 100644 src/chainwatch/serving/live_api.py create mode 100644 tests/live_fixtures.py create mode 100644 tests/test_live.py create mode 100644 tests/test_live_api.py 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..a7dd3cc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,30 @@ # Changelog +## 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 diff --git a/README.md b/README.md index a31ad36..05e388b 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ [![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-309%20Python%20%2B%206%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?** @@ -13,9 +13,10 @@ 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 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** model. ![ChainWatch replay dashboard on synthetic demo data](docs/images/demo_replay.png) Replay dashboard running the synthetic demo (every screenshot in this repository uses @@ -107,6 +108,31 @@ 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. +* Real ingestion has **not** been verified from the build environment (its proxy blocks + mempool.space). 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). + ## Limitations - **No untouched holdout.** Steps 35–49 were inspected in Phase 1, so the retraining gains @@ -122,13 +148,13 @@ 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/ 309 tests: leakage canaries, metrics, backtest causality, API contract 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 +scripts/ screenshot capture, demo smoke test, mock mempool, live load test ``` ## Documentation @@ -139,7 +165,8 @@ 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) · [live ML proposal](docs/LIVE_ML_PROPOSAL.md) | Phase 5 data pipeline, API contract, limits, measurements | | [Interview guide](docs/INTERVIEW_GUIDE.md) · [portfolio material](docs/PORTFOLIO.md) | explanations and verified resume bullets | ## Development @@ -151,8 +178,10 @@ scripts/smoke_demo.sh http://localhost:8000 # end-to-end check of a running ``` **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 +and shift diagnostics, replay service and dashboard, Docker, CI, live mempool monitor MVP +(no model). 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/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/docs/INTERVIEW_GUIDE.md b/docs/INTERVIEW_GUIDE.md index c3ff5bc..ea8856e 100644 --- a/docs/INTERVIEW_GUIDE.md +++ b/docs/INTERVIEW_GUIDE.md @@ -147,7 +147,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 (309 tests):** schema and join, 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), diff --git a/docs/LIVE_ML_PROPOSAL.md b/docs/LIVE_ML_PROPOSAL.md new file mode 100644 index 0000000..95b40c7 --- /dev/null +++ b/docs/LIVE_ML_PROPOSAL.md @@ -0,0 +1,83 @@ +# 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`, so nothing leaks. +* **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, recorded at observation + time), 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. + +## 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. +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..9c0245f --- /dev/null +++ b/docs/LIVE_MONITOR.md @@ -0,0 +1,182 @@ +# 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, invalid txids, malformed frames, not sampled, queued, dropped, expired, fetched, failed, not found, rate limited, timeouts, malformed payloads, removed, replaced, connects, reconnects, stale reconnects | + +## 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/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 | + +## 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` and `replaced` events + are only counted. +* **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 local collector. Several collectors, or a hosted + deployment, would need a different store. diff --git a/docs/PORTFOLIO.md b/docs/PORTFOLIO.md index d8bb311..d35faf2 100644 --- a/docs/PORTFOLIO.md +++ b/docs/PORTFOLIO.md @@ -42,7 +42,7 @@ XGBoost model (AP 0.80 overall) collapsed after a regime change (AP 0.92 → 0.0 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 +scores match the research predictions exactly (234,596 of them), with 309 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. @@ -81,7 +81,7 @@ holdout, labels are heuristic, and the system does not score live transactions. 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 + 309 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/frontend/package-lock.json b/frontend/package-lock.json index 80bd973..97ce6ec 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "chainwatch-dashboard", - "version": "0.4.1", + "version": "0.5.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "chainwatch-dashboard", - "version": "0.4.1", + "version": "0.5.0", "dependencies": { "d3-force": "3.0.0", "react": "18.3.1", diff --git a/frontend/package.json b/frontend/package.json index 3a464f4..23b4e90 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,7 @@ { "name": "chainwatch-dashboard", "private": true, - "version": "0.4.1", + "version": "0.5.0", "type": "module", "scripts": { "dev": "vite", diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index fd11299..8f8c1cd 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -4,8 +4,9 @@ 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]; export default function App() { @@ -17,18 +18,23 @@ export default function App() { api.info().then(setInfo).catch((e) => setError(String(e.message ?? e))); }, []); - const synthetic = info?.data_mode === "synthetic"; + const live = tab === "Live monitor"; + const synthetic = info?.data_mode === "synthetic" && !live; return (

ChainWatch

- Historical replay of illicit-transaction risk ranking on Elliptic++ - {info && ( + + {live + ? "Live Bitcoin mempool monitor" + : "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,11 +43,13 @@ 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. -
+ {!live && ( +
+ 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}

}