security: fix batch-payout tx_hash collision and double-pay risk

transfer_split sends one on-chain tx to many destinations, so payout rows
in a batch share a tx_hash. The old UNIQUE index on payouts.tx_hash made
the 2nd+ row fail to record, leaving funds sent but rows stranded in
'processing' and re-sendable by the retry service.

- Migration 015 drops the payouts tx_hash unique index (idempotency is
  enforced by idx_payouts_one_per_game) and extends that guard to cover
  'processing' so no second payable row can be inserted mid-flight.
- Batch completion now updates the whole batch in a single transaction via
  id = ANY(...), so rows can't be left half-completed. Per-user stats use
  BIGINT arithmetic in SQL (no JS float).
- Ambiguous batch failures are marked 'needs_review' (which the retry
  service does NOT pick up) instead of 'failed', preventing a double-send
  when transfer_split may have already broadcast. Operator is alerted.

Adds batchPayout.test.js covering the shared-tx_hash completion and the
needs_review failure path. Full suite: 12 suites / 115 tests.
This commit is contained in:
jwinterm
2026-05-31 09:26:14 -04:00
parent 3e6e3b858b
commit d07967c3d1
4 changed files with 165 additions and 19 deletions
@@ -0,0 +1,20 @@
-- Migration 015: Allow batched payouts to share a tx_hash; tighten one-per-game guard
--
-- `transfer_split` sends ONE on-chain transaction to many destinations, so multiple
-- payout rows in a batch legitimately share the same tx_hash. The old UNIQUE index on
-- payouts.tx_hash (migration 008) made the 2nd+ row in a batch fail to record its
-- tx_hash, leaving funds already sent but rows stranded in 'processing' — and at risk
-- of being re-sent by the retry service (a double-payout vector).
--
-- Payout idempotency does NOT depend on tx_hash uniqueness; it is enforced by
-- idx_payouts_one_per_game (one active payout per game). So we drop the payouts
-- tx_hash unique index. (The payments.tx_hash unique index stays — incoming payments
-- are 1:1 with a transaction.)
DROP INDEX IF EXISTS idx_payouts_tx_hash_unique;
-- Extend the one-active-payout-per-game guard to also cover 'processing', so a second
-- payable row cannot be inserted for a game while its payout is mid-flight.
DROP INDEX IF EXISTS idx_payouts_one_per_game;
CREATE UNIQUE INDEX IF NOT EXISTS idx_payouts_one_per_game
ON payouts(game_id)
WHERE game_id IS NOT NULL AND status IN ('pending', 'processing', 'completed');