From c50224b3dc0f112d2a221ab074223918f6fb065c Mon Sep 17 00:00:00 2001 From: Adlgr87 <164441450+Adlgr87@users.noreply.github.com> Date: Fri, 23 Oct 2026 18:07:18 +0000 Subject: [PATCH 01/17] =?UTF-8?q?docs:=20a=C3=B1ade=20auditor=C3=ADa=20t?= =?UTF-8?q?=C3=A9cnica=20completa=20del=20proyecto?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Informe en español con hallazgos ordenados por severidad (S/F/D/H/R/T/U), cada uno con evidencia archivo:línea y prueba reproducible: - 7 críticos/altos: pérdida de eventos en el indexador (cursor avanza tras un fallo), upsert_market con INSERT OR IGNORE, funciones admin del contrato inalcanzables, rate limiter eludible vía X-Forwarded-For, CSP que anula un botón, importe de apuesta corrompido con decimales, reserva permanente de wallet tras unlink. - 15 medios: navegación admin, modo grupo, multiplicadores sin fee, notificaciones de resolución, CI ausente, SRI del CDN, deploy.js, etc. - 25 menores + 19 símbolos de código muerto, hardcodes, rendimiento y tests. Solo documentación: no se modifica código de producción. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- AUDITORIA.md | 375 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 375 insertions(+) create mode 100644 AUDITORIA.md diff --git a/AUDITORIA.md b/AUDITORIA.md new file mode 100644 index 0000000..9a52d0c --- /dev/null +++ b/AUDITORIA.md @@ -0,0 +1,375 @@ +# Auditoría técnica — BetPoly_Bot + +**Fecha:** 2026-10-23 +**Alcance:** repositorio completo (`bot/`, `config.py`, `main.py`, `web/`, `contracts/`, `scripts/`, `tests/`). +**Commit auditado:** `6b50853` (rama `arena/de3be963-betpoly-bot`, igual a `origin/main`). +**Naturaleza de este documento:** **solo hallazgos documentados**. No se ha modificado ni una línea del proyecto. + +> Este informe está ordenado por severidad. Cada hallazgo indica evidencia reproducible (`archivo:línea`), impacto y, cuando aplica, la prueba ejecutada que lo confirma. +> La numeración (`S-*`, `F-*`, `D-*`, `H-*`, `R-*`, `T-*`) es estable para poder referenciarla en instrucciones posteriores. + +--- + +## 0. Resumen ejecutivo + +| Área | Veredicto | +| :--- | :--- | +| Contrato escrow (FunC) | ✅ Compila de forma determinista y pasa 22/22 comprobaciones en sandbox TVM | +| Backend no-custodial | ✅ Se mantiene el invariante: nunca hay claves privadas ni firma del lado servidor | +| Persistencia | ⚠️ Transacciones correctas, pero hay pérdida silenciosa de eventos on-chain (S-01) | +| Índice on-chain | ❌ Un error de persistencia descarta el evento para siempre (S-01) | +| API HTTP | ⚠️ Autenticación sólida; limitador de tasa eludible (S-04) | +| Capa Telegram (handlers) | ⚠️ 0 % de cobertura y varios defectos de navegación/entrada (F-01, F-04) | +| Mini App (`web/`) | ⚠️ Cableada correctamente, salvo un botón roto por CSP (S-05) | +| Código muerto / duplicado | ⚠️ 19 símbolos sin uso, 3 clones reales, 1 fachada de paquete sin consumidores | +| Hardcodeo | ⚠️ Sin secretos ni direcciones; sí constantes de dinero/tiempos dispersas | +| Dependencias | ✅ Fijadas y al día salvo `python-telegram-bot` (una major por detrás) | +| Automatización | ❌ No existe CI: los 119 tests nunca se ejecutan automáticamente | + +**Conteo:** 7 hallazgos críticos/altos · 15 medios · 25 menores, más 19 símbolos de código muerto. + +--- + +## 1. Metodología y evidencia + +Herramientas ejecutadas sobre el commit auditado: + +- `ruff` (0.17.2), `vulture` (2.16), `bandit` (1.9.4), `radon`, `jscpd` (4.x), `pip-audit` (2.10.1), `npm audit`. +- `pytest` con `pytest-cov` → **119 tests en verde, cobertura total 55 %**. +- `contracts/`: `node scripts/build.js`, `node tests/escrow.test.js` (22 comprobaciones), `npm audit`, `node scripts/deploy.js` (dry-run real). +- Arranque real de `scripts/dev_server.py` en el puerto 8080 y sondeo con `curl`. +- Pruebas de API con `aiohttp.test_utils.TestClient` sobre bases de datos desechables (`/tmp/audit*.db`), incluidos casos de abuso (rotación de `X-Forwarded-For`, montos límite, `limit`/`offset` extremos). +- Pruebas directas contra `bot.database` y `bot.chain.indexer` con clientes falsos para forzar fallos de persistencia. +- Lectura manual íntegra de `bot/api.py`, `bot/security.py`, `bot/database.py`, `bot/markets.py`, `bot/chain/*`, `bot/handlers/*`, `bot/keyboards.py`, `config.py`, `web/index.html`, `web/static/app.js`, `main.py`, `contracts/scripts/*.js` y secciones de `contracts/escrow.fc`. +- Verificación de versiones publicadas hoy en PyPI y npm contra los *pins* del repositorio. + +--- + +## 2. Lo que sí está verificado y funciona + +Para que el listado de problemas no dé una impresión falsa del estado del proyecto: + +1. **Contrato:** `node scripts/build.js` reproduce exactamente el hash fijado en `tests/test_contract_sync.py::CODE_HASH` → `a29c5c51fe93597967c6d37c976a27e989d13662117165dec1d899fe3292db9b`. Compilación determinista y verificable. +2. **Suite del contrato:** 22/22 comprobaciones en `@ton/sandbox` (crear, apostar, resolver, reclamar, cancelar, reembolsos, pausa, fees). +3. **Suite Python:** 119 tests, 0 fallos, sin red. +4. **Arranque de la Mini App:** `scripts/dev_server.py` responde `200` en `/`, `/api/health` y devuelve mercados sembrados en `/api/markets`. +5. **`main.py --check`:** valida de verdad y sale con código `2` ante configuración inválida (probado con `BET_MODE=hybrid` sin `ESCROW_ADDRESS` y con `PUBLIC_BASE_URL` en `http://`). +6. **`deploy.js`:** dry-run correcto, exit `1` con dirección inválida, exit `0` con datos válidos; no envía transacciones en dry-run. +7. **Validación de importes (crítica para dinero):** matriz probada contra `/api/markets/{id}/bets/prepare` → `-5e9` → `stake_too_low`, `1e18` → `stake_too_high`, `true` → `bad_amount`, `"1e9"` → `bad_amount`, `"0.000000001"` → `stake_too_low`, sin wallet → `wallet_required`. **Correcto.** +8. **Cadena de autenticación:** `initData` (HMAC) → nonce de un solo uso (`ton_proof`) → `verify_ton_proof` (valida `state_init.hash == address_hash` y luego la firma) → `link_wallet`. Sin fugas: `/api/me` no expone el nonce. +9. **SQLite:** `journal_mode=WAL`, `synchronous=NORMAL`, `busy_timeout=5000`; liquidaciones idempotentes; `chain_txs(tx_hash, lt)` como PK garantiza procesamiento *exactly-once*. +10. **Dependencias:** `npm audit` sin vulnerabilidades; `pip-audit` limpio sobre `requirements.txt`; los *pins* de npm coinciden con las últimas versiones publicadas. +11. **Sin secretos en el código:** ni tokens, ni mnemónicos, ni direcciones de administrador embebidas. Las fixtures de test usan valores evidentemente falsos (`123456789:TEST-TOKEN-…`). +12. **Variables de entorno:** todas las declaradas en `.env.example` se leen en `config.py`; una de ellas (`ESCROW_ADMIN_ADDRESS`) se lee y luego no se usa (ver D-03). *(Una sospecha inicial sobre `FRAME_ANCESTORS` resultó **falsa**: sí se lee en `config.py:254`.)* + +--- + +## 3. Hallazgos críticos y altos + +### S-01 — 🔴 El indexador pierde eventos on-chain de forma permanente si falla una escritura +**Evidencia:** `bot/chain/indexer.py:140-157` +En el `except` se marca la tx como no procesada (`unmark_tx_processed`) con el comentario *«retry this tx next poll»*, pero **acto seguido el cursor se actualiza igual** (`if tx.lt >= newest_lt: newest_lt, newest_hash = tx.lt, tx.tx_hash`) y se persiste con `set_cursor(...)`. El siguiente ciclo solo pide transacciones *más nuevas* que el cursor, por lo que la tx fallida queda fuera de la ventana para siempre. + +**Prueba ejecutada** (3 txs, fallo forzado en la del medio): +``` +run 1 -> fetched 3 processed 2 errores 1 +cursor tras run 1: (30, ...) +run 2 -> fetched 0 processed 0 +¿tx 20 quedó procesada? True ← el cursor ya la dejó atrás +``` +**Impacto:** una apuesta o una resolución on-chain puede quedar invisible para el backend mientras el dinero sí se movió. No hay reconciliación posterior ni alerta. Es el hallazgo de mayor riesgo del proyecto. + +--- + +### S-02 — 🔴 `upsert_market` ignora silenciosamente cualquier corrección posterior de los datos del mercado +**Evidencia:** `bot/database.py:943` (`INSERT OR IGNORE INTO markets ...`), usado desde `bot/chain/indexer.py:286` y `:321`. +La fila se crea la primera vez y **nunca se actualiza**. El caso real está documentado en el propio código (`indexer.py:319-330`): si una apuesta llega antes que el evento de creación, se crea un marcador con `title="Mercado #N"`, `closes_at=0` y sin `fee_bps`; cuando luego se indexa el evento de creación, los datos buenos se descartan. + +**Prueba ejecutada:** +``` +upsert_market existente -> created: False | título final: 'Mercado #1' | closes_at: 0 +``` +**Impacto:** mercado con fecha de cierre de 1970 (aparece siempre como cerrado), título genérico permanente, `option_count` incorrecto y `estimate_payout` calculando con `fee_bps = 0`. + +--- + +### S-03 — 🔴 Funciones de administración del contrato inalcanzables desde cualquier interfaz +**Evidencia:** `bot/chain/bodies.py` define `build_set_paused`, `build_set_fee`, `build_change_admin`, `build_withdraw_fees`; `contracts/escrow.fc` las implementa; **ningún** router, handler, teclado o botón de la Mini App las invoca (búsqueda exhaustiva sobre `bot/`, `main.py`, `web/`). +El indexador sí sabe *leer* esos eventos, lo que confirma que el contrato los emite. + +**Impacto:** el administrador **no puede retirar las comisiones acumuladas, pausar el contrato en una emergencia, cambiar la comisión ni transferir la administración** sin construir el mensaje a mano en una wallet. Las fees quedan atrapadas en el contrato. Es una funcionalidad completa (código + contrato) sin puerta de entrada. + +--- + +### S-04 — 🔴 El limitador de tasa es eludible falsificando `X-Forwarded-For` +**Evidencia:** `bot/api.py:82-84` +```python +def _client_ip(request): + forwarded = request.headers.get("X-Forwarded-For", "") + return (forwarded.split(",")[0].strip() if forwarded else request.remote) or "?" +``` +Se confía en la cabecera sin lista blanca de proxies. Se aplica a `/api/session` (`api.py:243`) y, por clave de usuario, a `/api/wallet/verify`. + +**Prueba ejecutada:** 40 peticiones `POST /api/session` rotando `X-Forwarded-For: 10.0.0.N` → **40 × 200, cero 429**. +**Impacto:** un atacante abre sesiones ilimitadas y evita el freno de verificación de wallet; además el diccionario interno del limitador recibe claves arbitrarias (el recorte de memoria solo elimina cubetas vacías, `bot/security.py`). + +--- + +### S-05 — 🔴 La CSP del propio servidor anula el botón «Reintentar» de la Mini App +**Evidencia:** `web/static/app.js:186` inyecta ` + +
Cargando estado…
+ +
+ + +

+ Solo se pueden retirar las comisiones acumuladas. El contrato nunca + permite sacar los fondos de los usuarios. +

+
+ +
+ + +

Aplica solo a los mercados creados a partir de ahora.

+
+ +
+ + +

+ ⚠️ Irreversible: si pierdes esa wallet, pierdes el control del contrato. +

+
+ + +

+ Pausado: nadie puede crear mercados ni apostar. Resolver, cancelar y + reclamar pagos siguen funcionando. Cada acción se firma en tu wallet: + el backend nunca tiene llaves. +

+ +

Estado del indexador

—
diff --git a/web/static/app.js b/web/static/app.js index c295c42..12a674e 100644 --- a/web/static/app.js +++ b/web/static/app.js @@ -848,6 +848,126 @@ } } + /* --------------------------------------------------- contrato escrow */ + + const contract = { data: null }; + + function renderContract() { + const box = $('#contract-state'); + if (!box || !contract.data) return; + const data = contract.data; + const paused = !!data.is_paused; + const tons = (nano) => `${fmtTon(Number(nano || 0) / 1e9)} TON`; + const rows = [ + ['Estado', paused ? '⏸ pausado' : '▶️ activo'], + ['Comisión actual', `${data.fee_percent || '0.00'} %`], + ['Apuesta mínima', tons(data.min_stake_nano)], + ['Comisiones acumuladas', tons(data.fees_nano)], + ['Fondos de usuarios bloqueados', tons(data.total_locked_nano)], + ['Mercados creados', String(data.market_count == null ? '—' : data.market_count)], + ]; + if (data.balance_nano != null) rows.push(['Balance del contrato', tons(data.balance_nano)]); + if (data.admin) rows.push(['Admin configurado', short(data.admin, 6)]); + const warnings = []; + if (data.stale) warnings.push('⚠️ Estado sin actualizar: la cadena no respondió.'); + if (data.admin_matches_wallet === false) { + warnings.push('⚠️ Tu wallet vinculada no es la administradora: el contrato rechazaría la firma.'); + } + if (data.admin_matches_wallet === null && data.admin) { + warnings.push('ℹ️ Vincula tu wallet en el bot para comprobar quién es el administrador.'); + } + box.innerHTML = ` +
+ ${rows.map(([label, value]) => `
${esc(label)}
${esc(value)}
`).join('')} +
+ ${warnings.map((text) => `

${esc(text)}

`).join('')}`; + + const pause = $('#contract-pause'); + if (pause) pause.textContent = paused ? 'Reanudar contrato' : 'Pausar contrato'; + const amount = $('#contract-withdraw-amount'); + if (amount) { + const availableTon = Number(data.max_withdrawable_nano || data.fees_nano || 0) / 1e9; + amount.max = String(availableTon); + } + } + + async function loadContract(force = false) { + const box = $('#contract-state'); + if (!box) return; + if (!state.config || !state.config.escrow_enabled) { + box.textContent = 'Esta instancia no tiene contrato escrow configurado.'; + return; + } + try { + const data = force + ? await api('/api/admin/contract?refresh=1') + : await api('/api/admin/contract'); + contract.data = data; + renderContract(); + } catch (error) { + contract.data = null; + box.textContent = friendlyError(error); + } + } + + async function signContract(prepare, message) { + busy(true); + try { + const tx = await prepare(); + busy(false); + await signTransaction(tx); + toast(message, 'ok'); + loadContract(true); + } catch (error) { + busy(false); + toast(friendlyError(error), 'error'); + } + } + + async function contractWithdraw(event) { + event.preventDefault(); + const amount = $('#contract-withdraw-amount').value.trim(); + if (!amount) return; + if (!window.confirm(`¿Retirar ${amount} TON de comisiones? La firma la hace tu wallet.`)) return; + await signContract( + () => api('/api/admin/contract/withdraw/prepare', { method: 'POST', body: { amount } }), + 'Retiro enviado. El indexador lo confirmará en unos segundos.'); + } + + async function contractSetFee(event) { + event.preventDefault(); + const percent = $('#contract-fee-percent').value.trim(); + if (!percent) return; + if (!window.confirm(`¿Cambiar la comisión al ${percent} %? Solo afecta a mercados nuevos.`)) return; + await signContract( + () => api('/api/admin/contract/set-fee/prepare', { method: 'POST', body: { percent } }), + 'Comisión enviada. Se aplicará a los mercados creados desde ahora.'); + } + + async function contractSetPaused() { + if (!contract.data) return; + const paused = !contract.data.is_paused; + const question = paused + ? '¿Pausar el contrato? Nadie podrá crear mercados ni apostar.' + : '¿Reanudar el contrato? Se volverán a aceptar mercados y apuestas.'; + if (!window.confirm(question)) return; + await signContract( + () => api('/api/admin/contract/set-paused/prepare', { method: 'POST', body: { paused } }), + paused ? 'Contrato pausado.' : 'Contrato reanudado.'); + } + + async function contractChangeAdmin(event) { + event.preventDefault(); + const address = $('#contract-admin-address').value.trim(); + if (!address) return; + const sure = window.confirm( + `Vas a transferir la administración a:\n${address}\n\nEs irreversible. ¿Continuar?`); + if (!sure) return; + await signContract( + () => api('/api/admin/contract/change-admin/prepare', { method: 'POST', body: { address } }), + 'Cambio de administrador enviado. Verifícalo on-chain antes de cerrar.'); + } + async function loadAdminStatus() { try { const status = await api('/api/indexer'); @@ -868,7 +988,10 @@ const section = document.getElementById(`view-${name}`); if (section) section.classList.toggle('hidden', name !== view); }); - if (view === 'admin') loadAdminStatus(); + if (view === 'admin') { + loadAdminStatus(); + loadContract(); + } if (view === 'mine') loadMine(); if (view === 'markets') loadMarkets(true); } @@ -883,6 +1006,17 @@ $('#wallet-chip').addEventListener('click', connectWallet); $('#reconnect').addEventListener('click', reconnectWallet); $('#refresh-markets').addEventListener('click', () => loadMarkets()); + const contractBindings = [ + ['#contract-refresh', 'click', () => loadContract(true)], + ['#contract-withdraw-form', 'submit', contractWithdraw], + ['#contract-fee-form', 'submit', contractSetFee], + ['#contract-admin-form', 'submit', contractChangeAdmin], + ['#contract-pause', 'click', contractSetPaused], + ]; + contractBindings.forEach(([selector, event, handler]) => { + const el = $(selector); + if (el) el.addEventListener(event, handler); + }); $('#create-form').addEventListener('submit', createMarket); $('#sheet-confirm').addEventListener('click', () => { if (state.sheetMode === 'resolve') confirmResolve(); diff --git a/web/static/styles.css b/web/static/styles.css index 6d8e30f..11746a8 100644 --- a/web/static/styles.css +++ b/web/static/styles.css @@ -351,3 +351,9 @@ textarea { resize: vertical; min-height: 84px; } .sheet { align-items: center; justify-items: center; } .sheet-panel { width: min(94vw, 480px); border-radius: 22px; } } + +/* ------------------------------------------------- contrato escrow (admin) */ +.contract-rows { display: grid; gap: 6px; margin: 10px 0; } +.contract-rows > div { display: flex; justify-content: space-between; gap: 10px; } +.contract-rows dt { color: var(--muted); font-size: 12.5px; margin: 0; } +.contract-rows dd { margin: 0; font-size: 12.5px; font-weight: 650; text-align: right; } From 6183291fd83a9ebf227233a993a607b912935d24 Mon Sep 17 00:00:00 2001 From: Adlgr87 <164441450+Adlgr87@users.noreply.github.com> Date: Fri, 23 Oct 2026 20:05:25 +0000 Subject: [PATCH 06/17] feat(fase 3): endurecimiento de la API (S-04, S-05, D-01, D-02) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - S-04: _client_ip solo honra X-Forwarded-For con TRUST_PROXY y un peer de TRUSTED_PROXIES; se recorre la lista de derecha a izquierda. RateLimiter con evicción LRU real y 429 con Retry-After. - Backstop global por endpoint (independiente de la identidad) más validación de arranque de TRUST_PROXY/TRUSTED_PROXIES. - S-05: fuera el onclick inline del botón «Reintentar»; data-reload con delegación de eventos y test que vigila la CSP publicada. - D-01: _user_payload / _market_id / _require_admin y un mapeo único de MarketError (forbidden→403, chain_unavailable→503); helper único para las dos cancelaciones del bot. - D-02: «Desvincular wallet» y «Cancelar y reembolsar» en la Mini App; el baseline de test_wiring queda solo con /api/health. - Pruebas: 415 (antes 402), cobertura 60 % (umbral en CI), config y activos web con suite propia. Verificado en vivo: 40 POST /api/session rotando XFF → 30×200 y 10×429. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- .env.example | 8 ++ .github/workflows/ci.yml | 2 +- CHANGELOG.md | 62 +++++++++ PLAN_IMPLEMENTACION.md | 2 +- README.md | 23 +++- bot/api.py | 289 ++++++++++++++++++++++++--------------- bot/handlers/admin.py | 56 ++++---- bot/security.py | 32 +++-- config.py | 33 +++++ tests/test_api.py | 166 +++++++++++++++++++++- tests/test_config.py | 110 +++++++++++++++ tests/test_web_assets.py | 77 +++++++++++ tests/test_wiring.py | 5 +- web/static/app.js | 65 ++++++++- web/static/styles.css | 3 + 15 files changed, 767 insertions(+), 166 deletions(-) create mode 100644 tests/test_config.py create mode 100644 tests/test_web_assets.py diff --git a/.env.example b/.env.example index 6fdfcec..955d73d 100644 --- a/.env.example +++ b/.env.example @@ -70,3 +70,11 @@ APP_TITLE=BetPoly SUPPORT_URL= # Orígenes que pueden embeber la Mini App (CSP frame-ancestors) FRAME_ANCESTORS='self' https://*.telegram.org https://web.telegram.org https://*.e2b.app + +# --- Proxy inverso (IP real para los límites de tasa) ------------------------- +# Solo se honra X-Forwarded-For si TRUST_PROXY=true Y la conexión viene de una +# de estas redes. Con TRUST_PROXY=false la cabecera se ignora (recomendado si +# el proceso escucha directo en Internet). +TRUST_PROXY=false +# Lista de CIDR separada por comas, p. ej. 127.0.0.1/32,10.0.0.0/8 +TRUSTED_PROXIES= diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9f7aa8a..5f97c8b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -44,7 +44,7 @@ jobs: pytest \ --cov=bot --cov=config --cov=main --cov=scripts \ --cov-report=term-missing:skip-covered \ - --cov-fail-under=59 + --cov-fail-under=60 contract: name: Contrato (build + sandbox + audit) diff --git a/CHANGELOG.md b/CHANGELOG.md index df4f279..3fa5b5d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -158,3 +158,65 @@ arregló**, **qué se decidió** y **qué quedó pendiente**. El plan completo v - Fase 3 (seguridad y aislamiento de la API) antes de la Fase 4. - El panel del contrato no muestra aún el historial de transacciones de administración; hoy se consulta en el explorador con la dirección del escrow. + +--- + +## Fase 3 — Endurecimiento de la API (S-04, S-05, D-01, D-02) + +**Fecha:** 2026-10-23 + +### Arreglado +- **S-04 · El limitador de tasa se eludía falsificando `X-Forwarded-For`.** + `bot/api.py:_client_ip` ya no confía en la cabecera: solo se honra con + `TRUST_PROXY=true` **y** si la conexión llega desde una red de + `TRUSTED_PROXIES`; entonces se recorre la lista de derecha a izquierda y se + devuelve el primer salto que no sea un proxy de confianza. La prueba de la + auditoría (40 `POST /api/session` rotando la cabecera) ahora termina en `429`. +- **S-04 · El diccionario del limitador crecía sin control.** `RateLimiter` usa + ahora `OrderedDict` con **evicción LRU real** (`max_keys`, 10 000 por defecto) + en lugar de borrar solo las cubetas vacías. Las respuestas `429` incluyen + `Retry-After` en segundos. +- **S-05 · El botón «Reintentar» no hacía nada.** Era un `onclick` inline que la + propia CSP del servidor bloquea. Pasa a `data-reload="1"` con delegación de + eventos (el patrón que ya usa el resto de la UI). +- **D-02 · Dos endpoints sin consumidor.** La Mini App incorpora «Desvincular + wallet» (`DELETE /api/wallet`) y «Cancelar y reembolsar» por mercado + (`POST /api/admin/markets/{id}/cancel/prepare`), ambos con confirmación. El + baseline de `test_wiring` queda solo con `/api/health`, justificado. + +### Añadido +- **Backstop global por endpoint** (300/min en `/api/session` y + `/api/wallet/nonce`, 120/min en `/api/wallet/verify`, `/api/markets/prepare` y + `/api/wallet`): la clave es la ruta, no el cliente, así que rotar IPs o + sesiones no lo esquiva. Los limitadores se crean por aplicación + (`create_app(backstop_limits=…)`) para que una app de prueba no herede + contadores ajenas. +- **Configuración que no puede quedar muda:** `TRUST_PROXY` y `TRUSTED_PROXIES` + se validan al arrancar; confiar sin lista (o declarar lista sin confiar) + lanza `ConfigError` en vez de no hacer nada, que es la lección de D-03. +- **D-01 · Menos duplicación en la API:** `_user_payload`, `_market_id` y + `_require_admin` sustituyen los clones de `/api/session` ↔ `/api/me` y de los + cuatro handlers con `market_id`/chequeo de admin; el mapeo de errores de + dominio (`forbidden`→403, `chain_unavailable`→503) vive en un único sitio + (`_MARKET_ERROR_STATUS`), lo que además elimina `_escrow_admin_error`. En los + handlers del bot, `_show_cancel_prepared` unifica las dos cancelaciones. +- Pruebas nuevas: `tests/test_config.py` (proxies y validaciones de arranque) y + `tests/test_web_assets.py` (cero manejadores inline + la CSP que se publica de + verdad), más los casos de IP real, backstop, `Retry-After`, desvincular wallet + y cancelar desde la Mini App. + +### Decidido +- **La cabecera no se honra por defecto.** Un despliegue directo a Internet no + necesita saber nada de proxies; detrás de uno, se declara explícitamente. El + valor por defecto seguro evita el fallo silencioso. +- **No borrar endpoints, cablearlos.** `DELETE /api/wallet` y el `cancel/prepare` + de admin se exponen en la Mini App; `/api/health` se documenta como endpoint de + sondas y queda como único huérfano justificado. +- **Un techo por endpoint, no por IP.** El backstop es una segunda barrera + independiente de la identidad; no sustituye al límite por usuario, que sigue + dando mensajes más precisos en el uso normal. + +### Pendiente +- Fase 4: economía única y coherencia de lo mostrado (F-03, H-*, U-05). +- El backstop es en memoria y por proceso: con varias réplicas cada una lleva su + propia cuenta (aceptable en el host único de 512 MB; ver ADR-05). diff --git a/PLAN_IMPLEMENTACION.md b/PLAN_IMPLEMENTACION.md index ed8dc5c..2a8e863 100644 --- a/PLAN_IMPLEMENTACION.md +++ b/PLAN_IMPLEMENTACION.md @@ -124,7 +124,7 @@ Cada decisión incluye la alternativa descartada y **por qué es subóptima para | ✅ | **0** | Red de seguridad (CI, baseline) | F-10, F-11, T-01 (base), T-04, R-10 | 1 | — | | ✅ | **1** | Integridad del dinero on-chain | **S-01, S-02, S-07**, F-05, F-06 | 4 | 0 | | ✅ | **2** | Administración del contrato | **S-03**, D-03 | 3-4 | 0, 1 | -| ⬜ | **3** | Endurecimiento de la API | **S-04, S-05**, D-01 (api), D-02 | 2 | 0 | +| ✅ | **3** | Endurecimiento de la API | **S-04, S-05**, D-01 (api), D-02 | 2 | 0 | | ⬜ | **4** | Economía única y coherencia mostrada | F-03, H-*, U-05 | 2-3 | 1 | | ⬜ | **5** | Capa Telegram: navegación, entrada, notificaciones | F-01, F-14, F-02, F-04, **S-06**, U-01…U-04, U-06 | 4 | 1, 4 | | ⬜ | **6** | Rendimiento y activos | R-01…R-09 | 2-3 | 1, 5 | diff --git a/README.md b/README.md index 9f6a465..f456cf9 100644 --- a/README.md +++ b/README.md @@ -142,6 +142,9 @@ TON_PROOF_DOMAIN=tu-dominio SECRET_KEY=<32+ bytes aleatorios> TON_NETWORK=mainnet TON_API_KEY=… +# Solo tras un proxy inverso: sin TRUST_PROXY la cabecera X-Forwarded-For se ignora +TRUST_PROXY=false +TRUSTED_PROXIES=127.0.0.1/32 ``` `PUBLIC_BASE_URL` debe servirse por HTTPS y alojar `/tonconnect-manifest.json` y `/static/icon.png`: TON Connect los descarga y verifica el origen. @@ -187,7 +190,18 @@ Las sesiones viajan en la cabecera `X-Session`. El backend **nunca** devuelve un * **Autenticación**: `hash = HMAC_SHA256(bot_token, "WebAppData")` sobre el `init_data`; se valida `auth_date` y se exige `ALLOW_DEV_SESSION=false` en producción. * **Sesiones**: token `user_id.expira.hmac(secret_key)`; sin `secret_key` persistente las sesiones mueren al reiniciar (solo válido en desarrollo). * **ton_proof**: digest `sha256("ton-proof-item-v2/" ‖ wc ‖ address_hash ‖ domain_len ‖ domain ‖ timestamp ‖ payload)`, firmado en Ed25519 con la clave del `StateInit` (que debe hashear a la dirección declarada). Dominio exacto, ventana de 600 s, nonce de un solo uso por `(user_id, purpose)`. -* **Rate limiting** por IP/usuario en sesión, preparación de transacciones y verificación de wallets. +* **IP real**: `X-Forwarded-For` es una cabecera que el cliente controla, así que + se ignora salvo que `TRUST_PROXY=true` **y** la conexión llegue desde una red de + `TRUSTED_PROXIES`. En ese caso se recorre la lista de derecha a izquierda y se + toma el primer salto que no sea un proxy de confianza. Una configuración + incoherente (confiar sin lista, o lista sin confiar) **falla al arrancar**. +* **Rate limiting** por IP/usuario en sesión, preparación de transacciones y + verificación de wallets, más un **backstop global por endpoint** + (`/api/session`, `/api/wallet/*`, `/api/markets/prepare`) que no depende de la + identidad: rotar IPs o sesiones no lo esquiva. Las respuestas `429` incluyen + `Retry-After`, y el limitador desaloja por LRU real (memoria acotada). +* **CSP estricta** sin `'unsafe-inline'` para scripts: la Mini App no usa + manejadores inline y un test lo verifica. * **CSP** con `frame-ancestors` configurable (`FRAME_ANCESTORS`) para permitir Telegram y bloquear el resto. * **Índice idempotente**: cada transacción se procesa una vez (`chain_txs`), el cursor solo avanza tras confirmar, y un fallo de red nunca bloquea al bot. @@ -258,12 +272,15 @@ La suite de Python no necesita red, Telegram ni TON API: usa SQLite en `tmp_path cobertura, compilación del contrato con verificación del hash reproducible, sandbox TVM, `npm audit` y `pip-audit`. -Dos suites son *guardarraíles* y no pruebas funcionales: +Tres suites son *guardarraíles* y no pruebas funcionales: - `tests/test_architecture.py` — dirección de las dependencias entre capas. - `tests/test_wiring.py` — conectividad: rutas sin consumidor, botones sin handler, builders on-chain inalcanzables y comandos prometidos en `/help`. - Los huérfanos conocidos viven en un baseline que solo puede encogerse. + Los huérfanos conocidos viven en un baseline que solo puede encogerse (hoy + solo queda `/api/health`, endpoint de sondas). +- `tests/test_web_assets.py` — la Mini App no lleva manejadores inline y la CSP + que se publica de verdad los bloquearía. ### Administración del contrato (Fase 2) diff --git a/bot/api.py b/bot/api.py index f74d31d..b99d884 100644 --- a/bot/api.py +++ b/bot/api.py @@ -12,10 +12,13 @@ """ from __future__ import annotations +import ipaddress import logging +import math import time +from functools import lru_cache from pathlib import Path -from typing import Any, Dict, Optional +from typing import Any, Dict, Optional, Tuple from aiohttp import web @@ -38,6 +41,33 @@ _session_limiter = security.RateLimiter(limit=30, window_seconds=60) _verify_limiter = security.RateLimiter(limit=10, window_seconds=300) +#: Global backstop per endpoint (limit, window seconds). These are *not* keyed by +#: client: even a client that rotates IPs or sessions hits this ceiling, which is +#: what makes S-04 impossible to exploit by forging headers (see Fase 3). +BACKSTOP_LIMITS: Dict[str, Tuple[int, float]] = { + "/api/session": (300, 60), + "/api/wallet/nonce": (300, 60), + "/api/wallet/verify": (120, 60), + "/api/markets/prepare": (120, 60), + "/api/wallet": (120, 60), +} + +def _new_backstops( + limits: Optional[Dict[str, Tuple[int, float]]] = None, +) -> Dict[str, security.RateLimiter]: + """Fresh limiters per app: a test app must not inherit another's counters.""" + return { + path: security.RateLimiter(limit=limit, window_seconds=window) + for path, (limit, window) in (limits or BACKSTOP_LIMITS).items() + } + +#: Market error codes that are not a plain 400. +_MARKET_ERROR_STATUS = { + "forbidden": 403, + "wallet_not_admin": 403, + "chain_unavailable": 503, +} + def _settings() -> config.Settings: return config.get_settings() @@ -79,9 +109,47 @@ async def read_json(request: web.Request) -> Dict[str, Any]: return data +@lru_cache(maxsize=32) +def _networks(cidrs: Tuple[str, ...]) -> Tuple[Any, ...]: + """Parsed networks, cached: ``_client_ip`` runs on every request.""" + return tuple(ipaddress.ip_network(cidr, strict=False) for cidr in cidrs) + + +def _is_trusted_proxy(ip: str, cidrs: Tuple[str, ...]) -> bool: + if not cidrs: + return False + try: + address = ipaddress.ip_address(str(ip).strip().strip("[]")) + except ValueError: + return False + return any(address in network for network in _networks(cidrs)) + + def _client_ip(request: web.Request) -> str: - forwarded = request.headers.get("X-Forwarded-For", "") - return (forwarded.split(",")[0].strip() if forwarded else request.remote) or "?" + """Peer address used for rate limiting, honouring proxies only when declared. + + ``X-Forwarded-For`` is client controlled, so it is ignored unless + ``TRUST_PROXY`` is on *and* the direct peer is one of ``TRUSTED_PROXIES``. + The header list is then walked right to left, returning the first hop that + is not itself a trusted proxy (the real client as seen by our edge). + """ + remote = request.remote or "?" + settings = _settings() + if not settings.trust_proxy or not _is_trusted_proxy(remote, settings.trusted_proxies): + return remote + raw = ",".join(request.headers.getall("X-Forwarded-For", [])) + hops = [hop.strip() for hop in raw.split(",") if hop.strip()] + for hop in reversed(hops): + if not _is_trusted_proxy(hop, settings.trusted_proxies): + return hop + return hops[0] if hops else remote + + +def _rate_limited(message: str, retry_after: float = 0.0) -> web.Response: + """429 + ``Retry-After`` (seconds) so clients can back off correctly.""" + response = json_error("rate_limited", message, 429) + response.headers["Retry-After"] = str(max(1, math.ceil(retry_after))) + return response def current_user(request: web.Request) -> int: @@ -96,6 +164,33 @@ def _admin(user_id: int) -> bool: return user_id in _settings().admin_ids +def _user_payload(user_id: int, user: Optional[Dict[str, Any]]) -> Dict[str, Any]: + """Public shape of a user, shared by ``/api/session`` and ``/api/me``.""" + return { + "user_id": user_id, + "username": (user or {}).get("username"), + "full_name": (user or {}).get("full_name"), + "points": (user or {}).get("points", 0), + "is_admin": _admin(user_id), + } + + +def _market_id(request: web.Request) -> Optional[int]: + """``market_id`` from the URL, or ``None`` when it is not an integer.""" + try: + return int(request.match_info["market_id"]) + except (KeyError, ValueError): + return None + + +def _require_admin(request: web.Request) -> int: + """Return the caller's id, raising a domain ``forbidden`` when not admin.""" + user_id = current_user(request) + if not _admin(user_id): + raise markets.MarketError("forbidden", "Solo administradores.") + return user_id + + def _wallet_view(wallet: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: if not wallet: return None @@ -226,7 +321,7 @@ async def index(request: web.Request) -> web.StreamResponse: async def create_session(request: web.Request) -> web.Response: allowed, retry = _session_limiter.allow(_client_ip(request)) if not allowed: - return json_error("rate_limited", "Demasiados intentos. Espera un momento.", 429) + return _rate_limited("Demasiados intentos. Espera un momento.", retry) data = await read_json(request) init_data = data.get("init_data") or "" @@ -263,13 +358,7 @@ async def create_session(request: web.Request) -> web.Response: "nonce": nonce, "dev_mode": dev, "user_id": user_id, - "user": { - "user_id": user_id, - "username": (user or {}).get("username"), - "full_name": (user or {}).get("full_name"), - "points": (user or {}).get("points", 0), - "is_admin": _admin(user_id), - }, + "user": _user_payload(user_id, user), "wallet": _wallet_view(wallet), "config": public_config(), } @@ -287,9 +376,9 @@ async def wallet_nonce(request: web.Request) -> web.Response: async def verify_wallet(request: web.Request) -> web.Response: user_id = current_user(request) - allowed, _ = _verify_limiter.allow(str(user_id)) + allowed, retry = _verify_limiter.allow(str(user_id)) if not allowed: - return json_error("rate_limited", "Demasiados intentos de verificación.", 429) + return _rate_limited("Demasiados intentos de verificación.", retry) data = await read_json(request) address = data.get("address") or "" @@ -378,13 +467,7 @@ async def me(request: web.Request) -> web.Response: bets = await database.list_onchain_bets(wallet["address"], limit=25) return json_ok( { - "user": { - "user_id": user_id, - "username": (user or {}).get("username"), - "full_name": (user or {}).get("full_name"), - "points": (user or {}).get("points", 0), - "is_admin": _admin(user_id), - }, + "user": _user_payload(user_id, user), "wallet": _wallet_view(wallet), "bets": [ { @@ -428,9 +511,8 @@ async def list_markets(request: web.Request) -> web.Response: async def get_market(request: web.Request) -> web.Response: - try: - market_id = int(request.match_info["market_id"]) - except (KeyError, ValueError): + market_id = _market_id(request) + if market_id is None: return json_error("bad_market", "market_id inválido.") user_id = None try: @@ -448,7 +530,7 @@ async def prepare_market(request: web.Request) -> web.Response: user_id = current_user(request) allowed, retry = _prepare_limiter.allow(f"create:{user_id}") if not allowed: - return json_error("rate_limited", "Espera un momento antes de crear otro mercado.", 429) + return _rate_limited("Espera un momento antes de crear otro mercado.", retry) data = await read_json(request) options = data.get("options") or [] @@ -470,13 +552,12 @@ async def prepare_market(request: web.Request) -> web.Response: async def prepare_bet(request: web.Request) -> web.Response: user_id = current_user(request) - allowed, _ = _prepare_limiter.allow(f"bet:{user_id}") + allowed, retry = _prepare_limiter.allow(f"bet:{user_id}") if not allowed: - return json_error("rate_limited", "Espera un momento antes de apostar de nuevo.", 429) + return _rate_limited("Espera un momento antes de apostar de nuevo.", retry) - try: - market_id = int(request.match_info["market_id"]) - except (KeyError, ValueError): + market_id = _market_id(request) + if market_id is None: return json_error("bad_market", "market_id inválido.") data = await read_json(request) try: @@ -499,9 +580,8 @@ async def prepare_bet(request: web.Request) -> web.Response: async def prepare_claim(request: web.Request) -> web.Response: user_id = current_user(request) - try: - market_id = int(request.match_info["market_id"]) - except (KeyError, ValueError): + market_id = _market_id(request) + if market_id is None: return json_error("bad_market", "market_id inválido.") try: tx = await markets.prepare_claim(user_id, market_id) @@ -511,12 +591,9 @@ async def prepare_claim(request: web.Request) -> web.Response: async def prepare_resolve(request: web.Request) -> web.Response: - user_id = current_user(request) - if not _admin(user_id): - return json_error("forbidden", "Solo administradores.", 403) - try: - market_id = int(request.match_info["market_id"]) - except (KeyError, ValueError): + user_id = _require_admin(request) + market_id = _market_id(request) + if market_id is None: return json_error("bad_market", "market_id inválido.") data = await read_json(request) try: @@ -531,12 +608,9 @@ async def prepare_resolve(request: web.Request) -> web.Response: async def prepare_cancel(request: web.Request) -> web.Response: - user_id = current_user(request) - if not _admin(user_id): - return json_error("forbidden", "Solo administradores.", 403) - try: - market_id = int(request.match_info["market_id"]) - except (KeyError, ValueError): + user_id = _require_admin(request) + market_id = _market_id(request) + if market_id is None: return json_error("bad_market", "market_id inválido.") try: tx = await markets.prepare_cancel(user_id, market_id) @@ -549,39 +623,11 @@ async def prepare_cancel(request: web.Request) -> web.Response: # escrow administration (payload builders only: the wallet signs) # --------------------------------------------------------------------------- -#: Errores del dominio que significan "no eres el administrador". -_ADMIN_FORBIDDEN = ("forbidden", "wallet_not_admin") -#: Errores de infraestructura (la cadena o el RPC no respondieron). -_UNAVAILABLE = ("chain_unavailable",) - - -def _escrow_admin_error(exc: Exception) -> web.Response: - """Map domain errors to HTTP without leaking chain details.""" - if isinstance(exc, markets.MarketError): - if exc.code in _ADMIN_FORBIDDEN: - status = 403 - elif exc.code in _UNAVAILABLE: - status = 503 - else: - status = 400 - return json_error(exc.code, str(exc), status) - raise exc - - -def _require_web_admin(request: web.Request) -> int: - user_id = current_user(request) - if not _admin(user_id): - raise markets.MarketError("forbidden", "Solo un administrador puede operar el contrato.") - return user_id - - async def admin_contract_state(request: web.Request) -> web.Response: - try: - user_id = _require_web_admin(request) - force = request.query.get("refresh") in ("1", "true", "yes") - state = await markets.escrow_state(force=force) - except Exception as exc: # noqa: BLE001 - mapped below - return _escrow_admin_error(exc) + user_id = _require_admin(request) + force = request.query.get("refresh") in ("1", "true", "yes") + # Los MarketError (chain_unavailable incluido) los traduce el middleware. + state = await markets.escrow_state(force=force) payload = state.as_dict() payload["admin_matches_wallet"] = await _admin_matches_wallet(user_id, state) return json_ok(payload) @@ -601,51 +647,40 @@ async def _admin_matches_wallet(user_id: int, state: Any) -> Optional[bool]: async def admin_contract_withdraw(request: web.Request) -> web.Response: - try: - user_id = _require_web_admin(request) - data = await read_json(request) - amount = parse_nano(data.get("amount"), field="importe") - tx = await markets.prepare_withdraw_fees(user_id, amount) - except Exception as exc: # noqa: BLE001 - mapped below - return _escrow_admin_error(exc) + user_id = _require_admin(request) + data = await read_json(request) + amount = parse_nano(data.get("amount"), field="importe") + tx = await markets.prepare_withdraw_fees(user_id, amount) return json_ok(tx.as_dict()) async def admin_contract_set_fee(request: web.Request) -> web.Response: - try: - user_id = _require_web_admin(request) - data = await read_json(request) - if data.get("fee_bps") is not None: + user_id = _require_admin(request) + data = await read_json(request) + if data.get("fee_bps") is not None: + try: fee_bps = int(data["fee_bps"]) - else: - fee_bps = parse_fee_bps(data.get("percent")) - tx = await markets.prepare_set_fee(user_id, fee_bps) - except (TypeError, ValueError): - return json_error("bad_fee", "fee_bps debe ser un entero.", 400) - except Exception as exc: # noqa: BLE001 - mapped below - return _escrow_admin_error(exc) + except (TypeError, ValueError): + return json_error("bad_fee", "fee_bps debe ser un entero.") + else: + fee_bps = parse_fee_bps(data.get("percent")) + tx = await markets.prepare_set_fee(user_id, fee_bps) return json_ok(tx.as_dict()) async def admin_contract_set_paused(request: web.Request) -> web.Response: - try: - user_id = _require_web_admin(request) - data = await read_json(request) - if not isinstance(data.get("paused"), bool): - return json_error("bad_flag", "paused debe ser true o false.", 400) - tx = await markets.prepare_set_paused(user_id, data["paused"]) - except Exception as exc: # noqa: BLE001 - mapped below - return _escrow_admin_error(exc) + user_id = _require_admin(request) + data = await read_json(request) + if not isinstance(data.get("paused"), bool): + return json_error("bad_flag", "paused debe ser true o false.") + tx = await markets.prepare_set_paused(user_id, data["paused"]) return json_ok(tx.as_dict()) async def admin_contract_change_admin(request: web.Request) -> web.Response: - try: - user_id = _require_web_admin(request) - data = await read_json(request) - tx = await markets.prepare_change_admin(user_id, str(data.get("address") or "")) - except Exception as exc: # noqa: BLE001 - mapped below - return _escrow_admin_error(exc) + user_id = _require_admin(request) + data = await read_json(request) + tx = await markets.prepare_change_admin(user_id, str(data.get("address") or "")) return json_ok(tx.as_dict()) @@ -690,7 +725,9 @@ async def middleware(request: web.Request, handler): ) raise except markets.MarketError as exc: - return json_error(exc.code, str(exc), 400) + return json_error( + exc.code, str(exc), _MARKET_ERROR_STATUS.get(exc.code, 400) + ) except (BodyError, AddressError) as exc: return json_error("bad_request", str(exc), 400) except Exception: # noqa: BLE001 - last resort, no stack traces leaked @@ -700,6 +737,28 @@ async def middleware(request: web.Request, handler): return middleware +def _backstop_middleware(backstops: Dict[str, security.RateLimiter]): + """Ceiling per endpoint, independent of the caller's identity. + + Forging ``X-Forwarded-For`` or minting sessions cannot bypass this: the key + is the endpoint itself, so the "rotate keys until it works" attack (S-04) + hits a wall even if no proxy is configured. + """ + @web.middleware + async def middleware(request: web.Request, handler): + limiter = backstops.get(request.path) + if limiter is not None: + allowed, retry = limiter.allow(request.path) + if not allowed: + return _rate_limited( + "El servicio recibe demasiadas peticiones. Inténtalo en unos segundos.", + retry, + ) + return await handler(request) + + return middleware + + def _headers_middleware(allowed_ancestors: str): @web.middleware async def middleware(request: web.Request, handler): @@ -723,11 +782,19 @@ async def middleware(request: web.Request, handler): return middleware -def create_app(ton_client: Any = None) -> web.Application: +def create_app( + ton_client: Any = None, + *, + backstop_limits: Optional[Dict[str, Tuple[int, float]]] = None, +) -> web.Application: settings = _settings() app = web.Application( client_max_size=MAX_BODY, - middlewares=[_error_middleware(), _headers_middleware(settings.frame_ancestors)], + middlewares=[ + _error_middleware(), + _backstop_middleware(_new_backstops(backstop_limits)), + _headers_middleware(settings.frame_ancestors), + ], ) app[TON_CLIENT_KEY] = ton_client diff --git a/bot/handlers/admin.py b/bot/handlers/admin.py index 86470a4..a9caa6c 100644 --- a/bot/handlers/admin.py +++ b/bot/handlers/admin.py @@ -440,6 +440,30 @@ async def admin_chain_win_callback(update: Update, context: ContextTypes.DEFAULT ) +async def _show_cancel_prepared( + update: Update, market_id: int, tx: markets.PreparedTx, *, emergency: bool = False +) -> None: + """One renderer for both cancellation paths (normal and emergency).""" + title = "Cancelación de emergencia preparada" if emergency else "Cancelación preparada" + await edit_or_reply( + update, + f"🧾 {title} (sin firmar)\n\n" + f"Mercado: #{market_id} {esc(tx.details.get('market_title', ''))}\n\n" + "Al firmarla, todas las wallets podrán reclamar su reembolso completo.\n\n" + f"{code(tx.deeplink)}", + reply_markup=InlineKeyboardMarkup( + [ + [InlineKeyboardButton("🔐 Firmar en la wallet", url=tx.deeplink)], + [ + InlineKeyboardButton( + "🔙 Volver", callback_data=f"admin_chain_market:{market_id}" + ) + ], + ] + ), + ) + + async def admin_chain_cancel_callback(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: query = update.callback_query await safe_answer(query) @@ -482,19 +506,7 @@ async def admin_chain_cancel_callback(update: Update, context: ContextTypes.DEFA await edit_or_reply(update, f"❌ {esc(exc)}") return - await edit_or_reply( - update, - "🧾 Cancelación preparada (sin firmar)\n\n" - f"Mercado: #{market_id} {esc(tx.details.get('market_title', ''))}\n\n" - "Al firmarla, todas las wallets podrán reclamar su reembolso completo.\n\n" - f"{code(tx.deeplink)}", - reply_markup=InlineKeyboardMarkup( - [ - [InlineKeyboardButton("🔐 Firmar en la wallet", url=tx.deeplink)], - [InlineKeyboardButton("🔙 Volver", callback_data=f"admin_chain_market:{market_id}")], - ] - ), - ) + await _show_cancel_prepared(update, market_id, tx) async def admin_chain_cancel_force_callback( @@ -515,23 +527,7 @@ async def admin_chain_cancel_force_callback( await edit_or_reply(update, f"❌ {esc(exc)}") return - await edit_or_reply( - update, - "🧾 Cancelación de emergencia preparada (sin firmar)\n\n" - f"Mercado: #{market_id} {esc(tx.details.get('market_title', ''))}\n\n" - "Al firmarla, todas las wallets podrán reclamar su reembolso completo.\n\n" - f"{code(tx.deeplink)}", - reply_markup=InlineKeyboardMarkup( - [ - [InlineKeyboardButton("🔐 Firmar en la wallet", url=tx.deeplink)], - [ - InlineKeyboardButton( - "🔙 Volver", callback_data=f"admin_chain_market:{market_id}" - ) - ], - ] - ), - ) + await _show_cancel_prepared(update, market_id, tx, emergency=True) # =========================================================================== diff --git a/bot/security.py b/bot/security.py index 3dc3144..65ff473 100644 --- a/bot/security.py +++ b/bot/security.py @@ -19,9 +19,9 @@ import hmac import json import time -from collections import deque +from collections import OrderedDict, deque from dataclasses import dataclass -from typing import Deque, Dict, Optional, Tuple +from typing import Deque, Optional, Tuple from urllib.parse import parse_qsl import config @@ -171,27 +171,41 @@ def dev_session(init_data: Optional[str]) -> Optional[str]: # --------------------------------------------------------------------------- class RateLimiter: - """Sliding window limiter (per key) for API and chat actions.""" + """Sliding window limiter (per key) for API and chat actions. - def __init__(self, limit: int, window_seconds: float) -> None: + Memory is bounded by real LRU eviction (``max_keys``): the least recently + used key is dropped, not just the buckets that happen to be empty. Without + that, a client rotating keys could grow the dict without limit while every + bucket stays "full" and therefore never empty — the old bug behind S-04. + """ + + def __init__(self, limit: int, window_seconds: float, *, max_keys: int = 10_000) -> None: self.limit = max(1, int(limit)) self.window = float(window_seconds) - self._hits: Dict[str, Deque[float]] = {} + self.max_keys = max(1, int(max_keys)) + self._hits: OrderedDict[str, Deque[float]] = OrderedDict() def allow(self, key: str, *, now: Optional[float] = None) -> Tuple[bool, float]: current = float(now if now is not None else time.time()) - bucket = self._hits.setdefault(key, deque()) + bucket = self._hits.get(key) + if bucket is None: + bucket = deque() + self._hits[key] = bucket + else: + self._hits.move_to_end(key) while bucket and current - bucket[0] > self.window: bucket.popleft() if len(bucket) >= self.limit: retry_after = max(0.0, self.window - (current - bucket[0])) return False, retry_after bucket.append(current) - if len(self._hits) > 10_000: # bound memory on long running bots - for stale in [k for k, v in self._hits.items() if not v]: - self._hits.pop(stale, None) + while len(self._hits) > self.max_keys: # LRU real, no solo cubetas vacías + self._hits.popitem(last=False) return True, 0.0 + def __len__(self) -> int: + return len(self._hits) + def reset(self, key: Optional[str] = None) -> None: if key is None: self._hits.clear() diff --git a/config.py b/config.py index a2a4610..ed9e490 100644 --- a/config.py +++ b/config.py @@ -15,6 +15,7 @@ """ from __future__ import annotations +import ipaddress import os import secrets as _secrets from dataclasses import dataclass, field @@ -69,6 +70,23 @@ def _bool(key: str, default: bool = False) -> bool: return raw in ("1", "true", "yes", "y", "on", "si", "sí") +def _cidrs(key: str) -> Tuple[str, ...]: + """Parse a comma separated list of CIDRs, rejecting anything malformed.""" + raw = (os.getenv(key) or "").strip() + if not raw: + return () + out = [] + for chunk in raw.replace(";", ",").split(","): + chunk = chunk.strip() + if not chunk: + continue + try: + out.append(str(ipaddress.ip_network(chunk, strict=False))) + except ValueError as exc: + raise ConfigError(f"{key} contains an invalid CIDR: {chunk!r}") from exc + return tuple(out) + + def _ids(key: str) -> Tuple[int, ...]: raw = (os.getenv(key) or "").strip() if not raw: @@ -138,6 +156,9 @@ class Settings: app_title: str support_url: Optional[str] = field(default=None) frame_ancestors: str = "'self'" + #: Only honour ``X-Forwarded-For`` when the peer is one of these proxies. + trust_proxy: bool = False + trusted_proxies: Tuple[str, ...] = () # -- derived helpers --------------------------------------------------- @property @@ -198,6 +219,16 @@ def validate(self) -> None: ) if self.is_production and self.secret_key.startswith("dev-"): raise ConfigError("SECRET_KEY must be set to a strong random value in production.") + if self.trust_proxy and not self.trusted_proxies: + raise ConfigError( + "TRUST_PROXY=true requires TRUSTED_PROXIES (e.g. 127.0.0.1/32): " + "without a proxy list X-Forwarded-For would be trusted from anyone." + ) + if self.trusted_proxies and not self.trust_proxy: + raise ConfigError( + "TRUSTED_PROXIES is set but TRUST_PROXY is false: the list would have " + "no effect. Set TRUST_PROXY=true or remove TRUSTED_PROXIES." + ) try: ZoneInfo(self.timezone) except ZoneInfoNotFoundError as exc: @@ -254,6 +285,8 @@ def _build_settings() -> Settings: "FRAME_ANCESTORS", "'self' https://*.telegram.org https://web.telegram.org https://*.e2b.app", ), + trust_proxy=_bool("TRUST_PROXY", False), + trusted_proxies=_cidrs("TRUSTED_PROXIES"), ) return settings diff --git a/tests/test_api.py b/tests/test_api.py index 8ec39c1..9045d49 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -4,10 +4,12 @@ import time import pytest_asyncio +from aiohttp import web from aiohttp.test_utils import TestClient, TestServer from test_security import signed_init_data from test_ton_proof import make_proof, make_wallet +import config from bot import api from bot.chain import bodies @@ -102,7 +104,6 @@ async def test_static_assets_are_served(self, client): assert content_type in response.headers["Content-Type"], path async def test_manifest_icon_exists(self, client): - import config icon = api.WEB_DIR / "static" / "icon.png" assert icon.is_file(), "el manifiesto apunta a /static/icon.png" @@ -137,7 +138,6 @@ async def test_session_without_init_data_is_rejected_when_dev_off( self, client, monkeypatch ): monkeypatch.setenv("ALLOW_DEV_SESSION", "0") - import config config.reset_settings() response = await client.post("/api/session", json={}) @@ -230,11 +230,18 @@ async def test_unlink(self, client): assert data["wallet"] is None +async def ready_market(db, market_id=1, closes_in=3600): + """Market mirrored from the chain, ready to be listed (or resolved).""" + await db.enrich_market_from_event( + market_id, "0:" + "11" * 32, "¿Gana México?", 2, + int(time.time()) + closes_in, fee_bps=200, + ) + await db.set_market_options(market_id, ["Sí", "No"]) + + class TestMarketsApi: async def _ready_market(self, db, market_id=1, closes_in=3600): - await db.enrich_market_from_event(market_id, "0:" + "11" * 32, "¿Gana México?", 2, - int(time.time()) + closes_in, fee_bps=200) - await db.set_market_options(market_id, ["Sí", "No"]) + await ready_market(db, market_id, closes_in) async def test_list_and_detail(self, client, db): await self._ready_market(db) @@ -561,6 +568,134 @@ async def _async(value): return value +class TestClientIpAndBackstop: + """Fase 3.1 — S-04: la cabecera X-Forwarded-For no puede eludir los límites.""" + + @staticmethod + def _ip_app(): + app = api.create_app() + + async def current_ip(request): + return web.json_response({"ip": api._client_ip(request)}) + + app.router.add_get("/api/_ip", current_ip) + return app + + async def test_rotating_xff_does_not_bypass_the_session_limiter(self, client): + """40 intentos con IP falsa rotada: la cubeta real es la del peer.""" + assert config.get_settings().trust_proxy is False + api._session_limiter.reset() + statuses = [] + for n in range(40): + response = await client.post( + "/api/session", json={}, headers={"X-Forwarded-For": f"10.0.0.{n}"} + ) + statuses.append(response.status) + assert 429 in statuses, "rotar X-Forwarded-For no debe abrir sesiones infinitas" + assert statuses[0] != 429 + + async def test_429_carries_retry_after(self, client): + api._verify_limiter.reset() + payload, headers = await session_for(client, USER) + statuses = [] + for _ in range(12): + response = await client.post("/api/wallet/verify", headers=headers, json={}) + statuses.append(response.status) + limited = [s for s in statuses if s == 429] + assert limited, statuses + response = await client.post("/api/wallet/verify", headers=headers, json={}) + if response.status == 429: + assert int(response.headers["Retry-After"]) >= 1 + + async def test_forwarded_header_is_ignored_when_the_peer_is_not_a_proxy(self, db, monkeypatch): + monkeypatch.setenv("TRUST_PROXY", "true") + monkeypatch.setenv("TRUSTED_PROXIES", "10.0.0.0/8") + config.reset_settings() + async with TestClient(TestServer(self._ip_app())) as local: + response = await local.get("/api/_ip", headers={"X-Forwarded-For": "203.0.113.9"}) + assert (await response.json())["ip"] == "127.0.0.1" + + async def test_trusted_proxy_resolves_the_original_client(self, db, monkeypatch): + monkeypatch.setenv("TRUST_PROXY", "true") + monkeypatch.setenv("TRUSTED_PROXIES", "127.0.0.1/32") + config.reset_settings() + async with TestClient(TestServer(self._ip_app())) as local: + response = await local.get( + "/api/_ip", headers={"X-Forwarded-For": "203.0.113.9, 127.0.0.1"} + ) + assert (await response.json())["ip"] == "203.0.113.9" + # Cadena de proxies de confianza: el primer hop público manda. + response = await local.get( + "/api/_ip", headers={"X-Forwarded-For": "198.51.100.4, 127.0.0.1"} + ) + assert (await response.json())["ip"] == "198.51.100.4" + + async def test_backstop_is_per_endpoint_and_identity_independent(self, db): + """Aunque se roten IPs y sesiones, el endpoint tiene un techo global.""" + app = api.create_app(backstop_limits={"/api/session": (3, 60)}) + async with TestClient(TestServer(app)) as local: + statuses = [ + (await local.post( + "/api/session", json={}, headers={"X-Forwarded-For": f"10.1.0.{n}"} + )).status + for n in range(4) + ] + assert statuses[:3] != [429, 429, 429] + assert statuses[3] == 429 + + async def test_backstop_does_not_apply_to_other_endpoints(self, db): + app = api.create_app(backstop_limits={"/api/session": (1, 60)}) + async with TestClient(TestServer(app)) as local: + for _ in range(3): + response = await local.get("/api/health") + assert response.status == 200 + + +class TestUnlinkAndCancelFromTheMiniApp: + """Fase 3.4 — D-02: lo que la Mini App promete, la Mini App lo usa.""" + + async def test_unlink_wallet_round_trip(self, client, db): + payload, headers = await session_for(client, USER, wallet=True) + assert payload["wallet"]["address"] + + response = await client.delete("/api/wallet", headers=headers) + assert response.status == 200, await response.text() + assert (await response.json())["data"]["wallet"] is None + + me = (await (await client.get("/api/me", headers=headers)).json())["data"] + assert me["wallet"] is None + assert me["user"]["is_admin"] is False + + async def test_unlink_requires_a_session(self, client): + assert (await client.delete("/api/wallet")).status == 401 + + async def test_admin_cannot_unlink_someone_else(self, client, db): + _, user_headers = await session_for(client, USER, wallet=True) + _, admin_headers = await session_for(client, ADMIN) + await client.delete("/api/wallet", headers=admin_headers) + me = (await (await client.get("/api/me", headers=user_headers)).json())["data"] + assert me["wallet"] is not None + + async def test_cancel_prepare_from_the_admin_panel(self, client, db): + await ready_market(db, closes_in=-60) + _, headers = await session_for(client, ADMIN, wallet=True) + response = await client.post( + "/api/admin/markets/1/cancel/prepare", headers=headers, json={} + ) + assert response.status == 200, await response.text() + tx = (await response.json())["data"] + assert tx["kind"] == "cancel_market" + assert bodies.parse_message_body(tx["payload"]).market_id == 1 + + async def test_cancel_prepare_is_admin_only(self, client, db): + await ready_market(db, closes_in=-60) + _, headers = await session_for(client, USER, wallet=True) + response = await client.post( + "/api/admin/markets/1/cancel/prepare", headers=headers, json={} + ) + assert response.status == 403 + + class TestHardening: async def test_invalid_json(self, client): response = await client.post( @@ -568,6 +703,27 @@ async def test_invalid_json(self, client): ) assert response.status == 400 + async def test_json_must_be_an_object(self, client): + response = await client.post("/api/session", json=[1, 2, 3]) + assert response.status == 400 + + async def test_body_size_is_capped(self, client): + response = await client.post( + "/api/session", data="x" * (api.MAX_BODY + 1024), + headers={"Content-Type": "application/json"}, + ) + assert response.status == 413 + + async def test_unknown_page_is_not_wrapped_as_json(self, client): + response = await client.get("/ruta-que-no-existe") + assert response.status == 404 + assert "application/json" not in response.headers["Content-Type"] + + async def test_trusted_proxy_rejects_a_malformed_ip(self): + assert api._is_trusted_proxy("no-es-una-ip", ("10.0.0.0/8",)) is False + assert api._is_trusted_proxy("10.1.2.3", ()) is False + assert api._is_trusted_proxy("10.1.2.3", ("10.0.0.0/8",)) is True + async def test_rate_limited_sessions(self, client): api._session_limiter.reset() statuses = [] diff --git a/tests/test_config.py b/tests/test_config.py new file mode 100644 index 0000000..641ef87 --- /dev/null +++ b/tests/test_config.py @@ -0,0 +1,110 @@ +"""Configuración: proxies de confianza y validaciones de arranque (Fase 3.1). + +Estas pruebas cubren el contrato de ``TRUST_PROXY``/``TRUSTED_PROXIES``: sin +lista de proxies la cabecera ``X-Forwarded-For`` no se honra (S-04), y una +combinación incoherente falla al arrancar en lugar de quedarse sin efecto +(la lección de D-03). +""" +from __future__ import annotations + +import pytest + +import config + + +def _settings(monkeypatch, **env): + for key, value in env.items(): + monkeypatch.setenv(key, value) + config.reset_settings() + return config.get_settings() + + +class TestTrustProxy: + def test_off_by_default(self): + settings = config.get_settings() + assert settings.trust_proxy is False + assert settings.trusted_proxies == () + + def test_parses_a_cidr_list(self, monkeypatch): + settings = _settings( + monkeypatch, + TRUST_PROXY="true", + TRUSTED_PROXIES="127.0.0.1/32, 10.0.0.0/8; 192.168.1.0/24", + ) + assert settings.trust_proxy is True + assert settings.trusted_proxies == ( + "127.0.0.1/32", + "10.0.0.0/8", + "192.168.1.0/24", + ) + + def test_normalises_a_bare_ip_to_a_host_network(self, monkeypatch): + settings = _settings(monkeypatch, TRUST_PROXY="1", TRUSTED_PROXIES="172.16.5.4") + assert settings.trusted_proxies == ("172.16.5.4/32",) + + def test_rejects_a_malformed_cidr(self, monkeypatch): + with pytest.raises(config.ConfigError): + _settings(monkeypatch, TRUST_PROXY="true", TRUSTED_PROXIES="no-es-una-red") + + def test_trust_proxy_without_a_list_is_a_config_error(self, monkeypatch): + settings = _settings(monkeypatch, TRUST_PROXY="true") + with pytest.raises(config.ConfigError): + settings.validate() + + def test_proxy_list_without_trust_proxy_is_a_config_error(self, monkeypatch): + settings = _settings(monkeypatch, TRUSTED_PROXIES="10.0.0.0/8") + with pytest.raises(config.ConfigError): + settings.validate() + + def test_a_coherent_pair_validates(self, monkeypatch): + settings = _settings( + monkeypatch, TRUST_PROXY="true", TRUSTED_PROXIES="127.0.0.1/32" + ) + settings.validate() # no lanza + + +class TestValidation: + """Los errores de configuración fallan al arrancar, no en producción.""" + + def test_unknown_mode(self, monkeypatch): + with pytest.raises(config.ConfigError): + _settings(monkeypatch, BET_MODE="casino").validate() + + def test_escrow_mode_requires_an_address(self, monkeypatch): + monkeypatch.delenv("ESCROW_ADDRESS", raising=False) + with pytest.raises(config.ConfigError): + _settings(monkeypatch, BET_MODE="escrow").validate() + + def test_escrow_mode_requires_https(self, monkeypatch): + settings = _settings(monkeypatch, PUBLIC_BASE_URL="http://betpoly.test") + with pytest.raises(config.ConfigError): + settings.validate() + + def test_dev_sessions_are_forbidden_in_production(self, monkeypatch): + settings = _settings( + monkeypatch, ENVIRONMENT="production", ALLOW_DEV_SESSION="1", WEB_ENABLED="1" + ) + with pytest.raises(config.ConfigError): + settings.validate() + + def test_production_requires_a_real_secret(self, monkeypatch): + monkeypatch.delenv("SECRET_KEY", raising=False) + settings = _settings(monkeypatch, ENVIRONMENT="production") + with pytest.raises(config.ConfigError): + settings.validate() + + def test_unknown_timezone(self, monkeypatch): + with pytest.raises(config.ConfigError): + _settings(monkeypatch, TIMEZONE="Marte/Olympus").validate() + + def test_non_numeric_points_are_rejected(self, monkeypatch): + with pytest.raises(config.ConfigError): + _settings(monkeypatch, STARTING_POINTS="mil") + + def test_out_of_range_points_are_rejected(self, monkeypatch): + with pytest.raises(config.ConfigError): + _settings(monkeypatch, MIN_BET_POINTS="0") + + def test_admin_ids_must_be_numeric(self, monkeypatch): + with pytest.raises(config.ConfigError): + _settings(monkeypatch, ADMIN_IDS="1001,root") diff --git a/tests/test_web_assets.py b/tests/test_web_assets.py new file mode 100644 index 0000000..141673f --- /dev/null +++ b/tests/test_web_assets.py @@ -0,0 +1,77 @@ +"""Activos web: CSP real y cero manejadores inline (Fase 3.2, S-05). + +La CSP que publica el servidor no permite ``unsafe-inline`` para scripts, así +que cualquier ``onclick="..."`` es un botón muerto. Estas pruebas son un +guardarraíl estático (no hay navegador en CI) más una comprobación de que la +cabecera que se envía de verdad coincide con esa política. +""" +from __future__ import annotations + +import re +from pathlib import Path + +import pytest_asyncio +from aiohttp.test_utils import TestClient, TestServer + +from bot import api + +ROOT = Path(__file__).resolve().parents[1] +INDEX = ROOT / "web" / "index.html" +APP_JS = ROOT / "web" / "static" / "app.js" + +#: ``onclick=``, ``onerror=``… pero no ``data-on...`` ni ``addEventListener``. +INLINE_HANDLER = re.compile(r"(?]*>", html): + assert "src=" in tag, f"script inline bloqueado por la CSP: {tag}" + + def test_the_retry_button_uses_event_delegation(self): + source = APP_JS.read_text(encoding="utf-8") + assert 'data-reload="1"' in source + assert "closest('[data-reload]')" in source + + +class TestCspHeader: + async def test_csp_forbids_inline_scripts(self, web_client): + response = await web_client.get("/") + assert response.status == 200 + csp = response.headers["Content-Security-Policy"] + script_src = next( + part.strip() for part in csp.split(";") if part.strip().startswith("script-src") + ) + assert "'unsafe-inline'" not in script_src + assert "'self'" in script_src + assert "frame-ancestors" in csp + assert "default-src 'self'" in csp + + async def test_security_headers_are_present(self, web_client): + response = await web_client.get("/") + assert response.headers["X-Content-Type-Options"] == "nosniff" + assert response.headers["Referrer-Policy"] == "same-origin" + + async def test_api_responses_carry_the_same_csp(self, web_client): + response = await web_client.get("/api/health") + assert response.status == 200 + assert "script-src" in response.headers["Content-Security-Policy"] + + async def test_static_js_is_served(self, web_client): + response = await web_client.get("/static/app.js") + assert response.status == 200 + assert "data-reload" in await response.text() diff --git a/tests/test_wiring.py b/tests/test_wiring.py index 5b67784..e7ba863 100644 --- a/tests/test_wiring.py +++ b/tests/test_wiring.py @@ -23,11 +23,10 @@ MAIN_PY = ROOT / "main.py" BODIES_PY = ROOT / "bot" / "chain" / "bodies.py" -# Ruta de API sin consumidor en el frontend -> motivo y fase que lo cablea. +# Ruta de API sin consumidor en el frontend -> motivo. Desde la Fase 3 la lista +# solo conserva el endpoint de sondas, que por diseño no consume la UI. KNOWN_API_ORPHANS: Dict[str, str] = { "/api/health": "Endpoint de orquestador / sondas; no lo consume la UI (correcto).", - "/api/wallet": "DELETE sin botón en la Mini App: se cablea en la Fase 3.", - "/api/admin/markets/{x}/cancel/prepare": "Solo alcanzable desde el bot; se cablea en la Fase 3.", } # Builders de cuerpo sin consumidor -> motivo y fase. Vacío desde la Fase 2: diff --git a/web/static/app.js b/web/static/app.js index 12a674e..340809f 100644 --- a/web/static/app.js +++ b/web/static/app.js @@ -183,7 +183,7 @@ function showFatal(message) { const boot = $('#boot'); boot.innerHTML = `

${esc(message)}

- `; + `; } function applyConfig() { @@ -377,7 +377,10 @@ ${esc(points)} puntos ${state.myBets.length} apuestas on-chain ${wins} ganadas -
`; + + ${state.wallet + ? `` + : ''}`; } function marketCard(market) { @@ -483,7 +486,10 @@ 🪙 ${fmtTon(market.pool_ton)} TON ⏰ ${fmtDate(market.closes_at)} - +
+ + +
`).join(''); } @@ -968,6 +974,42 @@ 'Cambio de administrador enviado. Verifícalo on-chain antes de cerrar.'); } + async function unlinkWallet() { + if (!state.wallet) return; + const sure = window.confirm( + '¿Desvincular esta wallet de tu cuenta?\n\nPodrás volver a conectarla cuando quieras.'); + if (!sure) return; + busy(true); + try { + await api('/api/wallet', { method: 'DELETE' }); + busy(false); + state.wallet = null; + renderWallet(); + renderProfile(); + toast('Wallet desvinculada.', 'ok'); + } catch (error) { + busy(false); + toast(friendlyError(error), 'error'); + } + } + + async function adminCancelMarket(marketId) { + const sure = window.confirm( + `¿Cancelar el mercado #${marketId}?\n\nTodos podrán reclamar su reembolso completo.`); + if (!sure) return; + busy(true); + try { + const tx = await api(`/api/admin/markets/${marketId}/cancel/prepare`, { method: 'POST' }); + busy(false); + await signTransaction(tx); + toast('Cancelación enviada. El indexador la confirmará.', 'ok'); + switchView('admin'); + } catch (error) { + busy(false); + toast(friendlyError(error), 'error'); + } + } + async function loadAdminStatus() { try { const status = await api('/api/indexer'); @@ -1027,6 +1069,23 @@ }); document.addEventListener('click', (event) => { + const reloadEl = event.target.closest('[data-reload]'); + if (reloadEl) { + window.location.reload(); + return; + } + const unlinkEl = event.target.closest('[data-unlink-wallet]'); + if (unlinkEl) { + unlinkWallet(); + return; + } + const cancelEl = event.target.closest('[data-admin-cancel]'); + if (cancelEl) { + adminCancelMarket(Number(cancelEl.dataset.adminCancel)).catch((error) => { + toast(friendlyError(error), 'error'); + }); + return; + } const openEl = event.target.closest('[data-open-market]'); if (openEl) { openMarket(Number(openEl.dataset.openMarket)); diff --git a/web/static/styles.css b/web/static/styles.css index 11746a8..5b4e6b4 100644 --- a/web/static/styles.css +++ b/web/static/styles.css @@ -357,3 +357,6 @@ textarea { resize: vertical; min-height: 84px; } .contract-rows > div { display: flex; justify-content: space-between; gap: 10px; } .contract-rows dt { color: var(--muted); font-size: 12.5px; margin: 0; } .contract-rows dd { margin: 0; font-size: 12.5px; font-weight: 650; text-align: right; } + +/* Arranque fallido: el botón «Reintentar» se engancha por delegación (sin inline). */ +.boot-retry { max-width: 240px; margin: 0 auto; } From 6bc6619541dd6e9ef34f05fe1fa20501e4212b95 Mon Sep 17 00:00:00 2001 From: Adlgr87 <164441450+Adlgr87@users.noreply.github.com> Date: Fri, 23 Oct 2026 20:28:30 +0000 Subject: [PATCH 07/17] =?UTF-8?q?Fase=204:=20econom=C3=ADa=20=C3=BAnica=20?= =?UTF-8?q?(F-03),=20importes=20configurables=20(H-*)=20y=20U-05?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - bot/economics.py es la única copia de la fórmula pari-mutuel; database, markets y los handlers la consumen. - La Mini App deja de calcular: pide /api/markets/{id}/quote y solo formatea. - Gas, tope de apuesta, ventanas y TTL pasan a Settings y a /api/config (cierra H-*). - U-05: la confirmación de apuesta de puntos ya no usa formato «x…». - Vectores compartidos contracts/vectors/economics.json + tests de paridad Python/contrato y guardarraíl contra los literales de dinero. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- .env.example | 11 +++ AUDITORIA.md | 13 ++- CHANGELOG.md | 69 +++++++++++++++ PLAN_IMPLEMENTACION.md | 11 ++- README.md | 26 +++++- bot/api.py | 29 ++++++- bot/database.py | 23 ++--- bot/economics.py | 97 +++++++++++++++++++++ bot/handlers/admin.py | 13 ++- bot/handlers/help.py | 2 +- bot/handlers/markets.py | 6 +- bot/markets.py | 140 +++++++++++++++++++++++-------- config.py | 27 ++++++ contracts/tests/escrow.test.js | 48 +++++++++++ contracts/vectors/economics.json | 35 ++++++++ tests/test_admin_contract.py | 2 +- tests/test_api.py | 47 ++++++++++- tests/test_config.py | 40 +++++++++ tests/test_economics.py | 115 +++++++++++++++++++++++++ tests/test_markets_service.py | 69 +++++++++++++-- tests/test_web_assets.py | 18 ++++ web/index.html | 2 +- web/static/app.js | 58 ++++++++++--- 23 files changed, 821 insertions(+), 80 deletions(-) create mode 100644 bot/economics.py create mode 100644 contracts/vectors/economics.json create mode 100644 tests/test_economics.py diff --git a/.env.example b/.env.example index 955d73d..a36aeeb 100644 --- a/.env.example +++ b/.env.example @@ -36,7 +36,18 @@ ESCROW_ADDRESS= ESCROW_ADMIN_ADDRESS= # Apuesta mínima aceptada por el contrato, en nanoTON (0.1 TON) MIN_STAKE_NANO=100000000 +# Apuesta máxima que el backend acepta preparar, en nanoTON (5000 TON) +MAX_STAKE_NANO=5000000000000 MAX_OPTIONS=8 +# Gas adjunto por operación, en nanoTON (0.03 / 0.05 / 0.05 / 0.02 TON) +BET_GAS_NANO=30000000 +CREATE_GAS_NANO=50000000 +ADMIN_GAS_NANO=50000000 +CLAIM_GAS_NANO=20000000 +# Ventana de creación de mercados y caducidad de la firma +MIN_MARKET_DURATION_MIN=15 +MAX_MARKET_DURATION_DAYS=365 +TX_TTL_SECONDS=300 # --- TON Connect / ton_proof ------------------------------------------------- PUBLIC_BASE_URL=https://betpoly.example.com diff --git a/AUDITORIA.md b/AUDITORIA.md index 68076bd..5b89936 100644 --- a/AUDITORIA.md +++ b/AUDITORIA.md @@ -153,10 +153,11 @@ otro usuario NO puede vincularla ❌ -> "Esta wallet ya está vinculada a otra c `README.md:281` marca **F010 Modo grupo ✅**. Las predicciones sí se guardan por `chat_id` (`bot/database.py:169`, `predictions.py:71`), pero el paso del importe es un `MessageHandler` global restringido a privado: `main.py:324` (`filters.ChatType.PRIVATE`). La conversación además se declara `per_user=True, per_chat=False` (`predictions.py:534`). **Impacto:** en un grupo el flujo muere justo antes de apostar, y el estado de la conversación puede cruzarse entre chats del mismo usuario. -### F-03 — 🟠 Los multiplicadores que ve el usuario no descuentan la comisión +### F-03 — ✅ Los multiplicadores que ve el usuario no descuentan la comisión `bot/handlers/markets.py:111` usa `total / pool`; `bot/markets.py:397` publica `multiplier` igual; `web/static/app.js:660-661` calcula el «Pago potencial» sin fee. En cambio `estimate_payout` sí aplica `fee_bps` (`bot/markets.py:322`) y el contrato también. **Impacto:** la UI promete ~2 % más de lo que el contrato pagará (con `FEE_BPS=200`). Cuatro implementaciones distintas de la misma fórmula pari-mutuel en cuatro lenguajes. +**Resuelto (Fase 4):** la fórmula vive solo en `bot/economics.py`; `bot/database.py`, `bot/markets.py` y `bot/handlers/markets.py` la importan, la Mini App pide `GET /api/markets/{id}/quote` y `contracts/vectors/economics.json` fija vectores compartidos con `contracts/tests/escrow.test.js`. ### F-04 — 🟠 No existe notificación de resolución a los apostadores `README.md:278` marca **F007 «Recordatorios de cierre y notificación de resolución» ✅**. Hay recordatorio de cierre (`main.py:331`, `job_reminders`), pero al liquidar una predicción **nadie avisa a los usuarios**: `settle_prediction` (`bot/database.py:606`) no envía mensajes y el resumen solo lo ve el administrador (`bot/handlers/admin.py:233`). @@ -256,6 +257,14 @@ Es el módulo con más condicionales de presentación y el menos probado; `back_ ## 6. Valores hardcodeados (H) +**Estado: H-\* cerrado en la Fase 4.** El gas por operación, el tope de apuesta, +las ventanas de creación y el TTL de firma son ahora campos de `Settings` +(`BET_GAS_NANO`, `CREATE_GAS_NANO`, `ADMIN_GAS_NANO`, `CLAIM_GAS_NANO`, +`MAX_STAKE_NANO`, `MIN_MARKET_DURATION_MIN`, `MAX_MARKET_DURATION_DAYS`, +`TX_TTL_SECONDS`) y `/api/config` los publica en TON para la Mini App. Un test +(`tests/test_economics.py::TestNoMoneyLiterals`) falla si los literales vuelven al +código. La tabla siguiente conserva el diagnóstico original. + No se encontraron secretos, mnemónicos ni direcciones hardcodeadas. Lo que sí está incrustado: | Constante | Ubicación | Comentario | @@ -347,7 +356,7 @@ Es exactamente donde están F-01, F-02, F-04 y S-06: los defectos se concentran | U-02 | El ejemplo de fecha de cierre es `25/12/2025`, ya pasada, y el validador la rechazaría | `bot/handlers/predictions.py:400, 413` | | U-03 | El estado vacío invita a «consultar los resueltos con /mercados», el mismo comando que se acaba de usar (y no existe filtro de resueltos) | `bot/handlers/markets.py:49` | | U-04 | El panel admin lista `predictions[:8]` pero el teclado renderiza todas | `bot/handlers/admin.py:75` vs `bot/keyboards.py:201-212` | -| U-05 | «Pago por punto apostado» mezcla puntos con formato de multiplicador `x…` en el mismo bloque | `bot/handlers/admin.py:175-181` | +| ~~U-05~~ | ✅ «Pago por punto apostado» mezcla puntos con formato de multiplicador `x…` en el mismo bloque. Resuelto en Fase 4: la confirmación habla de «puntos por punto apostado» y del reintegro cuando no hay ganadores | `bot/handlers/admin.py` | | U-06 | `help.py` promete `/admin` y `/ranking` a todos, aunque el panel esté restringido | `bot/handlers/help.py:32-34` | --- diff --git a/CHANGELOG.md b/CHANGELOG.md index 3fa5b5d..2ae5531 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -220,3 +220,72 @@ arregló**, **qué se decidió** y **qué quedó pendiente**. El plan completo v - Fase 4: economía única y coherencia de lo mostrado (F-03, H-*, U-05). - El backstop es en memoria y por proceso: con varias réplicas cada una lleva su propia cuenta (aceptable en el host único de 512 MB; ver ADR-05). + +--- + +## Fase 4 — Economía única y coherencia de lo mostrado (F-03, H-*, U-05) + +**Fecha:** 2026-10-23 + +### Arreglado +- **F-03 · Lo que se muestra y lo que se paga salían de fórmulas distintas.** La + fórmula pari-mutuel vive ahora **solo** en `bot/economics.py` + (`distributable`, `fee_of`, `payout`, `multiplier`, `preview_payout`). La + consumen `bot/database.py` (liquidación de puntos), `bot/markets.py` + (`estimate_payout`, `market_view.multiplier`, `quote_payout`) y + `bot/handlers/markets.py`. Con un pozo de 4 TON repartido 3:1 y 2 % de comisión + el bot ya muestra `3.92x` / `1.307x` en vez de `4.00x` / `1.333x`. +- **F-03 · La Mini App calculaba el «Pago potencial» por su cuenta.** Ahora pide + `GET /api/markets/{id}/quote?option=N&stake_ton=X` (con *debounce* de 250 ms y + guarda de secuencia para descartar respuestas viejas) y pinta el + `payout_ton` del servidor; mientras responde, «Calculando…», y si falla, «—». + El frontend no calcula ningún importe. `market_detail` publica además `fee_bps` + y `fee_percent` por mercado. +- **U-05 · «Pago por punto apostado».** La confirmación de una apuesta de puntos + ya no mezcla puntos con formato de multiplicador: dice «N puntos por punto + apostado» y, cuando nadie acertó, «sin ganadores (se reembolsa todo)». + +### Añadido +- **H-* · Los importes son configuración, no literales.** `Settings` gana + `MAX_STAKE_NANO` (5000 TON), `BET_GAS_NANO`, `CREATE_GAS_NANO`, + `ADMIN_GAS_NANO`, `CLAIM_GAS_NANO`, `MIN_MARKET_DURATION_MIN` (15), + `MAX_MARKET_DURATION_DAYS` (365) y `TX_TTL_SECONDS` (300), con dos + validaciones de arranque (tope ≥ mínimo, duración mínima < máxima). + `.env.example` y `README.md` los documentan. +- **`/api/config` es la única copia para la UI:** publica `max_stake_ton`, + `min_market_duration_min`, `max_market_duration_days`, `bet_gas_ton`, + `create_gas_ton`, `admin_gas_ton` y `claim_gas_ton`. `help.py`, el formulario de + creación y la hoja de apuesta leen de ahí; `web/index.html` deja de traer + `0.05` y `app.js` deja de exigir `+900 s`. +- **`contracts/vectors/economics.json`:** vectores compartidos que ejecutan + `tests/test_economics.py` y `contracts/tests/escrow.test.js` (25 comprobaciones + en el sandbox TVM). Si Python o el contrato se desvían, falla el otro. +- **Guardarraíl contra la reincidencia:** `tests/test_economics.py::TestNoMoneyLiterals` + falla si `30_000_000`, `50_000_000`, `20_000_000`, `5_000 * NANO` o `0.05` + reaparecen en `bot/`, `web/`, `scripts/` o `main.py`, y + `tests/test_web_assets.py::TestNoLocalEconomics` falla si `app.js` vuelve a + mencionar la fórmula o deja de pedir el *quote*. +- Pruebas nuevas: `tests/test_economics.py` (aritmética, truncado, pozo vacío, + vectores compartidos, literales), `/quote` en `tests/test_api.py` y + `tests/test_markets_service.py`, límites publicados y valores por defecto en + `tests/test_config.py`. + +### Decidido +- **El backend es el único que calcula; si no hay *quote*, no hay promesa.** El + plan permitía un respaldo en JS con `fee_bps`; se descarta porque duplicaría la + fórmula (P6) y porque `tests/test_architecture.py` prohíbe `fee_bps` en + `app.js`. Un «—» honesto es mejor que un número inventado. +- **Los vectores son el contrato ejecutable.** Mantener la fórmula en dos + lenguajes es inevitable (FunC y Python); lo que se elimina es el tercer y + cuarto sitio, y un JSON compartido detecta la deriva en lugar de confiar en la + revisión manual. +- **El redondeo sigue siendo `floor` + resto al mayor apostador.** Los pagos suman + exactamente el pozo distribuible; el test lo verifica fila a fila. +- **Se mantiene `RESOLVE_WINDOW_SECONDS` (15 min) como constante de dominio**, no + de configuración: es una regla del producto (no se apuesta en el último cuarto + de hora), no un parámetro de despliegue. + +### Pendiente +- Fase 5: capa Telegram (F-01, F-14, F-02, F-04, S-06, U-01…U-04, U-06). +- F-04 (notificaciones), F-05 (`prepare_cancel` en mercado abierto) y F-06 + (bloqueo optimista de resolución) siguen abiertos, como marca el plan. diff --git a/PLAN_IMPLEMENTACION.md b/PLAN_IMPLEMENTACION.md index 2a8e863..b2fcd88 100644 --- a/PLAN_IMPLEMENTACION.md +++ b/PLAN_IMPLEMENTACION.md @@ -125,7 +125,7 @@ Cada decisión incluye la alternativa descartada y **por qué es subóptima para | ✅ | **1** | Integridad del dinero on-chain | **S-01, S-02, S-07**, F-05, F-06 | 4 | 0 | | ✅ | **2** | Administración del contrato | **S-03**, D-03 | 3-4 | 0, 1 | | ✅ | **3** | Endurecimiento de la API | **S-04, S-05**, D-01 (api), D-02 | 2 | 0 | -| ⬜ | **4** | Economía única y coherencia mostrada | F-03, H-*, U-05 | 2-3 | 1 | +| ✅ | **4** | Economía única y coherencia mostrada | F-03, H-*, U-05 | 2-3 | 1 | | ⬜ | **5** | Capa Telegram: navegación, entrada, notificaciones | F-01, F-14, F-02, F-04, **S-06**, U-01…U-04, U-06 | 4 | 1, 4 | | ⬜ | **6** | Rendimiento y activos | R-01…R-09 | 2-3 | 1, 5 | | ⬜ | **7** | Mantenibilidad, dependencias, contrato-tooling | 5.1, D-04, D-05, D-06, F-07, F-08, F-09, F-12, F-13, T-02 | 3 | 3, 4 | @@ -333,6 +333,15 @@ Helpers `_user_payload(user, user_id)`, `_require_admin(request)`, `_parse_marke ## 7. Fase 4 — Economía única y coherencia de lo mostrado +> **Estado: ✅ implementada.** `bot/economics.py` es la única copia de la +> fórmula; la API publica `multiplier` neto y `GET /api/markets/{id}/quote`; los +> importes son configuración (`Settings` + `/api/config`) y +> `contracts/vectors/economics.json` mantiene la paridad con `escrow.fc`. +> Detalle en `CHANGELOG.md`. Desviación consciente respecto de 4.2: la Mini App +> **no** conserva la fórmula con `fee_bps` como respaldo; si el *quote* falla +> muestra «—», porque `tests/test_architecture.py` prohíbe `fee_bps` en +> `app.js` y una sola copia es el objetivo de la fase. + ### 4.1 · `bot/economics.py` ```python diff --git a/README.md b/README.md index f456cf9..6f453e2 100644 --- a/README.md +++ b/README.md @@ -142,6 +142,15 @@ TON_PROOF_DOMAIN=tu-dominio SECRET_KEY=<32+ bytes aleatorios> TON_NETWORK=mainnet TON_API_KEY=… +# Importes y ventanas (opcionales; estos son los valores por defecto) +MAX_STAKE_NANO=5000000000000 +BET_GAS_NANO=30000000 +CREATE_GAS_NANO=50000000 +ADMIN_GAS_NANO=50000000 +CLAIM_GAS_NANO=20000000 +MIN_MARKET_DURATION_MIN=15 +MAX_MARKET_DURATION_DAYS=365 +TX_TTL_SECONDS=300 # Solo tras un proxy inverso: sin TRUST_PROXY la cabecera X-Forwarded-For se ignora TRUST_PROXY=false TRUSTED_PROXIES=127.0.0.1/32 @@ -168,7 +177,8 @@ Todas las rutas devuelven `{"ok": true, "data": …}` o `{"ok": false, "error": | DELETE | `/api/wallet` | Desvincula la wallet | | GET | `/api/me` | Perfil, puntos, wallet | | GET | `/api/markets` | Mercados del espejo on-chain | -| GET | `/api/markets/{id}` | Detalle + tu apuesta + multiplicadores | +| GET | `/api/markets/{id}` | Detalle + tu apuesta + multiplicadores **netos** de comisión | +| GET | `/api/markets/{id}/quote?option=&stake_ton=` | Pago estimado de una apuesta (`bot/economics.py`) | | POST | `/api/markets/prepare` | Transacción **sin firmar** para crear mercado | | POST | `/api/markets/{id}/bets/prepare` | Transacción sin firmar para apostar | | POST | `/api/markets/{id}/claim/prepare` | Transacción sin firmar para cobrar | @@ -218,6 +228,13 @@ distributable = total_pool − floor(total_pool · fee_bps / 10000) payout = floor(stake · distributable / winning_pool) ``` +Esa fórmula existe **una sola vez** fuera del contrato: `bot/economics.py` +(`distributable`, `fee_of`, `payout`, `multiplier`, `preview_payout`). La usan la +liquidación de puntos, los multiplicadores que muestran el bot y la API, y el +*quote* de la hoja de apuesta de la Mini App, que ya no calcula nada por su +cuenta. `contracts/vectors/economics.json` fija vectores compartidos: si el +contrato y Python se separan, fallan las dos suites. + Si nadie apostó a la opción ganadora, `resolve_market` falla con `412` y el admin debe `cancel_market`: entonces todos cobran su stake completo. | Opcode | Operación | Quién | @@ -252,7 +269,12 @@ Si nadie apostó a la opción ganadora, `resolve_market` falla con `412` y el ad | `416` | Comisión por encima del 10 % | | `417` | `withdraw_fees` tocaría fondos bloqueados | -Límites: `min_stake` configurable (0.1 TON por defecto), `max_options = 8`, cierre entre 5 min y 365 días, reserva de 0.01 TON para almacenamiento. +Límites configurables: `MIN_STAKE_NANO` (0.1 TON), `MAX_STAKE_NANO` (5000 TON), +`MAX_OPTIONS = 8`, cierre entre `MIN_MARKET_DURATION_MIN` (15 min) y +`MAX_MARKET_DURATION_DAYS` (365), gas por operación +(`BET_GAS_NANO`/`CREATE_GAS_NANO`/`ADMIN_GAS_NANO`/`CLAIM_GAS_NANO`) y +`TX_TTL_SECONDS` (300). `/api/config` publica los mismos valores (en TON) para +que la Mini App no repita ni un literal. Los eventos (`0xE0A00001…03`) se envían al `indexer` dentro de una cell con un único ref; `bot/chain/bodies.py` la desenvuelve. diff --git a/bot/api.py b/bot/api.py index b99d884..70ba732 100644 --- a/bot/api.py +++ b/bot/api.py @@ -65,6 +65,7 @@ def _new_backstops( _MARKET_ERROR_STATUS = { "forbidden": 403, "wallet_not_admin": 403, + "market_not_found": 404, "chain_unavailable": 503, } @@ -216,9 +217,14 @@ def public_config() -> Dict[str, Any]: "app_title": settings.app_title, "ton_proof_domain": settings.proof_domain, "support_url": settings.support_url, - "bet_gas_ton": ton(markets.BET_GAS_NANO), - "create_gas_ton": ton(markets.CREATE_GAS_NANO), - "claim_gas_ton": ton(markets.CLAIM_GAS_NANO), + "bet_gas_ton": ton(settings.bet_gas_nano), + "create_gas_ton": ton(settings.create_gas_nano), + "claim_gas_ton": ton(settings.claim_gas_nano), + "admin_gas_ton": ton(settings.admin_gas_nano), + "max_stake_nano": str(settings.max_stake_nano), + "max_stake_ton": ton(settings.max_stake_nano), + "min_market_duration_min": settings.min_market_duration_min, + "max_market_duration_days": settings.max_market_duration_days, } @@ -526,6 +532,22 @@ async def get_market(request: web.Request) -> web.Response: return json_ok(detail) +async def quote_market(request: web.Request) -> web.Response: + """Pago estimado de una apuesta nueva (la Mini App no calcula economía).""" + market_id = _market_id(request) + if market_id is None: + return json_error("bad_market", "market_id inválido.") + try: + option = int(request.query.get("option", "")) + except (TypeError, ValueError): + return json_error("bad_option", "Selecciona una opción válida.") + stake = parse_nano( + request.query.get("stake_ton") or request.query.get("stake"), field="importe" + ) + quote = await markets.quote_payout(market_id, option, stake) + return json_ok(quote) + + async def prepare_market(request: web.Request) -> web.Response: user_id = current_user(request) allowed, retry = _prepare_limiter.allow(f"create:{user_id}") @@ -812,6 +834,7 @@ def create_app( app.router.add_get("/api/markets", list_markets) app.router.add_get("/api/markets/{market_id}", get_market) app.router.add_post("/api/markets/prepare", prepare_market) + app.router.add_get("/api/markets/{market_id}/quote", quote_market) app.router.add_post("/api/markets/{market_id}/bets/prepare", prepare_bet) app.router.add_post("/api/markets/{market_id}/claim/prepare", prepare_claim) app.router.add_post("/api/admin/markets/{market_id}/resolve/prepare", prepare_resolve) diff --git a/bot/database.py b/bot/database.py index 1a95fc9..cb6c76c 100644 --- a/bot/database.py +++ b/bot/database.py @@ -27,6 +27,7 @@ import aiosqlite import config +from bot import economics from bot.formatting import iso_now, iso_utc logger = logging.getLogger(__name__) @@ -635,20 +636,22 @@ async def place_bet(user_id: int, pred_id: int, option_id: int, amount: int) -> def _split_payouts( - winners: List[Dict[str, Any]], distributable: int, winning_pool: int + winners: List[Dict[str, Any]], distributable_pool: int, winning_pool: int ) -> Dict[int, int]: - """Pari-mutuel split with deterministic rounding. + """Reparto pari-mutuel con redondeo determinista. - Every winner receives ``stake * distributable / winning_pool`` rounded down; - the remaining wei are handed out one by one to the largest stakes so the - sum of payouts is *exactly* ``distributable`` (no points are created). + Cada ganador recibe ``payout(stake, distributable, winning_pool)`` (la única + fórmula del proyecto, en :mod:`bot.economics`) redondeada hacia abajo; el + sobrante se reparte de uno en uno entre las apuestas mayores para que la + suma sea *exactamente* el pozo distribuible (no se crean puntos). """ - if winning_pool <= 0 or distributable <= 0: + if winning_pool <= 0 or distributable_pool <= 0: return {b["id"]: 0 for b in winners} payouts = { - b["id"]: (int(b["amount"]) * distributable) // winning_pool for b in winners + b["id"]: economics.payout(int(b["amount"]), distributable_pool, winning_pool) + for b in winners } - remainder = distributable - sum(payouts.values()) + remainder = distributable_pool - sum(payouts.values()) if remainder > 0: order = sorted(winners, key=lambda b: (-int(b["amount"]), b["id"])) for i in range(remainder): @@ -703,8 +706,8 @@ async def settle_prediction(pred_id: int, winning_option_id: int) -> SettlementR # Nobody was right: full refund, no rake. payouts = {b["id"]: int(b["amount"]) for b in bets} else: - rake = (total_pool * settings.house_rake_bps) // 10_000 - distributable = total_pool - rake + distributable = economics.distributable(total_pool, settings.house_rake_bps) + rake = total_pool - distributable payouts = _split_payouts(winners, distributable, winning_pool) now = iso_now() diff --git a/bot/economics.py b/bot/economics.py new file mode 100644 index 0000000..02a0ba9 --- /dev/null +++ b/bot/economics.py @@ -0,0 +1,97 @@ +"""La única implementación de la economía pari-mutuel del proyecto. + +Antes de este módulo la misma fórmula existía cinco veces (contrato, `markets`, +`database`, handlers y JavaScript) y no coincidían: el usuario veía +multiplicadores sin descontar la comisión mientras el contrato sí la descontaba +(F-03). Aquí vive **una** versión, en aritmética entera, y todo lo demás la llama: + +* ``bot/database.py`` — liquidación de los puntos del modo sandbox; +* ``bot/markets.py`` — estimación de pago y multiplicadores de la API; +* ``bot/handlers/*`` — lo que el bot muestra antes de resolver o apostar; +* ``bot/api.py`` — el *quote* que alimenta la hoja de apuesta de la Mini App. + +El contrato (`contracts/escrow.fc`) hace exactamente lo mismo con +``muldiv(total_pool, fee_bps, 10000)``; los vectores compartidos viven en +``tests/test_economics.py`` para que cualquier divergencia falle en CI. +""" +from __future__ import annotations + +from typing import Optional + +#: Los importes se guardan en la unidad mínima (nanoTON / puntos), así que las +#: comisiones se expresan en puntos base: 1 % = 100 bps. +BPS_DENOMINATOR = 10_000 + + +def distributable(total: int, fee_bps: int) -> int: + """Pool que se reparte entre los ganadores tras descontar la comisión. + + Redondea la comisión **hacia abajo** (``muldiv`` del contrato), de modo que + el redondeo nunca deja el pozo sin fondos suficientes. + """ + total = int(total) + if total <= 0: + return 0 + bps = max(0, min(int(fee_bps), BPS_DENOMINATOR)) + fee = (total * bps) // BPS_DENOMINATOR + return total - fee + + +def fee_of(total: int, fee_bps: int) -> int: + """Comisión efectiva (lo que ``distributable`` descuenta).""" + total = int(total) + if total <= 0: + return 0 + bps = max(0, min(int(fee_bps), BPS_DENOMINATOR)) + return (total * bps) // BPS_DENOMINATOR + + +def payout(stake: int, distributable_pool: int, winning_pool: int) -> int: + """Pago de una apuesta ganadora: ``stake · distributable / winning_pool``. + + Siempre redondea hacia abajo y nunca devuelve negativos. Si no hay pozo + ganador no hay pago (el administrador debe cancelar y reembolsar). + """ + stake = int(stake) + distributable_pool = int(distributable_pool) + winning_pool = int(winning_pool) + if stake <= 0 or distributable_pool <= 0 or winning_pool <= 0: + return 0 + return (stake * distributable_pool) // winning_pool + + +def multiplier(total: int, option_pool: int, fee_bps: int) -> Optional[float]: + """Multiplicador **neto** de una opción, o ``None`` si aún no hay pozo. + + Es lo que se muestra al usuario («x2.45» significa que cada TON apostado + devuelve 2.45 TON ya descontada la comisión), por eso aplica el fee. + """ + total = int(total) + option_pool = int(option_pool) + if option_pool <= 0 or total <= 0: + return None + return round(distributable(total, fee_bps) / option_pool, 4) + + +def preview_payout(stake: int, option_pool: int, total: int, fee_bps: int) -> int: + """Pago que tendría una apuesta nueva si el mercado cerrase ahora mismo. + + Incluye la propia apuesta en el pozo (total y opción) antes de calcular el + reparto: es exactamente la pregunta que responde la hoja de apuesta. + """ + stake = int(stake) + if stake <= 0: + return 0 + new_total = int(total) + stake + new_pool = int(option_pool) + stake + return payout(stake, distributable(new_total, fee_bps), new_pool) + + +__all__ = [ + "BPS_DENOMINATOR", + "distributable", + "fee_of", + "multiplier", + "payout", + "preview_payout", +] diff --git a/bot/handlers/admin.py b/bot/handlers/admin.py index a9caa6c..55489a4 100644 --- a/bot/handlers/admin.py +++ b/bot/handlers/admin.py @@ -25,7 +25,7 @@ ) import config -from bot import database, markets +from bot import database, economics, markets from bot.chain.addresses import same_address, to_friendly from bot.formatting import bold, code, esc, fmt_ts, ton from bot.formatting import points as fmt_points @@ -192,14 +192,19 @@ async def admin_winner_callback(update: Update, context: ContextTypes.DEFAULT_TY total = pools.pop(-1, 0) winning_pool = pools.get(opt_id, 0) settings = config.get_settings() - distributable = total - (total * settings.house_rake_bps) // 10_000 - multiplier = f"x{distributable / winning_pool:.2f}" if winning_pool else "sin ganadores (reembolso)" + distributable = economics.distributable(total, settings.house_rake_bps) + if winning_pool: + # Puntos, no TON: «por punto apostado» se expresa con puntos, no con «x». + per_point = distributable / winning_pool + payout_hint = f"{per_point:.2f} puntos por punto apostado" + else: + payout_hint = "sin ganadores (se reembolsa todo)" await edit_or_reply( update, f"⚠️ ¿Confirmas que la opción ganadora es {esc(label)}?\n\n" f"🪙 Pozo: {bold(fmt_points(total))} · en esa opción: {bold(fmt_points(winning_pool))}\n" - f"📈 Pago por punto apostado: {bold(esc(multiplier))}\n\n" + f"📈 Pago: {bold(esc(payout_hint))}\n\n" "Esta acción es irreversible y reparte los puntos una sola vez.", reply_markup=confirm_resolve_keyboard(pred_id, opt_id), ) diff --git a/bot/handlers/help.py b/bot/handlers/help.py index 87ae2f0..da404ae 100644 --- a/bot/handlers/help.py +++ b/bot/handlers/help.py @@ -56,7 +56,7 @@ def build_how_it_works() -> str: "", f"Contrato: {code(settings.escrow_address or '—')}", f"Apuesta mínima: {bold(ton(settings.min_stake_nano))} TON " - f"+ {bold(ton(30_000_000))} TON de gas.", + f"+ {bold(ton(settings.bet_gas_nano))} TON de gas.", "", ] diff --git a/bot/handlers/markets.py b/bot/handlers/markets.py index 77328d4..1484865 100644 --- a/bot/handlers/markets.py +++ b/bot/handlers/markets.py @@ -5,7 +5,7 @@ from telegram.ext import ContextTypes import config -from bot import database +from bot import database, economics from bot.formatting import bold, code, esc, fmt_ts, relative, ton from bot.handlers.common import edit_or_reply, register_user, safe_answer from bot.keyboards import market_detail_keyboard, markets_list_keyboard @@ -106,9 +106,11 @@ async def market_view_callback(update: Update, context: ContextTypes.DEFAULT_TYP f"⏰ Cierra: {esc(fmt_ts(int(market['closes_at'])))}\n", "Opciones", ] + fee_bps = int(market.get("fee_bps") or 0) for idx, label in sorted(options.items()): pool = pools.get(idx, 0) - multiplier = f"x{total / pool:.2f}" if pool else "—" + mult = economics.multiplier(total, pool, fee_bps) + multiplier = f"x{mult:.2f}" if mult else "—" lines.append(f"• {esc(label)} — {bold(ton(pool))} TON ({esc(multiplier)})") if market["status"] == "resolved" and market.get("winning_option") is not None: diff --git a/bot/markets.py b/bot/markets.py index 1c9801a..2e67f2a 100644 --- a/bot/markets.py +++ b/bot/markets.py @@ -20,7 +20,7 @@ from urllib.parse import urlencode import config -from bot import database +from bot import database, economics from bot.chain.addresses import AddressError, normalize_address, to_friendly from bot.chain.bodies import ( build_cancel_market, @@ -43,23 +43,39 @@ NANO = 1_000_000_000 -#: Gas the contract needs on top of the stake (forward fees + storage). -BET_GAS_NANO = 30_000_000 # 0.03 TON -CREATE_GAS_NANO = 50_000_000 # 0.05 TON -ADMIN_GAS_NANO = 50_000_000 # 0.05 TON (funds the lifecycle event) -CLAIM_GAS_NANO = 20_000_000 # 0.02 TON - -MIN_MARKET_DURATION = 15 * 60 # 15 minutes -MAX_MARKET_DURATION = 365 * 24 * 3600 -TX_TTL = 300 # 5 minutes to sign -# While a resolution is prepared and pending on-chain, new bets are refused: -# they would be rejected by the contract and the user would pay gas for nothing. +#: Ventana durante la que se rechazan apuestas mientras hay una resolución +#: preparada: el contrato las rechazaría y el usuario pagaría gas para nada. RESOLVE_WINDOW_SECONDS = 15 * 60 #: The contract caps the fee at 10 %; mirrored here to fail before signing. MAX_FEE_BPS = 1000 -#: Gas every admin operation must attach (it funds the event message). -ADMIN_OP_GAS_NANO = ADMIN_GAS_NANO + + +# -- dinero configurable ---------------------------------------------------- +# Los importes viven en ``config.Settings`` (una sola fuente, H-*); estas +# funciones existen para que nadie tenga que recordar el nombre del campo y para +# que el gas se lea siempre en el momento de preparar la transacción. + +def bet_gas_nano() -> int: + """Gas que acompaña a una apuesta, además del importe.""" + return config.get_settings().bet_gas_nano + + +def create_gas_nano() -> int: + return config.get_settings().create_gas_nano + + +def admin_gas_nano() -> int: + """Gas de cualquier operación de administración (funde el evento).""" + return config.get_settings().admin_gas_nano + + +def claim_gas_nano() -> int: + return config.get_settings().claim_gas_nano + + +def tx_ttl_seconds() -> int: + return config.get_settings().tx_ttl_seconds _escrow_state_cache = EscrowStateCache() @@ -133,7 +149,7 @@ def _prepared( body_cell, *, amount: int, kind: str, summary: str, details: Dict[str, Any] ) -> PreparedTx: escrow = escrow_address() - valid_until = int(time.time()) + TX_TTL + valid_until = int(time.time()) + tx_ttl_seconds() return PreparedTx( to=to_friendly(escrow), amount=int(amount), @@ -196,18 +212,22 @@ async def prepare_create_market( raise MarketError("bad_options", "Cada opción puede tener hasta 60 caracteres.") now = int(time.time()) - if closes_at < now + MIN_MARKET_DURATION: + min_minutes = settings.min_market_duration_min + max_days = settings.max_market_duration_days + if closes_at < now + min_minutes * 60: raise MarketError( "bad_close_date", - f"El cierre debe ser al menos {MIN_MARKET_DURATION // 60} minutos en el futuro.", + f"El cierre debe ser al menos {min_minutes} minutos en el futuro.", + ) + if closes_at > now + max_days * 86_400: + raise MarketError( + "bad_close_date", f"El cierre no puede estar a más de {max_days} días." ) - if closes_at > now + MAX_MARKET_DURATION: - raise MarketError("bad_close_date", "El cierre no puede estar a más de un año.") title_hash = title_to_hash(title) tx = _prepared( build_create_market(title_hash, closes_at, len(cleaned)), - amount=CREATE_GAS_NANO, + amount=create_gas_nano(), kind="create_market", summary=f"Crear mercado: {title[:60]}", details={ @@ -252,8 +272,11 @@ async def prepare_bet(user_id: int, market_id: int, option: int, stake: int) -> "stake_too_low", f"La apuesta mínima es de {ton(settings.min_stake_nano)} TON.", ) - if int(stake) > 5_000 * NANO: - raise MarketError("stake_too_high", "La apuesta máxima es de 5000 TON.") + max_stake = settings.max_stake_nano + if int(stake) > max_stake: + raise MarketError( + "stake_too_high", f"La apuesta máxima es de {ton(max_stake)} TON." + ) existing = await database.get_onchain_bet(int(market_id), normalize_address(wallet["address"])) if existing: @@ -263,7 +286,8 @@ async def prepare_bet(user_id: int, market_id: int, option: int, stake: int) -> options = {int(o["idx"]): o["label"] for o in market.get("options", [])} label = options.get(int(option), f"Opción {int(option) + 1}") - attached = int(stake) + BET_GAS_NANO + gas = bet_gas_nano() + attached = int(stake) + gas tx = _prepared( build_place_bet(int(market_id), int(option), int(stake)), amount=attached, @@ -275,7 +299,7 @@ async def prepare_bet(user_id: int, market_id: int, option: int, stake: int) -> "option_label": label, "stake": str(int(stake)), "stake_ton": ton(int(stake)), - "gas": str(BET_GAS_NANO), + "gas": str(gas), "market_title": market["title"], }, ) @@ -310,7 +334,7 @@ async def prepare_claim(user_id: int, market_id: int) -> PreparedTx: estimate = estimate_payout(bet, market) tx = _prepared( build_claim_payout(int(market_id)), - amount=CLAIM_GAS_NANO, + amount=claim_gas_nano(), kind="claim_payout", summary=f"Reclamar pago del mercado #{int(market_id)}", details={ @@ -339,8 +363,52 @@ def estimate_payout(bet: Dict[str, Any], market: Dict[str, Any]) -> int: if int(bet_option) != int(winning_option): return 0 fee_bps = int(market.get("fee_bps") or 0) - distributable = total - (total * fee_bps) // 10_000 - return (stake * distributable) // winning_pool + return economics.payout(stake, economics.distributable(total, fee_bps), winning_pool) + + +async def quote_payout(market_id: int, option: int, stake: int) -> Dict[str, Any]: + """Pago estimado de una apuesta nueva, calculado **solo** aquí (F-03). + + La Mini App no reimplementa la fórmula pari-mutuel: pide este *quote* y se + limita a formatear lo que devuelve el backend, que es la misma función que + usa la liquidación de puntos y que el contrato. + """ + settings = config.get_settings() + stake = int(stake) + if stake <= 0: + raise MarketError("bad_amount", "Escribe un importe mayor que cero.") + if stake < settings.min_stake_nano: + raise MarketError( + "stake_too_low", f"La apuesta mínima es de {ton(settings.min_stake_nano)} TON." + ) + if stake > settings.max_stake_nano: + raise MarketError( + "stake_too_high", f"La apuesta máxima es de {ton(settings.max_stake_nano)} TON." + ) + detail = await market_detail(int(market_id)) + if not detail.get("is_open"): + raise MarketError("market_closed", "Este mercado ya no acepta apuestas.") + if detail.get("resolving"): + raise MarketError( + "market_resolving", "Hay una resolución en curso: espera unos minutos." + ) + pools = {int(item["index"]): int(item["pool"]) for item in detail["options"]} + if int(option) not in pools: + raise MarketError("bad_option", "Esa opción no existe en este mercado.") + total = int(detail["pool"]) + estimated = economics.preview_payout( + stake, pools[int(option)], total, int(detail.get("fee_bps") or 0) + ) + return { + "market_id": int(market_id), + "option": int(option), + "stake": str(stake), + "stake_ton": ton(stake), + "payout": str(estimated), + "payout_ton": ton(estimated), + "multiplier": economics.multiplier(total + stake, pools[int(option)] + stake, + int(detail.get("fee_bps") or 0)), + } # --------------------------------------------------------------------------- @@ -372,7 +440,7 @@ async def prepare_resolve( await database.set_market_pending_resolve(int(market_id), now) return _prepared( build_resolve_market(int(market_id), int(winning_option)), - amount=ADMIN_GAS_NANO, + amount=admin_gas_nano(), kind="resolve_market", summary=f"Resolver #{int(market_id)} → «{label}»", details={ @@ -412,7 +480,7 @@ async def prepare_cancel( await database.set_market_pending_resolve(int(market_id), now) return _prepared( build_cancel_market(int(market_id)), - amount=ADMIN_GAS_NANO, + amount=admin_gas_nano(), kind="cancel_market", summary=f"Cancelar mercado #{int(market_id)} y habilitar reembolsos", details={"market_id": int(market_id), "market_title": market["title"]}, @@ -518,7 +586,7 @@ async def prepare_withdraw_fees( ) return _prepared( build_withdraw_fees(amount), - amount=ADMIN_OP_GAS_NANO, + amount=admin_gas_nano(), kind="withdraw_fees", summary=f"Retirar {ton(amount)} TON de comisiones", details={ @@ -540,7 +608,7 @@ async def prepare_set_fee(user_id: int, fee_bps: int) -> PreparedTx: ) return _prepared( build_set_fee(bps), - amount=ADMIN_OP_GAS_NANO, + amount=admin_gas_nano(), kind="set_fee", summary=f"Cambiar la comisión a {bps / 100:.2f} %", details={"fee_bps": bps, "fee_percent": round(bps / 100, 2)}, @@ -553,7 +621,7 @@ async def prepare_set_paused(user_id: int, paused: bool) -> PreparedTx: flag = bool(paused) return _prepared( build_set_paused(flag), - amount=ADMIN_OP_GAS_NANO, + amount=admin_gas_nano(), kind="set_paused", summary="Pausar el contrato" if flag else "Reanudar el contrato", details={"paused": flag}, @@ -580,7 +648,7 @@ async def prepare_change_admin(user_id: int, new_address: str) -> PreparedTx: raise MarketError("same_admin", "Esa ya es la dirección administradora.") return _prepared( build_change_admin(target), - amount=ADMIN_OP_GAS_NANO, + amount=admin_gas_nano(), kind="change_admin", summary=f"Transferir la administración a {to_friendly(target)}", details={"new_admin": to_friendly(target), "new_admin_raw": target}, @@ -603,10 +671,11 @@ def market_view(market: Dict[str, Any], *, wallet: Optional[str] = None, total_pool = int(market.get("pool") or market.get("total_pool") or 0) pools = market.get("option_pools") or {} options_out: List[Dict[str, Any]] = [] + fee_bps = int(market.get("fee_bps") or 0) for option in market.get("options", []): idx = int(option["idx"]) pool = int(pools.get(str(idx), 0)) - multiplier = round(total_pool / pool, 4) if pool > 0 and total_pool > 0 else None + multiplier = economics.multiplier(total_pool, pool, fee_bps) options_out.append( { "index": idx, @@ -628,7 +697,8 @@ def market_view(market: Dict[str, Any], *, wallet: Optional[str] = None, "pool": str(total_pool), "pool_ton": ton(total_pool), "bets": int(market.get("bets") or 0), - "fee_bps": int(market.get("fee_bps") or 0), + "fee_bps": fee_bps, + "fee_percent": f"{fee_bps / 100:.2f}", "options": options_out, "seconds_left": max(0, closes_at - now) if closes_at else None, "is_open": market.get("status") == "open" diff --git a/config.py b/config.py index ed9e490..fad70de 100644 --- a/config.py +++ b/config.py @@ -138,8 +138,18 @@ class Settings: ton_proof_domain: Optional[str] ton_proof_max_age: int min_stake_nano: int + max_stake_nano: int max_options: int + # --- dinero on-chain: gas y ventanas (una sola fuente) ---------------- + bet_gas_nano: int + create_gas_nano: int + admin_gas_nano: int + claim_gas_nano: int + min_market_duration_min: int + max_market_duration_days: int + tx_ttl_seconds: int + # --- indexer ---------------------------------------------------------- indexer_enabled: bool indexer_poll_interval: int @@ -219,6 +229,15 @@ def validate(self) -> None: ) if self.is_production and self.secret_key.startswith("dev-"): raise ConfigError("SECRET_KEY must be set to a strong random value in production.") + if self.max_stake_nano < self.min_stake_nano: + raise ConfigError( + "MAX_STAKE_NANO must be >= MIN_STAKE_NANO " + f"(got {self.max_stake_nano} < {self.min_stake_nano})." + ) + if self.min_market_duration_min * 60 >= self.max_market_duration_days * 86_400: + raise ConfigError( + "MIN_MARKET_DURATION_MIN must be shorter than MAX_MARKET_DURATION_DAYS." + ) if self.trust_proxy and not self.trusted_proxies: raise ConfigError( "TRUST_PROXY=true requires TRUSTED_PROXIES (e.g. 127.0.0.1/32): " @@ -267,7 +286,15 @@ def _build_settings() -> Settings: ton_proof_domain=_opt_str("TON_PROOF_DOMAIN"), ton_proof_max_age=_int("TON_PROOF_MAX_AGE", 600, minimum=60, maximum=3600), min_stake_nano=_int("MIN_STAKE_NANO", 100_000_000, minimum=1), + max_stake_nano=_int("MAX_STAKE_NANO", 5_000_000_000_000, minimum=1), max_options=_int("MAX_OPTIONS", 8, minimum=2, maximum=20), + bet_gas_nano=_int("BET_GAS_NANO", 30_000_000, minimum=0), + create_gas_nano=_int("CREATE_GAS_NANO", 50_000_000, minimum=0), + admin_gas_nano=_int("ADMIN_GAS_NANO", 50_000_000, minimum=0), + claim_gas_nano=_int("CLAIM_GAS_NANO", 20_000_000, minimum=0), + min_market_duration_min=_int("MIN_MARKET_DURATION_MIN", 15, minimum=1), + max_market_duration_days=_int("MAX_MARKET_DURATION_DAYS", 365, minimum=1), + tx_ttl_seconds=_int("TX_TTL_SECONDS", 300, minimum=30, maximum=3600), indexer_enabled=_bool("INDEXER_ENABLED", True), indexer_poll_interval=_int("INDEXER_POLL_INTERVAL", 20, minimum=5, maximum=3600), indexer_batch=_int("INDEXER_BATCH", 50, minimum=1, maximum=200), diff --git a/contracts/tests/escrow.test.js b/contracts/tests/escrow.test.js index 694a044..8f88332 100644 --- a/contracts/tests/escrow.test.js +++ b/contracts/tests/escrow.test.js @@ -142,8 +142,56 @@ async function getMarket(blockchain, address, marketId) { }; } +/** + * Vectores compartidos con `bot/economics.py` (Fase 4, F-03). + * + * Reproduce la aritmética de `escrow.fc`: + * distributable = total - muldiv(total, fee_bps, 10000) + * payout = muldiv(stake, distributable, winning_pool) + * con división entera BigInt (truncada, igual que `muldiv` del TVM). + */ +function checkEconomicsVectors() { + const vectors = require(path.join(__dirname, '..', 'vectors', 'economics.json')); + const muldiv = (a, b, c) => (a * b) / c; + const big = (value) => BigInt(value); + const expectedPayout = (stake, distributable, winningPool) => + stake > 0n && distributable > 0n && winningPool > 0n + ? muldiv(stake, distributable, winningPool) + : 0n; + + for (const c of vectors.payouts) { + const total = big(c.total); + const fee = big(c.fee_bps); + const stake = big(c.stake); + const winningPool = big(c.winning_pool); + const distributable = total > 0n ? total - muldiv(total, fee, 10000n) : 0n; + assert.strictEqual( + Number(distributable), c.distributable, + `distributable mismatch for ${JSON.stringify(c)}`, + ); + assert.strictEqual( + Number(expectedPayout(stake, distributable, winningPool)), c.payout, + `payout mismatch for ${JSON.stringify(c)}`, + ); + } + + for (const c of vectors.previews) { + const stake = big(c.stake); + const total = big(c.total) + stake; + const pool = big(c.option_pool) + stake; + const distributable = total - muldiv(total, big(c.fee_bps), 10000n); + assert.strictEqual( + Number(expectedPayout(stake, distributable, pool)), c.payout, + `preview mismatch for ${JSON.stringify(c)}`, + ); + } + step('economía pari-mutuel: vectores compartidos con bot/economics.py'); +} + + async function main() { console.log('\nBetPoly escrow · TVM sandbox tests\n'); + checkEconomicsVectors(); const code = await compile(); const blockchain = await Blockchain.create(); diff --git a/contracts/vectors/economics.json b/contracts/vectors/economics.json new file mode 100644 index 0000000..34d6fa5 --- /dev/null +++ b/contracts/vectors/economics.json @@ -0,0 +1,35 @@ +{ + "_comment": [ + "Vectores compartidos de la economía pari-mutuel.", + "Los consumen tests/test_economics.py (Python) y contracts/tests/escrow.test.js", + " (JavaScript, con la misma aritmética entera que contracts/escrow.fc:", + " distributable = total - muldiv(total, fee_bps, 10000),", + " payout = muldiv(stake, distributable, winning_pool)).", + "Importes en la unidad mínima (nanoTON o puntos). Si alguien cambia la", + "fórmula en un lado, el otro falla." + ], + "payouts": [ + {"total": 0, "fee_bps": 200, "stake": 0, "winning_pool": 0, + "distributable": 0, "payout": 0}, + {"total": 1000000000, "fee_bps": 0, "stake": 500000000, "winning_pool": 500000000, + "distributable": 1000000000, "payout": 1000000000}, + {"total": 4000000000, "fee_bps": 200, "stake": 1000000000, "winning_pool": 1000000000, + "distributable": 3920000000, "payout": 3920000000}, + {"total": 1000000003, "fee_bps": 333, "stake": 333333333, "winning_pool": 1000000003, + "distributable": 966700003, "payout": 322233333}, + {"total": 999, "fee_bps": 1000, "stake": 500, "winning_pool": 999, + "distributable": 900, "payout": 450}, + {"total": 7, "fee_bps": 250, "stake": 3, "winning_pool": 7, + "distributable": 7, "payout": 3} + ], + "previews": [ + {"stake": 1000000000, "option_pool": 0, "total": 0, "fee_bps": 200, + "payout": 980000000}, + {"stake": 2000000000, "option_pool": 1000000000, "total": 4000000000, "fee_bps": 200, + "payout": 3920000000}, + {"stake": 100000000, "option_pool": 0, "total": 0, "fee_bps": 1000, + "payout": 90000000}, + {"stake": 5000000000000, "option_pool": 0, "total": 0, "fee_bps": 0, + "payout": 5000000000000} + ] +} diff --git a/tests/test_admin_contract.py b/tests/test_admin_contract.py index 394ec8d..4cb3f7b 100644 --- a/tests/test_admin_contract.py +++ b/tests/test_admin_contract.py @@ -263,7 +263,7 @@ async def test_builds_unsigned_withdraw(self, db): assert parsed.op == bodies.OP_WITHDRAW_FEES assert parsed.amount == 1_000_000_000 assert tx.kind == "withdraw_fees" - assert tx.amount == markets.ADMIN_OP_GAS_NANO + assert tx.amount == config.get_settings().admin_gas_nano assert tx.details["available_ton"] == "2.5" assert tx.to.startswith("EQ") diff --git a/tests/test_api.py b/tests/test_api.py index 9045d49..46fb05c 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -78,6 +78,20 @@ async def test_config_does_not_leak_secrets(self, client): assert "secret" not in str(data).lower() assert "test-secret" not in str(data) + async def test_config_publishes_the_money_limits(self, client): + """Fase 4.3: la UI no repite importes, los lee de aquí.""" + response = await client.get("/api/config") + data = (await response.json())["data"] + settings = config.get_settings() + assert data["max_stake_ton"] == api.ton(settings.max_stake_nano) + assert data["max_stake_nano"] == str(settings.max_stake_nano) + assert data["bet_gas_ton"] == api.ton(settings.bet_gas_nano) + assert data["create_gas_ton"] == api.ton(settings.create_gas_nano) + assert data["admin_gas_ton"] == api.ton(settings.admin_gas_nano) + assert data["claim_gas_ton"] == api.ton(settings.claim_gas_nano) + assert data["min_market_duration_min"] == settings.min_market_duration_min + assert data["max_market_duration_days"] == settings.max_market_duration_days + async def test_manifest(self, client): response = await client.get("/tonconnect-manifest.json") data = await response.json() @@ -280,9 +294,38 @@ async def test_prepare_create_returns_unsigned_transaction(self, client): tx = (await response.json())["data"] parsed = bodies.parse_message_body(tx["payload"]) assert parsed.op == bodies.OP_CREATE_MARKET - assert tx["amount"] == str(api.markets.CREATE_GAS_NANO) + assert tx["amount"] == str(config.get_settings().create_gas_nano) assert tx["to"].startswith("EQ") + async def test_quote_endpoint_returns_the_backend_formula(self, client, db): + await self._ready_market(db) + response = await client.get( + "/api/markets/1/quote", params={"option": 0, "stake_ton": "1.5"} + ) + assert response.status == 200, await response.text() + data = (await response.json())["data"] + expected = api.markets.economics.preview_payout(1_500_000_000, 0, 0, 200) + assert data["payout"] == str(expected) + assert data["payout_ton"] == api.markets.ton(expected) + assert data["option"] == 0 + + async def test_quote_endpoint_rejects_bad_input(self, client, db): + await self._ready_market(db) + assert (await client.get("/api/markets/1/quote", params={"stake_ton": "1"})).status == 400 + bad_option = await client.get( + "/api/markets/1/quote", params={"option": 9, "stake_ton": "1"} + ) + assert bad_option.status == 400 + assert (await bad_option.json())["error"]["code"] == "bad_option" + bad_stake = await client.get( + "/api/markets/1/quote", params={"option": 0, "stake_ton": "nada"} + ) + assert bad_stake.status == 400 + missing = await client.get( + "/api/markets/99/quote", params={"option": 0, "stake_ton": "1"} + ) + assert missing.status == 404 + async def test_prepare_bet(self, client, db): _, headers = await session_for(client, USER, wallet=True) await self._ready_market(db) @@ -295,7 +338,7 @@ async def test_prepare_bet(self, client, db): tx = (await response.json())["data"] parsed = bodies.parse_message_body(tx["payload"]) assert parsed.stake == 2_500_000_000 - assert tx["amount"] == str(2_500_000_000 + api.markets.BET_GAS_NANO) + assert tx["amount"] == str(2_500_000_000 + config.get_settings().bet_gas_nano) async def test_prepare_bet_rejects_bad_amounts(self, client, db): _, headers = await session_for(client, USER, wallet=True) diff --git a/tests/test_config.py b/tests/test_config.py index 641ef87..bd8c2dc 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -63,6 +63,46 @@ def test_a_coherent_pair_validates(self, monkeypatch): settings.validate() # no lanza +class TestMoneySettings: + """Fase 4.3 (H-*): gas, tope de apuesta y ventanas son configuración.""" + + def test_defaults_match_the_documented_values(self): + settings = config.get_settings() + assert settings.max_stake_nano == 5_000_000_000_000 + assert settings.bet_gas_nano == 30_000_000 + assert settings.create_gas_nano == 50_000_000 + assert settings.admin_gas_nano == 50_000_000 + assert settings.claim_gas_nano == 20_000_000 + assert settings.min_market_duration_min == 15 + assert settings.max_market_duration_days == 365 + assert settings.tx_ttl_seconds == 300 + + def test_env_overrides_them(self, monkeypatch): + settings = _settings( + monkeypatch, + MAX_STAKE_NANO="1000000000", + BET_GAS_NANO="40000000", + MIN_MARKET_DURATION_MIN="5", + TX_TTL_SECONDS="600", + ) + assert settings.max_stake_nano == 1_000_000_000 + assert settings.bet_gas_nano == 40_000_000 + assert settings.min_market_duration_min == 5 + assert settings.tx_ttl_seconds == 600 + + def test_max_stake_cannot_be_below_the_minimum(self, monkeypatch): + settings = _settings(monkeypatch, MAX_STAKE_NANO="1") + with pytest.raises(config.ConfigError): + settings.validate() + + def test_durations_must_be_coherent(self, monkeypatch): + settings = _settings( + monkeypatch, MIN_MARKET_DURATION_MIN="1441", MAX_MARKET_DURATION_DAYS="1" + ) + with pytest.raises(config.ConfigError): + settings.validate() + + class TestValidation: """Los errores de configuración fallan al arrancar, no en producción.""" diff --git a/tests/test_economics.py b/tests/test_economics.py new file mode 100644 index 0000000..b89d9b4 --- /dev/null +++ b/tests/test_economics.py @@ -0,0 +1,115 @@ +"""Fase 4: una sola economía pari-mutuel (F-03, H-*). + +* La fórmula vive en `bot/economics.py` y se prueba aquí. +* `contracts/vectors/economics.json` fija los mismos vectores que consume el + test en JavaScript: si una de las dos implementaciones se desvía, CI falla. +* Un guardarraíl impide que vuelvan los literales de dinero por el árbol. +""" +from __future__ import annotations + +import json +import re +from pathlib import Path + +import pytest + +from bot import economics + +ROOT = Path(__file__).resolve().parents[1] +VECTORS = ROOT / "contracts" / "vectors" / "economics.json" + + +def _vectors() -> dict: + return json.loads(VECTORS.read_text(encoding="utf-8")) + + +class TestDistributable: + def test_keeps_the_pool_when_there_is_no_fee(self): + assert economics.distributable(10_000, 0) == 10_000 + + def test_subtracts_the_fee_rounding_down(self): + assert economics.distributable(999, 1_000) == 900 + assert economics.fee_of(999, 1_000) == 99 + + def test_clamps_a_fee_above_the_denominator(self): + assert economics.distributable(1_000, 50_000) == 0 + + def test_empty_or_negative_pool(self): + assert economics.distributable(0, 200) == 0 + assert economics.distributable(-5, 200) == 0 + assert economics.fee_of(0, 200) == 0 + + +class TestPayout: + def test_shares_the_pool_proportionally(self): + assert economics.payout(500, 1_000, 1_000) == 500 + + def test_rounds_down_and_never_returns_negatives(self): + assert economics.payout(3, 7, 7) == 3 + assert economics.payout(0, 10, 10) == 0 + assert economics.payout(10, 0, 10) == 0 + assert economics.payout(10, 10, 0) == 0 + assert economics.payout(-10, 10, 10) == 0 + + def test_multiplier_is_net_of_the_fee(self): + # 4 TON de pozo, 2 % de comisión → 3.92 por TON apostado, no 4. + assert economics.multiplier(4_000_000_000, 1_000_000_000, 200) == 3.92 + assert economics.multiplier(4_000_000_000, 1_000_000_000, 0) == 4.0 + + def test_multiplier_needs_a_pool(self): + assert economics.multiplier(0, 0, 200) is None + assert economics.multiplier(1_000, 0, 200) is None + + def test_preview_includes_the_new_stake(self): + assert economics.preview_payout(1_000_000_000, 0, 0, 200) == 980_000_000 + assert economics.preview_payout(0, 0, 0, 200) == 0 + + +class TestSharedVectors: + """Los mismos números que valida el sandbox del contrato (JS).""" + + @pytest.mark.parametrize("case", _vectors()["payouts"]) + def test_payout_matches_the_contract(self, case): + pool = economics.distributable(case["total"], case["fee_bps"]) + assert pool == case["distributable"] + assert economics.payout(case["stake"], pool, case["winning_pool"]) == case["payout"] + + @pytest.mark.parametrize("case", _vectors()["previews"]) + def test_preview_matches_the_contract(self, case): + assert economics.preview_payout( + case["stake"], case["option_pool"], case["total"], case["fee_bps"] + ) == case["payout"] + + +class TestNoMoneyLiterals: + """H-*: los importes configuran el sistema, no se copian por el código. + + El barrido ignora `config.py` (donde viven los valores por defecto), los + tests y el contrato (que tiene su propia unidad). + """ + + FORBIDDEN = (r"\b30_000_000\b", r"\b50_000_000\b", r"\b20_000_000\b", + r"5_000\s*\*\s*NANO", r"\b0\.05\b") + ROOTS = ("bot", "web", "scripts", "main.py") + + def _files(self): + for name in self.ROOTS: + path = ROOT / name + if path.is_dir(): + for child in path.rglob("*"): + if child.suffix in (".py", ".js", ".html") and "node_modules" not in child.parts: + yield child + elif path.is_file(): + yield path + + def test_no_hardcoded_money_amounts(self): + offenders = [] + for path in self._files(): + text = path.read_text(encoding="utf-8") + for pattern in self.FORBIDDEN: + for match in re.findall(pattern, text): + offenders.append(f"{path.relative_to(ROOT)}: {match}") + assert not offenders, ( + "importes de dinero incrustados fuera de config.py: " + f"{offenders}. Añádelos a Settings y léelos desde ahí." + ) diff --git a/tests/test_markets_service.py b/tests/test_markets_service.py index 9d670ad..3386a81 100644 --- a/tests/test_markets_service.py +++ b/tests/test_markets_service.py @@ -6,7 +6,7 @@ import pytest import config -from bot import markets +from bot import economics, markets from bot.chain import bodies WALLET = "0:" + "11" * 32 @@ -39,7 +39,7 @@ async def test_builds_unsigned_transaction(self, db): assert parsed.title_hash == bodies.title_to_hash("¿Ganará México?") assert parsed.closes_at == close assert parsed.option_count == 2 - assert tx.amount == markets.CREATE_GAS_NANO + assert tx.amount == config.get_settings().create_gas_nano assert tx.to.startswith("EQ") assert "app.tonkeeper.com/transfer/" in tx.deeplink assert "bin=" in tx.deeplink @@ -91,7 +91,7 @@ async def test_valid_bet(self, db): tx = await markets.prepare_bet(1, 1, 0, 2_000_000_000) parsed = bodies.parse_message_body(tx.payload) assert (parsed.market_id, parsed.option, parsed.stake) == (1, 0, 2_000_000_000) - assert tx.amount == 2_000_000_000 + markets.BET_GAS_NANO + assert tx.amount == 2_000_000_000 + config.get_settings().bet_gas_nano assert tx.details["stake_ton"] == "2" async def test_wallet_required(self, users): @@ -209,7 +209,7 @@ async def test_resolution_payload(self, db): tx = await markets.prepare_resolve(1001, 1, 2) parsed = bodies.parse_message_body(tx.payload) assert (parsed.market_id, parsed.winning_option) == (1, 2) - assert tx.amount == markets.ADMIN_GAS_NANO + assert tx.amount == config.get_settings().admin_gas_nano async def test_invalid_winner(self, db): await _linked(db, 1001) @@ -241,11 +241,30 @@ async def test_market_view_odds(self, db): detail = await markets.market_detail(1, user_id=1) assert detail["pool"] == "4000000000" assert detail["pool_ton"] == "4" - assert detail["options"][0]["multiplier"] == 4.0 - assert detail["options"][1]["multiplier"] == 1.3333 + # F-03: el multiplicador ya descuenta la comisión del mercado (2 %). + assert detail["fee_bps"] == 200 + assert detail["fee_percent"] == "2.00" + assert detail["options"][0]["multiplier"] == 3.92 # 4 × 0.98 + assert detail["options"][1]["multiplier"] == 1.3067 # 1.3333 × 0.98 + # Y el multiplicador publicado coincide con el pago real por TON. + expected = economics.payout( + 1_000_000_000, economics.distributable(4_000_000_000, 200), 1_000_000_000 + ) + assert expected == 3_920_000_000 + assert detail["options"][0]["multiplier"] == round(expected / 1e9, 4) assert detail["my_bet"]["stake"] == "1000000000" assert detail["seconds_left"] > 0 + async def test_displayed_payout_matches_the_claim(self, db): + """F-03: el «Pago estimado» que pinta la Mini App es lo que se reclama.""" + await _linked(db) + await _market(db, status="resolved", closes_in=-60, winning=0, + total=6_000_000_000, winning_pool=4_000_000_000) + await db.record_onchain_bet(1, WALLET, 0, 1_000_000_000, "tx", 1) + detail = await markets.market_detail(1, user_id=1) + tx = await markets.prepare_claim(1, 1) + assert detail["my_estimate"] == tx.details["estimate"] == "1470000000" + async def test_market_detail_missing(self, db): with pytest.raises(markets.MarketError): await markets.market_detail(1234) @@ -257,6 +276,44 @@ async def test_market_view_for_open_market_has_no_multiplier_without_pool(self, assert detail["pool"] == "0" +class TestQuote: + """F-03: el pago que se muestra sale de la misma fórmula que el contrato.""" + + async def test_quote_matches_the_shared_economics(self, db): + await _linked(db) + await _market(db, options=("A", "B"), fee_bps=200) + await db.record_onchain_bet(1, WALLET, 0, 1_000_000_000, "t1", 1) + quote = await markets.quote_payout(1, 1, 2_000_000_000) + expected = economics.preview_payout(2_000_000_000, 0, 1_000_000_000, 200) + assert quote["payout"] == str(expected) + assert quote["payout_ton"] == markets.ton(expected) + assert quote["stake"] == "2000000000" + assert int(quote["payout"]) < 2_000_000_000 + 1_000_000_000 # nunca promete de más + + async def test_quote_rejects_an_unknown_option(self, db): + await _market(db, options=("A", "B")) + with pytest.raises(markets.MarketError) as exc: + await markets.quote_payout(1, 5, 1_000_000_000) + assert exc.value.code == "bad_option" + + async def test_quote_rejects_amounts_out_of_range(self, db): + await _market(db, options=("A", "B")) + with pytest.raises(markets.MarketError) as exc: + await markets.quote_payout(1, 0, 1) + assert exc.value.code == "stake_too_low" + with pytest.raises(markets.MarketError) as exc: + await markets.quote_payout(1, 0, config.get_settings().max_stake_nano + 1) + assert exc.value.code == "stake_too_high" + with pytest.raises(markets.MarketError) as exc: + await markets.quote_payout(1, 0, 0) + assert exc.value.code == "bad_amount" + + async def test_quote_rejects_an_unknown_market(self, db): + with pytest.raises(markets.MarketError) as exc: + await markets.quote_payout(999, 0, 1_000_000_000) + assert exc.value.code == "market_not_found" + + class TestCancelPolicy: """F-05: cancelar un mercado vivo y con apuestas exige confirmación explícita.""" diff --git a/tests/test_web_assets.py b/tests/test_web_assets.py index 141673f..a433f38 100644 --- a/tests/test_web_assets.py +++ b/tests/test_web_assets.py @@ -75,3 +75,21 @@ async def test_static_js_is_served(self, web_client): response = await web_client.get("/static/app.js") assert response.status == 200 assert "data-reload" in await response.text() + + +class TestNoLocalEconomics: + """F-03: la economía la calcula el backend; el frontend solo formatea.""" + + FORBIDDEN = ("winning_pool", "distributable", "house_rake", "fee_bps") + + def test_app_js_does_not_reimplement_the_formula(self): + source = APP_JS.read_text(encoding="utf-8") + found = [token for token in self.FORBIDDEN if token in source] + assert not found, f"app.js calcularía economía propia: {found}" + assert not re.search(r"total\s*\+\s*amount", source) + + def test_the_bet_sheet_asks_the_backend_for_the_quote(self): + source = APP_JS.read_text(encoding="utf-8") + assert "/quote?option=" in source + assert "state.quote" in source + assert "payout_ton" in source diff --git a/web/index.html b/web/index.html index cebd616..da6f389 100644 --- a/web/index.html +++ b/web/index.html @@ -68,7 +68,7 @@

Mis apuestas on-chain

Crear mercado

El mercado se crea on-chain con una transacción firmada por tu wallet. - Tú pagas el gas de creación (≈ 0.05 TON). + Tú pagas el gas de creación (≈ — TON).