fix(B28): failover broadcast push across node pool (V67)

- `distribute._broadcast` push tx SAMA via `Net(host=node).push_transaction()` per node `API_NODES` sampai satu menerima; txid identik → `tx_duplicate`, ⊖ kirim ganda.
- `_is_duplicate` (deteksi `duplicate` di `error.name`/`what`); duplikat sah HANYA bila `_verify_settled(txid) is True` (V61 ⊖ dilemahkan).
- Dipakai send-loop distribusi + `claim._try_claim_once` + `claim._send_fee`.
- Oracles: `test_distribute.py` (blok V67 + pin 1 node utk hold V59/V61), `test_claim.py`, `test_images.py` PASS.
- SPEC §V67/§B28/§T58, AGENTS.md, docker-compose.yml (publish 3308).
This commit is contained in:
proitlab committed 2026-11-18 14:43:45 +07:00
1 parent c262b4677c
commit f9e2e44dad
7 files changed
+218 -14

No files matched your search

+3 -2
View File
@@ -7,6 +7,7 @@ Two tools scan the Vexanium blockchain voters table for accounts whose only vote
- Node reference script: `node get_voters.js` (no deps, Node 18+).
- Python tool (production): `./venv/bin/python get_voters.py`. venv is Python 3.12, deps `requests` + `flask` + `python-dotenv` + `gunicorn` + `pymysql` (mysql backend only) + `pyntelope` (distribute signing) (`requirements.txt`). Install with `./venv/bin/pip install -r requirements.txt`.
- Daily payout (production): `./venv/bin/python distribute.py` — reads the current voters snapshot **restricted to the reward window** (not stale AND account mature, `last_vote > now−28d` AND `first_seen_at ≤ now−3d`, §V40/V52: new voters (`first_seen` recent/NULL) and stale voters get nothing — returning re-voters with mature first_seen are paid regardless of vote age), fetches the BP account's liquid VEX, splits it pro-rata by stake (floor 4-dec, dust stays in the account), and pushes one signed `vex.token::transfer` per voter with memo `DATABISNISID PROFIT SHARE YYYY-MM-DD`. Preview the plan without signing/writing: `./venv/bin/python distribute.py --dry-run`. Requires `VEX_BP_PRIVATE_KEY` (BP active key) in env/`.env`; without it `--dry-run` still works, a real run raises. A real run is a no-op (exit 0) unless `DISTRIBUTE_ENABLED=true` — default is off (kill-switch, V35); `--dry-run` always works. Failed rows are recorded `failed` and rejoined by the next day's run — no manual cleanup needed. **Send safety (V59/V61)**: if a transfer broadcasts but Hyperion can't confirm it, the payment is held for real — marked `failed` at the first attempt and never re-signed (a resend would carry a fresh tapos/expiration → new txid → possible double-send). `verify_txid → None` (Hyperion unreachable) and `executed: false` (index lag, V50/B14) BOTH hold now — the send-loop exception path runs `_verify_settled` (retries the verify 3× with 2s delay to let Hyperion catch up; None → False immediately, pool fully dead) and only `True` marks `sent` + breaks, anything else holds (V61/B21). Chain rejections that come back as HTTP-500 bodies (pyntelope does NOT raise on them — duplicate/insufficient-balance, pattern V46/B11) are detected by `_send_rejected` (V61: WHITELIST — success is only a dict with `transaction_id` + receipt `executed`/no status; any other 500 body or soft_fail → rejected) and routed through the verify/retry path, never recorded `sent` for a tx that didn't land. **Pacing (V63)**: the send loop sleeps `DISTRIBUTE_SEND_DELAY` (default 30s) between voters — N voters → N−1 sleeps, none after the last — so the node/Hyperion can catch up with indexing and broadcast load stays even (real run only; `--dry-run` never sleeps). All `/v2/*` reads guard `isinstance(data, dict)` so a non-dict 200 (proxy misconfig) is skipped, never a crash (V61/B23). **Node resilience (V58)**: all chain RPC calls fail over across the `API_NODES` pool (`VEX_API_NODES` CSV, default `v2.vexascan.com:2096` + `https://api.databisnis.id`) — balance fetch, ABI+TAPOS, and broadcast; the real-run balance fetch retries with backoff ~10 min before aborting to the next schedule, `--dry-run` fails fast. **Hyperion resilience (V60)**: every `/v2/*` read (`verify_txid`, `claim.reward_from_tx`, dashboard SALDO LIQUID) fails over across the `HYPERION_NODES` pool (`VEX_HYPERION_NODES` CSV, default = `HYPERION_API` + `API_NODES` dedup — both hosts verified to serve Hyperion) via `distribute._get_json` (GET mirror of the V58 `_post_json`, 3 rounds, 2s), so a single Hyperion blip no longer force-holds payments or fails reward measurement.
- **Broadcast failover (V67/B28)**: `signed.send()` only pushes to the node pyntelope bound at `link()`, so a 502/503 push endpoint (`api.databisnis.id`, 7–18 Nov 2026 → ~80 `failed` of 442 rows) killed a whole allocation even though `v2.vexascan.com` was healthy. The distribution send loop, `claim._try_claim_once` (claim action) and `claim._send_fee` all call `distribute._broadcast(signed)`, which pushes the **same** signed tx through `Net(host=node).push_transaction()` for each node of `API_NODES` (`SignedTransaction` is pydantic-immutable, so `.net` cannot be re-bound) — payload/signature unchanged ⇒ identical txid, so a second acceptance is `tx_duplicate`, never a double send. `_is_duplicate(resp)` spots `duplicate` in `error.name`/`error.what`; duplicate counts as landed ONLY if `_verify_settled(txid) is True` (V61 not weakened), otherwise `failed`/hold. All nodes failing re-raises into the existing V59/V61 verify/hold path.
- Daily reward claim (production): `./venv/bin/python claim_loop.py` — the `claim` service scheduler. `claim.py` computes the claim window as `last_claim_time + 24h` (from the `vexcore` `producers` table) in **UTC-naive time** (`_utcnow()`, matching the chain's UTC `last_claim_time`; the container's local TZ must not shift the window — V49/B13), sleeps until near it, then polls `vexcore::claimrewards` every `CLAIM_RETRY_SECONDS` (default 60) until the chain accepts; if 24h have already elapsed since the last claim the window clamps to now (missed-window recovery, no permanent spin-timeout). A claim is only treated as "landed" if Hyperion says `executed` OR `last_claim_time` actually advanced past its pre-send value (`_claim_time_advanced`) — on **both** the send-success and send-exception paths (`_confirm_landed`), because pyntelope's `send()` does NOT raise on a chain rejection (HTTP 500 comes back as a JSON body, V46/B11), and Hyperion returning `executed: false` for a just-landed-but-not-yet-indexed tx must NOT count as "didn't land" (V50/B14). Unconfirmed ⇒ silent `retry` (no `claim_runs` row, no success notify) — self-heals when Hyperion indexes the tx on the next poll. The landing baseline (`last_claim_time` before send) is captured **once per poll window** in `poll_claim` and passed to every `_try_claim_once` — it must NOT be re-read per attempt, or a landed-but-stale-first-read claim falls into a permanent retry loop (V54/B16); `_confirm_landed` also retries the post-send `last_claim_time` read so a lagging RPC node doesn't cause a false negative. The **pre-claim liquid balance** is likewise captured **once per poll window** (`before_balance`) and passed to every `_try_claim_once` (V56/B18) — if a claim lands on attempt 1, the next (rejected "already claimed") attempt must still measure the reward via the window-start balance, not a re-read `before` that already includes the credit (which reads delta 0 → false `KLAIM MENDARAT · REWARD TAK TERUKUR`, e.g. the 2026-08-10 claim `bfa9ab02…` reward 1679.3365 recorded against rejected tx `b0a8b2f9…`). `next_window` raises if all producer reads fail (never clamps to now prematurely). Reward is measured **from the claim tx itself** (sum of `vex.bpay`+`vex.vpay` → BP transfers via Hyperion, `reward_from_tx`), **retried up to 4× at `SETTLE_SECONDS` (30s)** so a just-landed tx not yet indexed by Hyperion doesn't read as `None` (V55/B17); if Hyperion is down it falls back to the liquid-balance delta, but **only a positive delta (`after > before`) counts as measured** — a 0 delta is ambiguous (stale node balance) and is treated as unmeasured, never as a genuine zero; if neither can be read the claim is recorded with fee `pending` and an internal `KLAIM MENDARAT · REWARD TAK TERUKUR` alert is sent (never a misleading 0-reward success — a real 0-reward claim must be evidenced by `reward_from_tx` returning `Decimal('0')` from an executed tx). 10% (`VEX_BP_FEE_PERCENT`) is transferred to `VEX_BP_FEE_WALLET` (default `bpdbsjasprod`) with memo `BP FEE YYYY-MM-DD`, reusing `distribute.build_signed_transfer`. A claim cycle is complete only when the claim is recorded in `claim_runs` AND the fee is sent; an unsent fee (`pending`/`failed`) is retried each cycle and resumed on restart (crash-safe). No mutex with `distribute.py` — distribution freezes the balance at run start, so a mid-run claim is deferred to the next run.
- Storage backend: `db.py` abstracts it. Default `sqlite` (`VEX_DB_PATH`, stdlib `sqlite3`, WAL). Optional `mysql` (`VEX_DB_BACKEND=mysql` + `VEX_DB_HOST/PORT/USER/PASS/NAME`, PyMySQL). Oracle tests stay on sqlite; `test_mariadb.py` is opt-in (skips unless `VEX_DB_BACKEND=mysql`). Query SQL is written once with `%s` placeholders (translated to `?` for sqlite); `db.query` always returns a list.
- Test MariaDB/MySQL via docker: `docker compose -f docker-compose.dev.yml up -d` (mariadb:11 container `databisnisid-mariadb`, localhost-only `127.0.0.1:3306`, db/user/pass `databisnisid`/`databisnis`/`databisnis`, named volume, healthcheck). Stop/remove with `docker compose -f docker-compose.dev.yml down`; wipe data with `docker compose -f docker-compose.dev.yml down -v`. Verify with `docker compose -f docker-compose.dev.yml exec mariadb mariadb -u databisnis -pdatabisnis databisnisid -e 'SELECT 1'`. Smoke against the container:
@@ -40,8 +41,8 @@ Two tools scan the Vexanium blockchain voters table for accounts whose only vote
- `get_voters.py` — production fetcher: scan → filter (stake-min + BP target, semua umur vote disimpan V40; hanya last_vote tak terverifikasi dibuang) → `db.replace_snapshot` (each run replaces the table = daily snapshot, with `scanned_at` + derived `last_vote`; never appends history) → `db.record_first_seen` (V41: catat kemunculan pertama tiap owner ke `voter_first_seen`, idempoten). V62: `scanned_at`/`first_seen_at` disimpan UTC-naive (`datetime.now(timezone.utc)`) — konsisten dgn SEMUA cutoff umur (dashboard + distribusi) & `last_vote` (epoch UTC); jangan kembali ke `datetime.now()` lokal (B24: pemilih BARU tertahan +7 jam).
- `db.py` — storage abstraction (sqlite default | mysql via PyMySQL); `connect/query/queryone/replace_snapshot`; `%s` → `?` for sqlite; `query` returns list. Juga tabel distribusi: `distribute_runs` + `distribute_payments` (append-only) + helper `ensure_distribute_schema/record_run/record_payment/update_payment_status/update_run_status/list_runs/list_payments`. Juga tabel klaim: `claim_runs` + helper `ensure_claim_schema/record_claim/update_claim_fee/pending_claim_fee`. Juga tabel V41 `voter_first_seen` (owner PK + `first_seen_at`, append-only) + helper `ensure_first_seen_schema/record_first_seen` — dipakai dashboard membedakan PEMILIH BARU vs REVOTE. Juga helper V57 `eligible_voters(owner=None)` — single-source SQL jendela reward (payout window, V40/V52): `last_vote > now−STALE AND first_seen_at IS NOT NULL AND first_seen_at ≤ now−MATURITY` (cutoff UTC-naive); tanpa `owner` → semua baris `(owner, staked)` utk distribusi; dgn `owner` → baris akun itu (`[]`|one row) utk endpoint cek.
- `get_voters.js` — reference implementation only.
- `distribute.py` — pembayaran harian: fetch liquid balance → baca pemilih **band reward V40/V52** (`db.eligible_voters()` — V57 single source: `last_vote > now−28d AND first_seen_at ≤ now−3d`, pemilih baru (`first_seen` baru/NULL) & basi ⊥ dibayar; akun yang sudah matang dibayar langsung, ⊖ peduli umur vote, V52) → `compute_shares` (Decimal floor 4-des, sisa di akun) → sign `vex.token::transfer` via pyntelope (`trx.link` ambil ABI+TAPOS dari node, `sign` dengan `VEX_BP_PRIVATE_KEY`, `.send()`) → catat `sent/failed` per voter; verifikasi txid via Hyperion sebelum kirim ulang; `--dry-run` = rencana ⊥ tanda tangan; notifikasi Telegram mulai/selesai/gagal via `telegram.py` (best-effort, ⊥ dry-run/no-op). **V58 failover node pool**: `_post_json` coba SEMUA `API_NODES` per putaran (semua gagal → RuntimeError); `build_signed_transfer` coba tiap node utk link+sign (net ter-bind → send ikut node sama); `fetch_balance_with_retry` backoff `[30,60,90,120,150,180]s` (~10 mnt) di real-run sebelum menyerah ke jadwal berikutnya, dry-run satu attempt. **V59 send aman**: `verify_txid` → None (Hyperion down) = TAHAN sungguhan (break + `failed` di attempt 1, ⊖ resend dgn tapos baru yang bisa ganda). **V61 send-path hardening**: `_send_rejected(resp)` WHITELIST — sukses HANYA dict ber-`transaction_id` + receipt `executed`/tanpa-status, body HTTP-500 apa pun (pyntelope ⊥ raise, pola V46/B11) → tolak → raise → jalur verify/retry, ⊖ pernah `sent` utk tx yg ⊥ mendarat; `_verify_settled(txid)` retry `verify_txid` 3× dgn delay utk lag indeks (None → False langsung, pool mati semua) — jalur exception send-loop hold (`failed`+break) pada apa pun selain True, ⊖ RESEND utk `executed:false` (B21). **V60 Hyperion failover**: `_get_json` (GET mirror `_post_json`, 3 putaran, 2s, coba semua `HYPERION_NODES` per putaran → semua gagal → None) dipakai `verify_txid` — None kini berarti SEMUA host Hyperion gagal, jadi hold V59 jarang palsu; semua pembaca `/v2/*` guard `isinstance(data, dict)` (non-dict 200 → skip/skip-node/None, ⊖ crash run, B23). **V63 jeda antar kirim**: send-loop tidur `DISTRIBUTE_SEND_DELAY` (default 30s) ANTAR pemilih — N pemilih → N−1 tidur (⊥ setelah terakhir), beri node/Hyperion waktu mengejar indeks; real-run saja (dry-run ⊖ tidur). `test_distribute.py` — oracle (mock chain+pyntelope, temp DB).
- `claim.py` — klaim reward BP harian: baca `last_claim_time` (tabel `producers`, di-retry V46) → `next_window` = +24 jam, math UTC-naive via `_utcnow()` (V49/B13 — ⊥ `datetime.now()` lokal yang geser +TZ → poll prematur) → (≥24 jam lewat → clamp ke now, recovery B8); tidur sampai mendekat, lalu poll `vexcore::claimrewards` (sign pyntelope `VEX_BP_PRIVATE_KEY`) tiap `CLAIM_RETRY_SECONDS`; deteksi mendarat via `_confirm_landed` di KEDUA jalur (send sukses & exception) = Hyperion `executed` ATAU `last_claim_time` maju dari baseline (V46/B11 — `send()` pyntelope ⊥ raise saat chain menolak, HTTP 500 sbg body; Hyperion `executed: false` utk tx baru-mendarat-belum-terindeks juga dicek lewat `_claim_time_advanced`, V50/B14); tak terkonfirmasi → retry senyap; reward = isi tx via Hyperion (bpay+vpay → BP, `reward_from_tx` via `dist._get_json` pool `HYPERION_NODES`, V60) prioritas — di-RETRY 4× dgn `SETTLE_SECONDS` (30) beri waktu Hyperion indeks tx baru (V55/B17); selisih saldo fallback HANYA delta positif (`after > before`), delta 0 ambigu → ⊥ dianggap reward 0; baseline saldo (`before_balance`) dibaca SEKALI per window & dibawa tiap attempt (V56/B18) — klaim mendarat attempt 1 lalu attempt 2 ditolak (already claimed) ⊖ boleh baca-ulang `before` yg sudah termasuk reward → delta 0 → alert palsu; reward ⊥ terukur → fee `pending` + notif `KLAIM MENDARAT · REWARD TAK TERUKUR` (V33/B10/V55/V56), ⊖ pernah `KLAIM REWARD SUKSES 0.0000` palsu; fee 10% (`VEX_BP_FEE_PERCENT`) floor 4-des → `VEX_BP_FEE_WALLET` via `distribute.build_signed_transfer`, memo `BP FEE YYYY-MM-DD`; fee yang ditolak chain (HTTP-500 body via `dist._send_rejected`, V61/B20) → `failed` + retry, ⊖ pernah `sent` utk fee yg ⊖ mendarat; parse `get_table_rows` pakai `data.get('rows')` (bentuk asli dict, ⊥ `data[0]` — B7/V39); `step()` = state machine (resume fee → jadwal → poll), source of truth `claim_runs` (fee pending/failed diulang + resume saat restart). Modul logika (⊥ CLI). `test_claim.py` — oracle (mock chain+pyntelope, bentuk respons asli, temp DB).
- `distribute.py` — pembayaran harian: fetch liquid balance → baca pemilih **band reward V40/V52** (`db.eligible_voters()` — V57 single source: `last_vote > now−28d AND first_seen_at ≤ now−3d`, pemilih baru (`first_seen` baru/NULL) & basi ⊥ dibayar; akun yang sudah matang dibayar langsung, ⊖ peduli umur vote, V52) → `compute_shares` (Decimal floor 4-des, sisa di akun) → sign `vex.token::transfer` via pyntelope (`trx.link` ambil ABI+TAPOS dari node, `sign` dengan `VEX_BP_PRIVATE_KEY`, push via `_broadcast` V67) → catat `sent/failed` per voter; verifikasi txid via Hyperion sebelum kirim ulang; `--dry-run` = rencana ⊥ tanda tangan; notifikasi Telegram mulai/selesai/gagal via `telegram.py` (best-effort, ⊥ dry-run/no-op). **V58 failover node pool**: `_post_json` coba SEMUA `API_NODES` per putaran (semua gagal → RuntimeError); `build_signed_transfer` coba tiap node utk link+sign (net ter-bind → send ikut node sama); `fetch_balance_with_retry` backoff `[30,60,90,120,150,180]s` (~10 mnt) di real-run sebelum menyerah ke jadwal berikutnya, dry-run satu attempt. **V59 send aman**: `verify_txid` → None (Hyperion down) = TAHAN sungguhan (break + `failed` di attempt 1, ⊖ resend dgn tapos baru yang bisa ganda). **V61 send-path hardening**: `_send_rejected(resp)` WHITELIST — sukses HANYA dict ber-`transaction_id` + receipt `executed`/tanpa-status, body HTTP-500 apa pun (pyntelope ⊥ raise, pola V46/B11) → tolak → raise → jalur verify/retry, ⊖ pernah `sent` utk tx yg ⊥ mendarat; `_verify_settled(txid)` retry `verify_txid` 3× dgn delay utk lag indeks (None → False langsung, pool mati semua) — jalur exception send-loop hold (`failed`+break) pada apa pun selain True, ⊖ RESEND utk `executed:false` (B21). **V60 Hyperion failover**: `_get_json` (GET mirror `_post_json`, 3 putaran, 2s, coba semua `HYPERION_NODES` per putaran → semua gagal → None) dipakai `verify_txid` — None kini berarti SEMUA host Hyperion gagal, jadi hold V59 jarang palsu; semua pembaca `/v2/*` guard `isinstance(data, dict)` (non-dict 200 → skip/skip-node/None, ⊖ crash run, B23). **V63 jeda antar kirim**: send-loop tidur `DISTRIBUTE_SEND_DELAY` (default 30s) ANTAR pemilih — N pemilih → N−1 tidur (⊥ setelah terakhir), beri node/Hyperion waktu mengejar indeks; real-run saja (dry-run ⊖ tidur). `test_distribute.py` — oracle (mock chain+pyntelope, temp DB).
- `claim.py` — klaim reward BP harian: baca `last_claim_time` (tabel `producers`, di-retry V46) → `next_window` = +24 jam, math UTC-naive via `_utcnow()` (V49/B13 — ⊥ `datetime.now()` lokal yang geser +TZ → poll prematur) → (≥24 jam lewat → clamp ke now, recovery B8); tidur sampai mendekat, lalu poll `vexcore::claimrewards` (sign pyntelope `VEX_BP_PRIVATE_KEY`) tiap `CLAIM_RETRY_SECONDS`; aksi klaim di-push via `dist._broadcast` (V67, failover pool); deteksi mendarat via `_confirm_landed` di KEDUA jalur (send sukses & exception) = Hyperion `executed` ATAU `last_claim_time` maju dari baseline (V46/B11 — `send()` pyntelope ⊥ raise saat chain menolak, HTTP 500 sbg body; Hyperion `executed: false` utk tx baru-mendarat-belum-terindeks juga dicek lewat `_claim_time_advanced`, V50/B14); tak terkonfirmasi → retry senyap; reward = isi tx via Hyperion (bpay+vpay → BP, `reward_from_tx` via `dist._get_json` pool `HYPERION_NODES`, V60) prioritas — di-RETRY 4× dgn `SETTLE_SECONDS` (30) beri waktu Hyperion indeks tx baru (V55/B17); selisih saldo fallback HANYA delta positif (`after > before`), delta 0 ambigu → ⊥ dianggap reward 0; baseline saldo (`before_balance`) dibaca SEKALI per window & dibawa tiap attempt (V56/B18) — klaim mendarat attempt 1 lalu attempt 2 ditolak (already claimed) ⊖ boleh baca-ulang `before` yg sudah termasuk reward → delta 0 → alert palsu; reward ⊥ terukur → fee `pending` + notif `KLAIM MENDARAT · REWARD TAK TERUKUR` (V33/B10/V55/V56), ⊖ pernah `KLAIM REWARD SUKSES 0.0000` palsu; fee 10% (`VEX_BP_FEE_PERCENT`) floor 4-des → `VEX_BP_FEE_WALLET` via `distribute.build_signed_transfer`, memo `BP FEE YYYY-MM-DD`; fee yang ditolak chain (HTTP-500 body via `dist._send_rejected`, V61/B20) → `failed` + retry, ⊖ pernah `sent` utk fee yg ⊖ mendarat; parse `get_table_rows` pakai `data.get('rows')` (bentuk asli dict, ⊥ `data[0]` — B7/V39); `step()` = state machine (resume fee → jadwal → poll), source of truth `claim_runs` (fee pending/failed diulang + resume saat restart). Modul logika (⊥ CLI). `test_claim.py` — oracle (mock chain+pyntelope, bentuk respons asli, temp DB).
- `claim_loop.py` — scheduler harian dalam container stack (service `claim`): `_wait_db` (duplikat scan_loop) lalu `claim.step()` terus, loop tak pernah keluar.
- `telegram.py` — kirim notifikasi status distribusi + klaim + peringatan VOTE ULANG SEGERA via Telegram Bot API (best-effort; ⊥ token/chat id → kanal no-op senyap; gagal kirim → log saja). Dua kanal: `TELEGRAM_COMMUNITY_CHAT_IDS` (CSV) = brief mulai/selesai distribusi + VOTE ULANG SEGERA saja; `TELEGRAM_INTERNAL_CHAT_IDS` (CSV) = detail distribusi + semua kegagalan + klaim reward (⊥ komunitas, V30/V36). `send_text(text, chat_ids=None)` = komunitas, `send_internal(text)` = internal; dari env/`.env`/NFS `config.env`. V66a: `send_text`/`notify_warn` return bool pengiriman nyata (⊥ false-positive utk dedup warn, B27).
- `dashboard.py` + `templates/index.html` + `templates/history.html` + `static/style.css` + `static/app.js` — Flask web dashboard; reads the store via `db.py`, styled per `DESIGN.md`; `app.js` = debounced live owner search (fetch `/api/search`), degrades to the server-side `?q=` GET form if JS is off. Three vote-age bands (V40/V52): the voters list is split into BARU (top, `PEMILIH BARU · BELUM MATANG`, new accounts by `first_seen_at` within 3 days) and the main list (`voter-list` section, `.reward` cells, V29) where KADALUARSA rows are pinned at the top with amber styling + `VOTE ULANG` badge + legend before the paged VALID rows, which LEFT-joins a `status='sent'` payments aggregate for the TOTAL REWARD column; since V42 the VALID list also holds REVOTE (returning re-voters, `voter_first_seen.first_seen_at ≤ now−3d`) tagged with a mint `REVOTE` tag (legend `TAG MINT = REVOTE KURANG DARI 1 HARI · VALID LANGSUNG`, shows only while `last_vote > now−VEX_REVOTE_TAG_DAYS`) — no separate band, no maturity wait; only genuinely new voters sit in BARU tagged `BARU`; since V43 VALID rows within `VEX_WARN_DAYS` of the KADALUARSA cutoff get an amber dashed `VOTE ULANG SEGERA` badge + legend `TAG AMBER = KADALUARSA DALAM 3 HARI · N PEMILIH` (display-only); search (`?q=` and `/api/search`) covers all bands and tags each result (`group` = `baru|revote|valid|kadaluarsa` + `expired` + `expiring`); `/api/voter/<owner>` (V57) returns `{"owner", "is_valid_voter"}` — payout-eligibility check via the SAME `db.eligible_voters(owner)` window distribute pays from (never a second SQL copy), DB-snapshot only, always 200; Banner BERITA (V38) shows the next distribution run from `DISTRIBUTE_HOUR`/`DISTRIBUTE_WEEKDAY`/`DISTRIBUTE_FIRST_RUN` + `TZ` (mirror of `distribute_loop.next_boundary`, ⊥ impor lintas-image; drift guarded in test_dashboard; the banner clock is injectable via `dashboard._now()` — the route calls the helper instead of `datetime.now()` inline so the oracle fixes a date instead of depending on the real wall clock, V64/B25); the `SETIAP ... · HH:00` recurrence line renders only for regular weekly rounds — hidden while the next event is the one-off first-run (`_is_first_run_next`, date ≠ weekly day). A `stats-note` caption states the list is single-vote-to-BP accounts ≥ min stake (V47); account names link to `https://vexascan.com/account/{owner}` in the index list, `/history` pay-list, and live search (`.owner-link`, V51); a promo card (`BY DATABISNISID · VEXWALLET`) links the VexWallet Android app on the index page via the IDRS logo (`static/idrs.png`) + `UNDUH DI PLAY STORE` (V53); BARU rows show a `MATURITY PERIOD` countdown column (`VALID DALAM N HARI`) instead of TOTAL REWARD. `/history` = riwayat distribusi read-only; `run-list` = six-column desktop/tablet grid, `pay-list` = four-column grid (AKUN/JUMLAH/STATUS/TXID) showing only the latest run with its date in the title, and labeled mobile cards.
+3
View File
@@ -133,6 +133,7 @@ V63: jeda antar kirim distribusi: send-loop `run_distribution` tidur `DISTRIBUTE
V64: banner BERITA hermetik utk oracle (B25): route index menghitung jam via helper modul `_now()` (isi = `datetime.now()` lokal, ⊖ inline di route) & mengoper ke `_next_schedule(now)`/`_recurrence_label(now)` — test mock `dashboard._now` ke tanggal TETAP (sebelum/sesudah launch) sehingga asersi baris-berulang ⊖ bergantung jam dinding nyata; tanpa ini, setelah tanggal first-run baked (2026-08-17) LEWAT di kalender, `_is_first_run_next(real_now)` ⊖ pernah True (`start >= now` gagal) → baris berulang tampil → asersi "TAK tampil saat first-run" gagal walau `_next_schedule` sudah di-mock (B25; test lulus hanya kalau kalender < tanggal launch). Oracle test_dashboard V38: mock `_now` sebelum launch → baris hilang; sesudah launch → baris muncul | V64,V38,V44
V65: semua stempel data (audit trail, pembayaran, klaim) UTC-naive konsisten — `distribute.py` `created_at`, `db.py` `updated_at` (update_payment_status), `db.py` `now` (update_claim_fee) memakai `datetime.now(timezone.utc).replace(tzinfo=None)` — sama basis dengan `get_voters.persist` (V62), `eligible_voters` (V57), semua cutoff umur dashboard; ⊖ `datetime.now()` lokal yang menghasilkan WIB (UTC+7) dan merusak perbandingan string UTC. Oracle: test_distribute + test_claim tetap hijau | V65,V62,V57,V40,V52
V66: notifikasi VOTE ULANG SEGERA via Telegram + emoticon pada SEMUA notifikasi: `get_voters._notify_warn(now)` setelah `persist()` — query pemilih dalam jendela `now−STALE < last_vote ≤ now−(STALE−WARN)` dari tabel `voters`, hitung urgensi dari sisa hari (≤1d=🚨/3, ≤2d=🔴/2, >2d=⚠️/1), filter yg sdh diberi tahu pada level ≥ urgensi saat ini (tabel `voter_notify`, state-change-only → max 3 notif/pemilih per jendela), kirim via `telegram.notify_warn` ke KOMUNITAS (daftar max 50 + link per-akun `mining.databisnis.id?q={owner}`), catat ke `voter_notify`, bersihkan baris stale. Tabel `voter_notify` (owner PK, urgency INT, notified_at TEXT) — `ensure_notify_schema`/`get_notify_urgency`/`record_notify`/`cleanup_notify` di `db.py`. `Dockerfile.scan` salin `telegram.py`. SEMUA notifikasi Telegram (`notify_start`/`notify_finish`/`notify_failure`/`notify_claim`/`notify_claim_unmeasured`/`notify_claim_failure`) kini punya emoticon prefix (🚀/✅/⚠️/🔴/💰/🔍). Oracle test_get_voters V66: voter_notify schema + record/get/cleanup + _notify_warn integrasi (mock telegram) + skip redundancy + escalation trigger | V66,V62,V40 V66a: kirim dikunci ke pengiriman NYATA — `send_text` return bool (True bila SEMUA chat terkirim), `notify_warn` return bool (True bila semua chunk terkirim), `_notify_warn` catat `voter_notify` HANYA bila `notify_warn` True — gagal/no-op (token kosong, Telegram down) ⊖ pernah mencatat → dedup palsu (B27). `docker-compose.yml` service `scan` bind NFS `config.env:/app/.env:ro` (token+chat id) — sebelum ini scan container ⊖ punya TELEGRAM_* → notif senyap (B27)
V67: failover broadcast push (B28) — `distribute._broadcast(signed)` menggantikan `signed.send()` mentah di send-loop distribusi, `claim._try_claim_once` (aksi klaim) + `claim._send_fee` (fee): push lewat `Net(host=node).push_transaction(transaction=signed)` utk tiap node `API_NODES` sampai satu menerima (`SignedTransaction` pydantic-IMMUTABLE → `.net` ⊖ bisa di-rebind; payload+signature tetap sama). AMAN dari kirim ganda karena payload+signature ⊥ diubah → txid IDENTIK; node kedua yang sudah punya tx menjawab `tx_duplicate`. Beda dgn retry yg menandatangani ulang (TAPOS baru → txid baru → ganda). `_is_duplicate(resp)` deteksi `duplicate` di `error.name`/`error.what`; duplikat HANYA diterima sbg mendarat bila `_verify_settled(txid) is True` (V61 ⊥ dilonggarkan — Hyperion bisa belum melihat tx) → selain itu tetap `failed`/hold. Semua node gagal → exception terakhir dinaikkan ke jalur verify/hold V59/V61. Oracle test_distribute (failover push 502→node sehat, semua-mati raise, txid tetap) + test_claim (fee duplikat tanpa verifikasi → failed).
V35: kill-switch distribusi `DISTRIBUTE_ENABLED` default false → run nyata (bukan dry-run) no-op: exit 0, ⊥ baca saldo, ⊥ tanda tangan, ⊥ tulis DB, ⊥ notif; `--dry-run` tetap menampilkan rencana (read-only); nilai `true`/`1`/`yes` → normal
V36: notifikasi klaim reward (sukses `notify_claim` & gagal `notify_claim_failure`) → kanal INTERNAL saja, ⊥ pernah ke KOMUNITAS (V30); fee gagal ⊥ spam — satu notif per klaim (saat transisi ke `failed`)
V37: jadwal distribusi MINGGUAN (⊥ harian): `distribute_loop` menunggu `DISTRIBUTE_WEEKDAY` — SATU hari (`sat`) atau CSV beberapa hari (`wed,sat`), nama `mon`..`sun` atau 0-6 (V44: multi-hari, event terdekat di antara hari-hari terdaftar) — jam `DISTRIBUTE_HOUR` (lokal TZ); plus satu one-off `DISTRIBUTE_FIRST_RUN` (`YYYY-MM-DD`; default baked `2026-08-17`) yang diambil bila lebih dekat dari mingguan; setelah lewat (atau ⊥ diset) → hanya mingguan; batas dihitung ulang tiap iterasi loop (setelah run → jadwal berikutnya); payout di-tunda bila `DISTRIBUTE_ENABLED=false` (V35) — jadwal tetap maju, run jadi no-op; `distribute_loop.main` baca jadwal via `config` (⊥ `os.getenv` sendiri) agar konsisten dgn dashboard V38
@@ -198,6 +199,7 @@ T54|x|red-team send-path hardening V61 (B20–B23): `distribute.py` — `_send_r
T55|x|stempel scan UTC-naive V62 (B24): `get_voters.persist` ganti `datetime.now()` → `datetime.now(timezone.utc).replace(tzinfo=None)` utk `scanned_at`/`first_seen_at` (konsisten dgn semua cutoff umur UTC + `last_vote`); migrasi data existing DB prod WIB→UTC (−7 jam, backup `*_bak_wib`); docs §V/V62 + §B/B24 + T55 + AGENTS; oracle test_get_voters V62 (stempel ≈ now-UTC-naive, ⊖ WIB)|V62,V52,V41,V7
T56|x|jeda antar kirim V63: `config.py` += `DISTRIBUTE_SEND_DELAY` (int, default 30); `distribute.py` send-loop `enumerate(pending)` + `time.sleep(DISTRIBUTE_SEND_DELAY)` ANTAR pemilih (N pemilih → N−1 tidur, ⊖ setelah terakhir; dry-run ⊖); env compose distribute += `DISTRIBUTE_SEND_DELAY` + `.env.example` + docs §V/V63 + §I/env + T56 + AGENTS; oracle test_distribute V63 (3 pemilih → 2 sleep @ nilai config)|V63,V21,V22,I.env
T57|x|banner hermetik utk oracle V64 (B25): `dashboard.py` route index `now = _now()` (helper modul, ⊖ `datetime.now()` inline) utk `_next_schedule`/`_recurrence_label`; `test_dashboard.py` V38 mock `dashboard._now` ke tanggal tetap sebelum/sesudah launch; docs §V/V64 + §B/B25 + T57 + AGENTS; oracle test_dashboard V38|V64,V38,V44
T58|x|failover broadcast push V67 (B28): `distribute._broadcast` push `Net(host=node).push_transaction()` per node pool (tx SAMA → txid identik, ⊥ ganda) + `_is_duplicate` (duplikat hanya sah bila `_verify_settled` True); pakai di send-loop distribusi + `claim._try_claim_once` + `claim._send_fee`; test_distribute pin 1 node utk uji hold V59/V61 + blok V67; docs §V/V67 + §B/B28 + T58 + AGENTS|V67,V58,V59,V61
## §B — Bug log
id|date|cause|fix
@@ -228,3 +230,4 @@ B24|2026-08-17|`first_seen_at`/`scanned_at` tersimpan WIB (UTC+7) tapi dibanding
B25|2026-08-19|oracle V38 HTML-render bergantung jam dinding nyata: route index `_now = datetime.now()` inline → `_recurrence_label(real_now)` → `_is_first_run_next` cek `start >= now` — setelah tanggal first-run baked (2026-08-17) LEWAT di kalender nyata, `start >= now` ⊖ pernah True → baris berulang `SETIAP RABU & SABTU` tampil → asersi "baris berulang TAK tampil saat first-run" GAGAL walau `_next_schedule` sudah di-mock ke 2026-08-17 (test lulus hanya kalau kalender nyata < tanggal launch)|route pakai helper modul `_now()` injectable + oracle mock `dashboard._now` ke tanggal tetap sebelum/sesudah launch (V64)
B26|2026-08-27|tidak ada notifikasi Telegram untuk pemilih yang masuk jendela VOTE ULANG SEGERA — pemilih hanya terlihat di dashboard dgn badge amber, ⊥ alert proaktif ke komunitas → vote kedaluwarsa tanpa peringatan|`get_voters._notify_warn` + `telegram.notify_warn` + tabel `voter_notify` utk state-change dedup + emoticon pada SEMUA notifikasi (V66)
B27|2026-09-02|notifikasi VOTE ULANG SEGERA ⊖ pernah sampai ke kanal komunitas walau dashboard tampil badge: (1) service `scan` di `docker-compose.yml` ⊖ bind NFS `config.env` (hanya distribute/claim) → container scan `TELEGRAM_BOT_TOKEN`/`TELEGRAM_COMMUNITY_CHAT_IDS` kosong → `send_text` no-op senyap (2) walau no-op, `_notify_warn` TETAP `record_notify` → ledgers `voter_notify` terisi dedup palsu urgent 1→2→3 tiap scan → setelah token dibenahi, dedup `prev >= urgency` memblokir kirim (test manual `_notify_warn` senyap)|(1) compose bind `config.env:/app/.env:ro` utk scan (2) V66a: `send_text`/`notify_warn` return bool pengiriman nyata; `_notify_warn` catat `voter_notify` HANYA bila `True` (V66a); oracle V66 kirim-gagal → ⊖ catat
B28|2026-11-18|distribusi mentok sebagian 7–18 Nov 2026 (~80 `failed` dari 442 baris): `signed.send()` pyntelope hanya push ke node yg mengikat TAPOS saat `link()` — push endpoint `api.databisnis.id` balas 502/503, jadi SEMUA transfer alokasi itu gagal walau `v2.vexascan.com` sehat; jalur verify/hold V59 sebenarnya benar (⊖ resend) tapi ⊥ pernah mencoba node kedua → dana tetap di akun, pemilih ⊥ dibayar|`distribute._broadcast`: `Net(host=node).push_transaction()` per node `API_NODES` (`.net` immutable), kirim ulang tx SAMA (txid identik → `tx_duplicate`, ⊖ ganda) sampai satu menerima; dipakai distribusi + klaim (aksi & fee); `_is_duplicate` + verifikasi V61 (V67)
+11 -5
View File
@@ -273,7 +273,9 @@ def _try_claim_once(last_before=None, before_balance=None):
try:
signed = build_claim_action()
txid = signed.id()
signed.send()
# V67: broadcast failover pool node (B28) — klaim juga kena 502
# `api.databisnis.id`; payload sama → txid sama (⊥ ganda).
dist._broadcast(signed)
landed = _confirm_landed(txid, last_before)
except Exception as exc:
if txid is not None:
@@ -357,14 +359,18 @@ def _send_fee(claim):
try:
signed = dist.build_signed_transfer(BP_FEE_WALLET, fee, memo)
txid = signed.id()
resp = signed.send()
resp = dist._broadcast(signed)
# V61: pyntelope ⊥ raise pada HTTP 500 — penolakan chain (duplicate /
# insufficient-balance) datang sbg body JSON (pola V46/B11). Deteksi →
# perlakukan sbg gagal, ⊖ tandai 'sent' utk fee yang ⊥ pernah mendarat.
if dist._send_rejected(resp):
reason = (resp.get('error', {}).get('what')
if isinstance(resp, dict) else resp)
raise RuntimeError(f'chain menolak fee: {reason}')
# V67: duplicate = tx sudah diterima node lain — tetap WAJIB
# verifikasi (V61): ⊥ buta percaya body nodeos.
if not (dist._is_duplicate(resp)
and dist._verify_settled(txid) is True):
reason = (resp.get('error', {}).get('what')
if isinstance(resp, dict) else resp)
raise RuntimeError(f'chain menolak fee: {reason}')
except Exception as exc:
if txid is not None and dist.verify_txid(txid) is True:
pass # mendarat walau timeout — lanjut tandai sent
+54 -6
View File
@@ -191,14 +191,31 @@ def _send_rejected(resp):
return True
return False
def _is_duplicate(resp):
"""V67: nodeos menolak push krn txid SUDAH ada di chain (`tx_duplicate`).
Terjadi saat `_broadcast` jatuh ke node cadangan setelah node pertama
sebenarnya sudah meneruskan tx (502 dari proxy di depan, bukan dari
nodeos). Duplikat ⇒ tx MENDARAT, jadi diperlakukan sukses — bukan
penolakan. Deteksi: nama/`what` error mengandung 'duplicate'.
"""
if not isinstance(resp, dict):
return False
err = resp.get('error') or {}
if not isinstance(err, dict):
return 'duplicate' in str(err).lower()
blob = f"{err.get('name', '')} {err.get('what', '')}".lower()
return 'duplicate' in blob
def build_signed_transfer(to, amount, memo):
"""Bangun + tanda tangani tx `vex.token::transfer` via pyntelope.
Kembalikan objek SignedTransaction (⊥ broadcast). `amount` = Decimal.
Mengambil ABI + TAPOS dari node saat `link()` — V58: coba SETIAP node di
`API_NODES` (net di-bind ke node itu, jadi broadcast `send()` ikut ke node
yang sama); baru raise bila semua node gagal.
`API_NODES` sampai satu bisa link; baru raise bila semua node gagal.
Broadcast TIDAK lewat `net` hasil link — `_broadcast` (V67) push ulang
lewat pool.
"""
from pyntelope import Action, Authorization, Data, Net, Transaction, types
@@ -229,6 +246,30 @@ def build_signed_transfer(to, amount, memo):
f'Gagal membangun transfer {to} di semua node RPC {API_NODES}: '
f'{last_err}')
def _broadcast(signed):
"""V67 (B28): broadcast tx yang SAMA ke tiap node `API_NODES` sampai satu
menerima — memperbaiki B28: `signed.send()` hanya menghubungi node yang
mengikat TAPOS saat `link()`, jadi push endpoint satu host 502/503
(mis. `api.databisnis.id` 7–18 Nov 2026) menggagalkan seluruh transfer
walau node cadangan sehat.
AMAN dari kirim ganda: payload + signature ⊥ diubah, jadi txid identik —
diterima node kedua = duplikat `tx_duplicate` (ditolak chain), ⊖ transfer
kedua. Failover hanya mengganti host tujuan push. `resp`/exception
diteruskan apa adanya; jalur verify/hold V59/V61 tetap berlaku.
"""
from pyntelope import Net
last_err = None
for node in API_NODES:
try:
# `SignedTransaction` pydantic-immutable (⊥ bisa rebind `.net`),
# jadi push lewat Net baru — payload sama, txid sama.
return Net(host=node).push_transaction(transaction=signed)
except Exception as exc: # node mati/502 → coba cadangan, txid sama
last_err = exc
raise last_err
def run_distribution(dry_run=False):
"""V21..V26: satu run distribusi harian.
@@ -295,14 +336,21 @@ def run_distribution(dry_run=False):
try:
signed = build_signed_transfer(owner, share, memo)
txid = signed.id() # deterministik, sebelum broadcast
resp = signed.send()
resp = _broadcast(signed)
# V59: pyntelope ⊥ raise pada HTTP 500 — penolakan chain datang
# sbg body JSON (pola V46/B11). Deteksi → perlakukan sbg gagal,
# ⊖ tandai 'sent' untuk tx yang ⊥ pernah mendarat.
if _send_rejected(resp):
raise RuntimeError(
f'chain menolak transfer: '
f"{resp.get('error', {}).get('what') or resp}")
# V67: `tx_duplicate` = node lain di pool SUDAH menerima
# tx ini. Tetap WAJIB verifikasi (V61) — Hyperion bisa
# belum melihatnya; ⊥ buta percaya body nodeos.
if not (_is_duplicate(resp)
and _verify_settled(txid) is True):
raise RuntimeError(
f'chain menolak transfer: '
f"{resp.get('error', {}).get('what') or resp}")
print(f'[INFO] {owner}: duplikat, terverifikasi mendarat',
flush=True)
db.update_payment_status(pid, 'sent', txid=txid)
sent_amount += float(share)
print(f'[OK] {owner}: {share} VEX ({txid[:16]}...)',
+3
View File
@@ -23,6 +23,9 @@ services:
- /data/db/mariadb/databisnisid/data:/var/lib/mysql
networks:
- appnet
ports:
- published: 3308
target: 3306
healthcheck:
test: ["CMD", "healthcheck.sh", "--connect", "--innodb_initialized"]
interval: 5s
+27 -1
View File
@@ -19,6 +19,24 @@ import claim
import telegram
import distribute as dist
import pyntelope
class _TestNet:
"""Net palsu: `push_transaction` meneruskan ke `send()` objek tiruan.
`dist._broadcast` (V67) mem-push lewat `Net.push_transaction` karena
`SignedTransaction` asli pydantic-immutable.
"""
def __init__(self, *, host):
self.host = host
def push_transaction(self, *, transaction):
return transaction.send()
pyntelope.Net = _TestNet
def check(tag, cond):
if not cond:
@@ -27,15 +45,23 @@ def check(tag, cond):
class FakeSigned:
"""Objek SignedTransaction tiruan: id deterministik + send terkontrol."""
"""Objek SignedTransaction tiruan: id deterministik + send terkontrol.
Bentuk mengikuti `SignedTransaction` asli (`signatures`, `pack()`) karena
`dist._broadcast` mem-push lewat `Net.push_transaction` (V67).
"""
def __init__(self, txid, exc=None):
self._txid = txid
self._exc = exc
self.signatures = ('SIG',)
def id(self):
return self._txid
def pack(self):
return 'packed-' + self._txid
def send(self):
if self._exc is not None:
raise self._exc
+117
View File
@@ -19,6 +19,25 @@ import db
import distribute as dist
import telegram
import pyntelope
class _TestNet:
"""Net palsu: `push_transaction` meneruskan ke `send()` objek tiruan.
`dist._broadcast` (V67) mem-push lewat `Net.push_transaction` karena
`SignedTransaction` asli pydantic-immutable. Uji cukup menyediakan
`send()` seperti sebelumnya.
"""
def __init__(self, *, host):
self.host = host
def push_transaction(self, *, transaction):
return transaction.send()
pyntelope.Net = _TestNet
def check(tag, cond):
if not cond:
@@ -380,6 +399,10 @@ def main():
calls['run_updates'][0][1] == 'ok')
# ————— V22/V59: verifikasi None → TAHAN (jangan resend), berapa pun attempt —————
# V67: pin satu node — failover pool kini mencoba node cadangan, jadi
# "semua node gagal" harus disimulasikan dgn satu node mati.
_orig_nodes_hold = dist.API_NODES
dist.API_NODES = ['http://node-dead']
dist.DISTRIBUTE_MAX_ATTEMPTS = 3 # default; hold harus jalan di attempt 1
sends = {'n': 0}
@@ -399,6 +422,8 @@ def main():
sends['n'] == 2) # 2 pemilih di seed V21, tiap hanya 1 attempt
check('V22 run status partial',
calls['run_updates'][0][1] == 'partial')
dist.API_NODES = _orig_nodes_hold # V67: pulihkan pool utk uji berikutnya
# ————— V59: penolakan chain (HTTP-500 body) ⊖ boleh jadi 'sent' —————
class FakeSignedReject:
@@ -432,6 +457,7 @@ def main():
# ————— V61: verify_txid False (Hyperion bilang tak mendarat) → TAHAN —————
# False bisa lag indeks utk tx yang BARU mendarat (pola V50/B14 di klaim):
# resend = tapos baru = txid baru = ganda. → hold di attempt 1, ⊖ resend.
dist.API_NODES = ['http://node-dead'] # V67: semua node gagal → hold
dist.DISTRIBUTE_MAX_ATTEMPTS = 3 # default; hold harus jalan di attempt 1
dist.time.sleep = lambda s: None
sends_false = {'n': 0}
@@ -452,6 +478,8 @@ def main():
sends_false['n'] == 2)
check('V61 run status partial',
calls['run_updates'][0][1] == 'partial')
dist.API_NODES = _orig_nodes_hold # V67: pulihkan pool
# ————— V61: `_send_rejected` whitelist — bentuk tak dikenal = tolak —————
check('V61 sukses nodeos (transaction_id + executed) → ⊖ tolak',
@@ -469,6 +497,95 @@ def main():
is True)
check('V61 non-dict response → tolak', dist._send_rejected(['x']) is True)
# ————— V67/B28: broadcast failover — node 1 push 502, node 2 menerima —
# Root cause produksi 7–18 Nov 2026: `signed.send()` hanya ke node yang
# mengikat TAPOS; push endpoint `api.databisnis.id` 502/503 → seluruh
# transfer gagal walau `v2.vexascan.com` sehat. Fix: broadcast tx SAMA
# (txid identik → ⊥ bisa ganda) ke tiap node sampai satu menerima.
_orig_nodes_v67 = dist.API_NODES
dist.API_NODES = ['http://node-bad', 'http://node-good']
push_hosts = []
class FakeNetV67:
def __init__(self, *, host):
self.host = host
def push_transaction(self, *, transaction):
push_hosts.append(self.host)
if 'bad' in self.host:
raise RuntimeError('502 Bad Gateway (mock)')
return {'transaction_id': transaction.id(),
'processed': {'receipt': {'status': 'executed'}}}
class FakeSignedV67:
def __init__(self, txid):
self._txid = txid
self.signatures = ('SIG',)
def id(self):
return self._txid
def pack(self):
return 'packed-' + self._txid
import pyntelope as _pynt
_saved_net = _pynt.Net
_pynt.Net = FakeNetV67
try:
tx = FakeSignedV67('txV67')
resp = dist._broadcast(tx)
check('V67 push 502 → failover node cadangan',
push_hosts == ['http://node-bad', 'http://node-good'])
check('V67 respons node sehat diteruskan',
resp['processed']['receipt']['status'] == 'executed')
check('V67 txid ⊥ berubah saat failover (⊥ ganda)', tx.id() == 'txV67')
# semua node mati → exception terakhir dinaikkan (jalur verify/hold)
dist.API_NODES = ['http://node-bad']
push_hosts.clear()
try:
dist._broadcast(FakeSignedV67('txX'))
check('V67 semua node gagal → raise', False)
except RuntimeError:
check('V67 semua node gagal → raise', True)
finally:
_pynt.Net = _saved_net
dist.API_NODES = _orig_nodes_v67
# `_is_duplicate`: hanya tx_duplicate yang dianggap mendarat
check('V67 error duplicate → True',
dist._is_duplicate({'code': 500,
'error': {'what': 'duplicate transaction'}})
is True)
check('V67 error lain → False',
dist._is_duplicate({'code': 500,
'error': {'what': 'insufficient balance'}})
is False)
check('V67 non-dict → False', dist._is_duplicate(['x']) is False)
# duplicate TANPA verifikasi chain → tetap ditahan (V61 ⊥ dilonggarkan)
class FakeSignedDup:
def __init__(self, txid):
self._txid = txid
def id(self):
return self._txid
def send(self):
return {'code': 500,
'error': {'what': 'duplicate transaction'}}
dist.DISTRIBUTE_MAX_ATTEMPTS = 1
dist.build_signed_transfer = (lambda to, amount, memo:
FakeSignedDup('txDup' + to))
dist.verify_txid = lambda txid: False # Hyperion: belum terlihat
calls['updates'] = []
calls['run_updates'] = []
with redirect_stdout(io.StringIO()):
dist.run_distribution(dry_run=False)
check('V67 duplikat tanpa verifikasi → failed (⊥ buta percaya)',
all(u[1] == 'failed' for u in calls['updates']))
# ————— V61: `_get_json`/`verify_txid` ⊖ crash pada bentuk non-dict —————
_orig_verify = dist.verify_txid # restore dr mock False di uji V61-F2
dist.verify_txid = _real_verify