mirror of
https://github.com/Such-Software/wownerogue.git
synced 2026-12-04 12:54:08 +01:00
feat: productionize paid modes and PvP capture
This commit is contained in:
@@ -6,7 +6,8 @@
|
||||
-- Design notes:
|
||||
-- - One fact, one table: matches, entrants, events, queue, and ticket ledger are separate.
|
||||
-- - All money movement uses DatabaseManager.withTransaction() at the application layer.
|
||||
-- - Provably fair: seed_hash stored at creation, seed revealed on finish (like solo games).
|
||||
-- - Verifiable commitment: seed_hash stored at creation and seed revealed on finish. Production
|
||||
-- paid matches additionally persist chain-block derivation metadata inside dungeon JSON.
|
||||
-- - Tickets (race_entries) are non-refundable crypto-race entry tokens; they avoid the
|
||||
-- need for on-chain refunds when a player leaves the queue before a match starts.
|
||||
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
-- Persist the operator-selected gameplay ruleset independently from the coarse legacy
|
||||
-- matches.variant ('race'/'pvp'). Existing rows are classic races; new built-ins such as
|
||||
-- score-attack and coop-escape remain fully auditable without widening money/economy keys.
|
||||
|
||||
ALTER TABLE matches
|
||||
ADD COLUMN IF NOT EXISTS ruleset_id VARCHAR(64) NOT NULL DEFAULT 'race';
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_matches_ruleset_finished
|
||||
ON matches (ruleset_id, ended_at DESC)
|
||||
WHERE status = 'finished';
|
||||
@@ -0,0 +1,22 @@
|
||||
-- Durable two-party proof material for solo games. The server seed is stored privately for
|
||||
-- crash/audit recovery but is exposed by verification routes only after the game completes.
|
||||
|
||||
ALTER TABLE games
|
||||
ADD COLUMN IF NOT EXISTS proof_version SMALLINT NOT NULL DEFAULT 1,
|
||||
ADD COLUMN IF NOT EXISTS fairness_offer_id VARCHAR(64),
|
||||
ADD COLUMN IF NOT EXISTS fairness_offer_issued_at TIMESTAMPTZ,
|
||||
ADD COLUMN IF NOT EXISTS proof_commitment CHAR(64),
|
||||
ADD COLUMN IF NOT EXISTS server_seed CHAR(64),
|
||||
ADD COLUMN IF NOT EXISTS client_seed VARCHAR(64) NOT NULL DEFAULT '',
|
||||
ADD COLUMN IF NOT EXISTS effective_seed CHAR(64),
|
||||
ADD COLUMN IF NOT EXISTS layout_fingerprint CHAR(64),
|
||||
ADD COLUMN IF NOT EXISTS proof_context JSONB,
|
||||
ADD COLUMN IF NOT EXISTS proof_revealed_at TIMESTAMPTZ;
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_games_fairness_offer_once
|
||||
ON games (fairness_offer_id)
|
||||
WHERE fairness_offer_id IS NOT NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_games_proof_commitment
|
||||
ON games (proof_commitment)
|
||||
WHERE proof_commitment IS NOT NULL;
|
||||
@@ -0,0 +1,56 @@
|
||||
-- Durable, idempotent admin payment refunds.
|
||||
--
|
||||
-- Only `requested` rows may be claimed by the application. A `processing` row means a
|
||||
-- wallet call may have been made and must never be retried automatically: if the process
|
||||
-- dies or loses the wallet response, an operator must reconcile it first.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS payment_refunds (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
payment_id INTEGER NOT NULL REFERENCES payments(id) ON DELETE RESTRICT,
|
||||
user_id INTEGER REFERENCES users(id) ON DELETE SET NULL,
|
||||
status VARCHAR(20) NOT NULL,
|
||||
amount BIGINT NOT NULL,
|
||||
payout_address VARCHAR(200),
|
||||
credits_deducted BIGINT NOT NULL DEFAULT 0,
|
||||
reason TEXT NOT NULL,
|
||||
tx_hash VARCHAR(128),
|
||||
error_message TEXT,
|
||||
requested_at TIMESTAMPTZ,
|
||||
processing_started_at TIMESTAMPTZ,
|
||||
completed_at TIMESTAMPTZ,
|
||||
needs_review_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
|
||||
CONSTRAINT payment_refunds_payment_once UNIQUE (payment_id),
|
||||
CONSTRAINT payment_refunds_status_check
|
||||
CHECK (status IN ('recorded', 'requested', 'processing', 'completed', 'needs_review')),
|
||||
CONSTRAINT payment_refunds_amount_check CHECK (amount >= 0),
|
||||
CONSTRAINT payment_refunds_credits_check CHECK (credits_deducted >= 0),
|
||||
CONSTRAINT payment_refunds_state_shape_check CHECK (
|
||||
(status = 'recorded')
|
||||
OR (status = 'requested' AND requested_at IS NOT NULL)
|
||||
OR (
|
||||
status = 'processing'
|
||||
AND requested_at IS NOT NULL
|
||||
AND processing_started_at IS NOT NULL
|
||||
)
|
||||
OR (
|
||||
status = 'completed'
|
||||
AND requested_at IS NOT NULL
|
||||
AND processing_started_at IS NOT NULL
|
||||
AND completed_at IS NOT NULL
|
||||
AND tx_hash IS NOT NULL
|
||||
AND LENGTH(tx_hash) > 0
|
||||
)
|
||||
OR (
|
||||
status = 'needs_review'
|
||||
AND requested_at IS NOT NULL
|
||||
AND error_message IS NOT NULL
|
||||
AND LENGTH(error_message) > 0
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_payment_refunds_status
|
||||
ON payment_refunds(status, created_at);
|
||||
@@ -0,0 +1,91 @@
|
||||
-- Migration 032: immutable solo payout commitments and unconditional payout identity
|
||||
--
|
||||
-- A paid game's payout eligibility and exact terms are committed in the same transaction
|
||||
-- that consumes its entry. Runtime kill switches may pause dispatch, but cannot erase or
|
||||
-- retroactively create an already-committed liability.
|
||||
ALTER TABLE games
|
||||
ADD COLUMN IF NOT EXISTS payout_eligible BOOLEAN,
|
||||
ADD COLUMN IF NOT EXISTS payout_terms JSONB,
|
||||
ADD COLUMN IF NOT EXISTS payout_committed_at TIMESTAMPTZ;
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint WHERE conname = 'games_payout_commitment_complete'
|
||||
) THEN
|
||||
ALTER TABLE games
|
||||
ADD CONSTRAINT games_payout_commitment_complete
|
||||
CHECK (
|
||||
payout_committed_at IS NULL
|
||||
OR (payout_eligible IS NOT NULL AND payout_terms IS NOT NULL)
|
||||
) NOT VALID;
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
CREATE OR REPLACE FUNCTION reject_game_payout_commitment_mutation()
|
||||
RETURNS TRIGGER AS $$
|
||||
BEGIN
|
||||
IF OLD.payout_committed_at IS NOT NULL AND (
|
||||
NEW.user_id IS DISTINCT FROM OLD.user_id
|
||||
OR NEW.payout_eligible IS DISTINCT FROM OLD.payout_eligible
|
||||
OR NEW.payout_terms IS DISTINCT FROM OLD.payout_terms
|
||||
OR NEW.payout_committed_at IS DISTINCT FROM OLD.payout_committed_at
|
||||
OR NEW.payout_escape_amount IS DISTINCT FROM OLD.payout_escape_amount
|
||||
OR NEW.payout_treasure_amount IS DISTINCT FROM OLD.payout_treasure_amount
|
||||
OR NEW.payout_escape_mult IS DISTINCT FROM OLD.payout_escape_mult
|
||||
OR NEW.payout_treasure_mult IS DISTINCT FROM OLD.payout_treasure_mult
|
||||
OR NEW.payout_address IS DISTINCT FROM OLD.payout_address
|
||||
OR NEW.game_mode IS DISTINCT FROM OLD.game_mode
|
||||
OR NEW.payment_id IS DISTINCT FROM OLD.payment_id
|
||||
) THEN
|
||||
RAISE EXCEPTION 'committed solo payout terms are immutable for game %', OLD.id
|
||||
USING ERRCODE = '23514';
|
||||
END IF;
|
||||
IF OLD.payout_committed_at IS NULL
|
||||
AND NEW.payout_committed_at IS NOT NULL
|
||||
AND NEW.user_id IS DISTINCT FROM OLD.user_id
|
||||
THEN
|
||||
RAISE EXCEPTION 'solo payout owner cannot change while committing game %', OLD.id
|
||||
USING ERRCODE = '23514';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
DROP TRIGGER IF EXISTS trg_games_immutable_payout_commitment ON games;
|
||||
CREATE TRIGGER trg_games_immutable_payout_commitment
|
||||
BEFORE UPDATE ON games
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION reject_game_payout_commitment_mutation();
|
||||
|
||||
-- Refuse to weaken identity silently if historical duplicate obligations exist. Operators
|
||||
-- must reconcile them explicitly before this migration can complete.
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM payouts
|
||||
WHERE game_id IS NOT NULL
|
||||
GROUP BY game_id HAVING COUNT(*) > 1
|
||||
) THEN
|
||||
RAISE EXCEPTION 'Cannot enforce one payout per game: duplicate game_id obligations exist';
|
||||
END IF;
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM payouts
|
||||
WHERE match_id IS NOT NULL
|
||||
GROUP BY match_id HAVING COUNT(*) > 1
|
||||
) THEN
|
||||
RAISE EXCEPTION 'Cannot enforce one payout per match: duplicate match_id obligations exist';
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
-- Status changes (including failed/needs_review) never release the identity. A possibly
|
||||
-- broadcast payout must not permit a replacement row for the same game or match.
|
||||
DROP INDEX IF EXISTS idx_payouts_one_per_game;
|
||||
CREATE UNIQUE INDEX idx_payouts_one_per_game
|
||||
ON payouts(game_id)
|
||||
WHERE game_id IS NOT NULL;
|
||||
|
||||
DROP INDEX IF EXISTS idx_payouts_one_per_match;
|
||||
CREATE UNIQUE INDEX idx_payouts_one_per_match
|
||||
ON payouts(match_id)
|
||||
WHERE match_id IS NOT NULL;
|
||||
@@ -0,0 +1,243 @@
|
||||
-- Durable match payout terms.
|
||||
--
|
||||
-- A crypto match consumes escrow only after these fields are written in the same transaction.
|
||||
-- They are an immutable acceptance snapshot: later configuration changes may stop new matches
|
||||
-- or pause dispatch, but cannot erase or manufacture a liability for an already accepted match.
|
||||
|
||||
ALTER TABLE matches
|
||||
ADD COLUMN IF NOT EXISTS payout_liability_amount_atomic BIGINT,
|
||||
ADD COLUMN IF NOT EXISTS payout_liability_cap_atomic BIGINT,
|
||||
ADD COLUMN IF NOT EXISTS payout_liability_terms JSONB,
|
||||
ADD COLUMN IF NOT EXISTS payout_liability_accepted_at TIMESTAMPTZ;
|
||||
|
||||
-- Paid ticket lots preserve the accepted atomic backing for every future crypto entry. Fungible
|
||||
-- user.race_entries remains the UI balance, but only a ticket with a funded lot can enter a crypto
|
||||
-- payout match; legacy/admin-granted tickets remain usable only outside that liability path.
|
||||
CREATE TABLE IF NOT EXISTS race_entry_lots (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
payment_id BIGINT NOT NULL REFERENCES payments(id) ON DELETE RESTRICT,
|
||||
unit_value_atomic BIGINT NOT NULL CHECK (unit_value_atomic > 0),
|
||||
original_entries INT NOT NULL CHECK (original_entries > 0),
|
||||
remaining_entries INT NOT NULL CONSTRAINT race_entry_lots_remaining_within_original CHECK (
|
||||
remaining_entries >= 0 AND remaining_entries <= original_entries
|
||||
),
|
||||
product_id VARCHAR(100),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
UNIQUE (payment_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_race_entry_lots_user_available
|
||||
ON race_entry_lots (user_id, created_at, id)
|
||||
WHERE remaining_entries > 0;
|
||||
|
||||
-- The backing identity and accepted economics of a lot are append-only. Redemption/refund
|
||||
-- workflows may only reduce remaining_entries (and later migrations may add terminal markers).
|
||||
CREATE OR REPLACE FUNCTION reject_race_entry_lot_backing_mutation()
|
||||
RETURNS TRIGGER AS $$
|
||||
BEGIN
|
||||
IF NEW.user_id IS DISTINCT FROM OLD.user_id
|
||||
OR NEW.payment_id IS DISTINCT FROM OLD.payment_id
|
||||
OR NEW.unit_value_atomic IS DISTINCT FROM OLD.unit_value_atomic
|
||||
OR NEW.original_entries IS DISTINCT FROM OLD.original_entries
|
||||
OR NEW.product_id IS DISTINCT FROM OLD.product_id
|
||||
OR NEW.created_at IS DISTINCT FROM OLD.created_at
|
||||
THEN
|
||||
RAISE EXCEPTION 'race entry lot backing is immutable for lot %', OLD.id
|
||||
USING ERRCODE = '23514';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
DROP TRIGGER IF EXISTS trg_race_entry_lot_immutable_backing ON race_entry_lots;
|
||||
CREATE TRIGGER trg_race_entry_lot_immutable_backing
|
||||
BEFORE UPDATE ON race_entry_lots
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION reject_race_entry_lot_backing_mutation();
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint
|
||||
WHERE conname = 'race_entry_lots_remaining_within_original'
|
||||
) THEN
|
||||
ALTER TABLE race_entry_lots
|
||||
ADD CONSTRAINT race_entry_lots_remaining_within_original
|
||||
CHECK (remaining_entries >= 0 AND remaining_entries <= original_entries) NOT VALID;
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
-- One durable queue row is the idempotency anchor for one escrow hold/refund. `consumed` is a
|
||||
-- terminal successful-start state; stale queue cleanup must never treat it as refundable merely
|
||||
-- because time passed. The exact held amount survives config changes and concurrent re-queues.
|
||||
ALTER TABLE match_queue_entries
|
||||
ADD COLUMN IF NOT EXISTS escrow_amount BIGINT NOT NULL DEFAULT 0,
|
||||
ADD COLUMN IF NOT EXISTS escrow_value_atomic BIGINT NOT NULL DEFAULT 0,
|
||||
ADD COLUMN IF NOT EXISTS race_entry_lot_id BIGINT
|
||||
REFERENCES race_entry_lots(id) ON DELETE RESTRICT,
|
||||
ADD COLUMN IF NOT EXISTS consumed_at TIMESTAMPTZ;
|
||||
|
||||
ALTER TABLE match_queue_entries
|
||||
DROP CONSTRAINT IF EXISTS match_queue_entries_status_check;
|
||||
ALTER TABLE match_queue_entries
|
||||
ADD CONSTRAINT match_queue_entries_status_check
|
||||
CHECK (status IN ('queued', 'matched', 'consumed', 'cancelled')) NOT VALID;
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint
|
||||
WHERE conname = 'match_queue_entries_escrow_nonnegative'
|
||||
) THEN
|
||||
ALTER TABLE match_queue_entries
|
||||
ADD CONSTRAINT match_queue_entries_escrow_nonnegative
|
||||
CHECK (escrow_amount >= 0 AND escrow_value_atomic >= 0) NOT VALID;
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint
|
||||
WHERE conname = 'match_queue_committed_escrow_complete'
|
||||
) THEN
|
||||
ALTER TABLE match_queue_entries
|
||||
ADD CONSTRAINT match_queue_committed_escrow_complete CHECK (
|
||||
status NOT IN ('matched', 'consumed')
|
||||
OR economy = 'free'
|
||||
OR (economy = 'credits_prestige' AND escrow_amount > 0)
|
||||
OR (
|
||||
economy = 'crypto_race'
|
||||
AND escrow_amount = 1
|
||||
AND escrow_value_atomic > 0
|
||||
AND race_entry_lot_id IS NOT NULL
|
||||
)
|
||||
) NOT VALID;
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
CREATE OR REPLACE FUNCTION reject_committed_match_queue_escrow_mutation()
|
||||
RETURNS TRIGGER AS $$
|
||||
BEGIN
|
||||
IF OLD.status IN ('matched', 'consumed', 'cancelled') AND (
|
||||
NEW.user_id IS DISTINCT FROM OLD.user_id
|
||||
OR NEW.economy IS DISTINCT FROM OLD.economy
|
||||
OR NEW.escrow_amount IS DISTINCT FROM OLD.escrow_amount
|
||||
OR NEW.escrow_value_atomic IS DISTINCT FROM OLD.escrow_value_atomic
|
||||
OR NEW.race_entry_lot_id IS DISTINCT FROM OLD.race_entry_lot_id
|
||||
) THEN
|
||||
RAISE EXCEPTION 'committed queue escrow is immutable for queue entry %', OLD.id
|
||||
USING ERRCODE = '23514';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
DROP TRIGGER IF EXISTS trg_match_queue_immutable_committed_escrow ON match_queue_entries;
|
||||
CREATE TRIGGER trg_match_queue_immutable_committed_escrow
|
||||
BEFORE UPDATE ON match_queue_entries
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION reject_committed_match_queue_escrow_mutation();
|
||||
|
||||
ALTER TABLE match_entrants
|
||||
ADD COLUMN IF NOT EXISTS queue_entry_id BIGINT
|
||||
REFERENCES match_queue_entries(id) ON DELETE SET NULL,
|
||||
ADD COLUMN IF NOT EXISTS entry_refunded_at TIMESTAMPTZ;
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_match_entrants_queue_entry
|
||||
ON match_entrants (queue_entry_id)
|
||||
WHERE queue_entry_id IS NOT NULL;
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint
|
||||
WHERE conname = 'matches_payout_liability_amount_nonnegative'
|
||||
) THEN
|
||||
ALTER TABLE matches
|
||||
ADD CONSTRAINT matches_payout_liability_amount_nonnegative
|
||||
CHECK (payout_liability_amount_atomic IS NULL OR payout_liability_amount_atomic >= 0)
|
||||
NOT VALID;
|
||||
END IF;
|
||||
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint
|
||||
WHERE conname = 'matches_payout_liability_cap_positive'
|
||||
) THEN
|
||||
ALTER TABLE matches
|
||||
ADD CONSTRAINT matches_payout_liability_cap_positive
|
||||
CHECK (payout_liability_cap_atomic IS NULL OR payout_liability_cap_atomic > 0)
|
||||
NOT VALID;
|
||||
END IF;
|
||||
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint
|
||||
WHERE conname = 'matches_payout_liability_complete'
|
||||
) THEN
|
||||
ALTER TABLE matches
|
||||
ADD CONSTRAINT matches_payout_liability_complete
|
||||
CHECK (
|
||||
payout_liability_accepted_at IS NULL
|
||||
OR (
|
||||
economy = 'crypto_race'
|
||||
AND payout_liability_amount_atomic IS NOT NULL
|
||||
AND payout_liability_amount_atomic > 0
|
||||
AND payout_liability_cap_atomic IS NOT NULL
|
||||
AND payout_liability_amount_atomic <= payout_liability_cap_atomic
|
||||
AND payout_liability_terms IS NOT NULL
|
||||
)
|
||||
) NOT VALID;
|
||||
END IF;
|
||||
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint
|
||||
WHERE conname = 'matches_payout_liability_economics_consistent'
|
||||
) THEN
|
||||
ALTER TABLE matches
|
||||
ADD CONSTRAINT matches_payout_liability_economics_consistent
|
||||
CHECK (
|
||||
payout_liability_accepted_at IS NULL
|
||||
OR (
|
||||
entry_fee_atomic > 0
|
||||
AND pot_atomic > 0
|
||||
AND house_fee_atomic >= 0
|
||||
AND house_fee_atomic < pot_atomic
|
||||
AND payout_liability_amount_atomic = pot_atomic - house_fee_atomic
|
||||
)
|
||||
) NOT VALID;
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
CREATE OR REPLACE FUNCTION reject_match_payout_liability_mutation()
|
||||
RETURNS TRIGGER AS $$
|
||||
BEGIN
|
||||
IF OLD.payout_liability_accepted_at IS NOT NULL AND (
|
||||
NEW.payout_liability_amount_atomic IS DISTINCT FROM OLD.payout_liability_amount_atomic
|
||||
OR NEW.payout_liability_cap_atomic IS DISTINCT FROM OLD.payout_liability_cap_atomic
|
||||
OR NEW.payout_liability_terms IS DISTINCT FROM OLD.payout_liability_terms
|
||||
OR NEW.payout_liability_accepted_at IS DISTINCT FROM OLD.payout_liability_accepted_at
|
||||
OR NEW.entry_fee_atomic IS DISTINCT FROM OLD.entry_fee_atomic
|
||||
OR NEW.pot_atomic IS DISTINCT FROM OLD.pot_atomic
|
||||
OR NEW.house_fee_atomic IS DISTINCT FROM OLD.house_fee_atomic
|
||||
OR NEW.house_fee_percent IS DISTINCT FROM OLD.house_fee_percent
|
||||
) THEN
|
||||
RAISE EXCEPTION 'accepted match payout liability is immutable for match %', OLD.id
|
||||
USING ERRCODE = '23514';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
DROP TRIGGER IF EXISTS trg_matches_immutable_payout_liability ON matches;
|
||||
CREATE TRIGGER trg_matches_immutable_payout_liability
|
||||
BEFORE UPDATE ON matches
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION reject_match_payout_liability_mutation();
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_matches_unsettled_payout_liability
|
||||
ON matches (ended_at, id)
|
||||
WHERE economy = 'crypto_race'
|
||||
AND status = 'finished'
|
||||
AND winner_user_id IS NOT NULL
|
||||
AND payout_liability_accepted_at IS NOT NULL;
|
||||
@@ -0,0 +1,19 @@
|
||||
-- Migration 034: versioned, all-depth solo fairness manifest
|
||||
--
|
||||
-- `layout_fingerprint` remains the legacy level-one alias. New games persist one
|
||||
-- generator/fingerprint-versioned entry for every depth advertised at game creation.
|
||||
ALTER TABLE games
|
||||
ADD COLUMN IF NOT EXISTS generator_version VARCHAR(64),
|
||||
ADD COLUMN IF NOT EXISTS layout_fingerprints JSONB;
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint WHERE conname = 'games_layout_fingerprints_array_check'
|
||||
) THEN
|
||||
ALTER TABLE games
|
||||
ADD CONSTRAINT games_layout_fingerprints_array_check
|
||||
CHECK (layout_fingerprints IS NULL OR jsonb_typeof(layout_fingerprints) = 'array')
|
||||
NOT VALID;
|
||||
END IF;
|
||||
END $$;
|
||||
@@ -0,0 +1,262 @@
|
||||
-- Durable payment entitlements, entry-consumption evidence, and payment-bound fairness.
|
||||
--
|
||||
-- A confirmed invoice must never become claimable again after it has been converted into
|
||||
-- another entitlement. Product refunds need an exact, payment-scoped grant record so every
|
||||
-- reversible benefit can be locked and revoked before any wallet transfer is attempted.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS payment_entitlement_grants (
|
||||
payment_id INTEGER PRIMARY KEY REFERENCES payments(id) ON DELETE RESTRICT,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
|
||||
source VARCHAR(40) NOT NULL,
|
||||
credits_granted BIGINT NOT NULL DEFAULT 0 CHECK (credits_granted >= 0),
|
||||
purchase_progress_granted BIGINT NOT NULL DEFAULT 0 CHECK (purchase_progress_granted >= 0),
|
||||
race_entries_granted INTEGER NOT NULL DEFAULT 0 CHECK (race_entries_granted >= 0),
|
||||
packs_granted JSONB NOT NULL DEFAULT '[]'::jsonb,
|
||||
premium_level_granted VARCHAR(32),
|
||||
premium_level_previous VARCHAR(32),
|
||||
status VARCHAR(20) NOT NULL DEFAULT 'active'
|
||||
CHECK (status IN ('active', 'reversed', 'needs_review')),
|
||||
credits_reversed BIGINT NOT NULL DEFAULT 0 CHECK (credits_reversed >= 0),
|
||||
purchase_progress_reversed BIGINT NOT NULL DEFAULT 0
|
||||
CHECK (purchase_progress_reversed >= 0),
|
||||
race_entries_reversed INTEGER NOT NULL DEFAULT 0 CHECK (race_entries_reversed >= 0),
|
||||
packs_reversed JSONB NOT NULL DEFAULT '[]'::jsonb,
|
||||
reversal_reason TEXT,
|
||||
reversed_at TIMESTAMPTZ,
|
||||
needs_review_at TIMESTAMPTZ,
|
||||
metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
CONSTRAINT payment_entitlement_packs_array
|
||||
CHECK (jsonb_typeof(packs_granted) = 'array' AND jsonb_typeof(packs_reversed) = 'array'),
|
||||
CONSTRAINT payment_entitlement_reversal_bounds
|
||||
CHECK (credits_reversed <= credits_granted
|
||||
AND purchase_progress_reversed <= purchase_progress_granted
|
||||
AND race_entries_reversed <= race_entries_granted),
|
||||
CONSTRAINT payment_entitlement_state_shape CHECK (
|
||||
(status = 'active' AND reversed_at IS NULL)
|
||||
OR (status = 'reversed' AND reversed_at IS NOT NULL)
|
||||
OR (status = 'needs_review' AND needs_review_at IS NOT NULL)
|
||||
)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_payment_entitlement_user
|
||||
ON payment_entitlement_grants(user_id, created_at DESC);
|
||||
|
||||
-- Tie fungible ledgers to their invoice. Partial indexes are final idempotency backstops in
|
||||
-- addition to the payment/refund row locks used by the application.
|
||||
ALTER TABLE credit_transactions
|
||||
ADD COLUMN IF NOT EXISTS payment_id INTEGER REFERENCES payments(id) ON DELETE SET NULL;
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_credit_tx_payment_grant_once
|
||||
ON credit_transactions(payment_id)
|
||||
WHERE payment_id IS NOT NULL AND transaction_type IN ('purchase', 'recovery');
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_credit_tx_payment_refund_once
|
||||
ON credit_transactions(payment_id)
|
||||
WHERE payment_id IS NOT NULL AND transaction_type = 'refund';
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_race_entry_tx_payment_refund_once
|
||||
ON race_entry_transactions(payment_id)
|
||||
WHERE payment_id IS NOT NULL AND reason = 'refund';
|
||||
|
||||
ALTER TABLE race_entry_lots
|
||||
ADD COLUMN IF NOT EXISTS refunded_at TIMESTAMPTZ;
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint WHERE conname = 'race_entry_lots_refund_shape'
|
||||
) THEN
|
||||
ALTER TABLE race_entry_lots
|
||||
ADD CONSTRAINT race_entry_lots_refund_shape
|
||||
CHECK (refunded_at IS NULL OR remaining_entries = 0) NOT VALID;
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
ALTER TABLE payment_refunds
|
||||
ADD COLUMN IF NOT EXISTS purchase_progress_deducted BIGINT NOT NULL DEFAULT 0,
|
||||
ADD COLUMN IF NOT EXISTS race_entries_deducted INTEGER NOT NULL DEFAULT 0,
|
||||
ADD COLUMN IF NOT EXISTS packs_revoked JSONB NOT NULL DEFAULT '[]'::jsonb,
|
||||
ADD COLUMN IF NOT EXISTS premium_level_restored VARCHAR(32),
|
||||
ADD COLUMN IF NOT EXISTS entitlement_grant_payment_id INTEGER
|
||||
REFERENCES payment_entitlement_grants(payment_id) ON DELETE RESTRICT;
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint WHERE conname = 'payment_refunds_progress_nonnegative'
|
||||
) THEN
|
||||
ALTER TABLE payment_refunds
|
||||
ADD CONSTRAINT payment_refunds_progress_nonnegative
|
||||
CHECK (purchase_progress_deducted >= 0) NOT VALID;
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
-- A game mode label is not evidence that value was taken. Startup recovery may refund only the
|
||||
-- exact entry snapshot committed in the same transaction that debited/linked the entry.
|
||||
ALTER TABLE games
|
||||
ADD COLUMN IF NOT EXISTS entry_consumed_at TIMESTAMPTZ,
|
||||
ADD COLUMN IF NOT EXISTS entry_credits_spent INTEGER;
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint WHERE conname = 'games_entry_consumption_shape'
|
||||
) THEN
|
||||
ALTER TABLE games
|
||||
ADD CONSTRAINT games_entry_consumption_shape CHECK (
|
||||
entry_credits_spent IS NULL OR entry_credits_spent > 0
|
||||
) NOT VALID;
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
-- Bind the secret half of a v2 fairness offer to the invoice before an address is shown. The
|
||||
-- server seed remains private until the linked game ends; only its hash is sent to the client.
|
||||
ALTER TABLE payments
|
||||
ADD COLUMN IF NOT EXISTS fairness_proof_version SMALLINT,
|
||||
ADD COLUMN IF NOT EXISTS fairness_offer_id VARCHAR(64),
|
||||
ADD COLUMN IF NOT EXISTS fairness_offer_issued_at TIMESTAMPTZ,
|
||||
ADD COLUMN IF NOT EXISTS fairness_commitment CHAR(64),
|
||||
ADD COLUMN IF NOT EXISTS fairness_server_seed CHAR(64),
|
||||
ADD COLUMN IF NOT EXISTS fairness_client_seed VARCHAR(64),
|
||||
ADD COLUMN IF NOT EXISTS fairness_bound_at TIMESTAMPTZ,
|
||||
ADD COLUMN IF NOT EXISTS fairness_consumed_at TIMESTAMPTZ;
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_payments_fairness_offer_once
|
||||
ON payments(fairness_offer_id)
|
||||
WHERE fairness_offer_id IS NOT NULL;
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint WHERE conname = 'payments_fairness_binding_complete'
|
||||
) THEN
|
||||
ALTER TABLE payments
|
||||
ADD CONSTRAINT payments_fairness_binding_complete CHECK (
|
||||
fairness_bound_at IS NULL OR (
|
||||
payment_type = 'single_game'
|
||||
AND fairness_proof_version = 2
|
||||
AND fairness_offer_id IS NOT NULL
|
||||
AND fairness_offer_issued_at IS NOT NULL
|
||||
AND fairness_commitment ~ '^[0-9a-f]{64}$'
|
||||
AND fairness_server_seed ~ '^[0-9a-f]{64}$'
|
||||
AND fairness_client_seed IS NOT NULL
|
||||
)
|
||||
) NOT VALID;
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
CREATE OR REPLACE FUNCTION reject_payment_fairness_binding_mutation()
|
||||
RETURNS TRIGGER AS $$
|
||||
BEGIN
|
||||
IF OLD.fairness_bound_at IS NOT NULL AND (
|
||||
NEW.user_id IS DISTINCT FROM OLD.user_id
|
||||
OR NEW.payment_type IS DISTINCT FROM OLD.payment_type
|
||||
OR NEW.expected_amount IS DISTINCT FROM OLD.expected_amount
|
||||
OR NEW.subaddress IS DISTINCT FROM OLD.subaddress
|
||||
OR NEW.address_index IS DISTINCT FROM OLD.address_index
|
||||
OR NEW.fairness_proof_version IS DISTINCT FROM OLD.fairness_proof_version
|
||||
OR NEW.fairness_offer_id IS DISTINCT FROM OLD.fairness_offer_id
|
||||
OR NEW.fairness_offer_issued_at IS DISTINCT FROM OLD.fairness_offer_issued_at
|
||||
OR NEW.fairness_commitment IS DISTINCT FROM OLD.fairness_commitment
|
||||
OR NEW.fairness_server_seed IS DISTINCT FROM OLD.fairness_server_seed
|
||||
OR NEW.fairness_client_seed IS DISTINCT FROM OLD.fairness_client_seed
|
||||
OR NEW.fairness_bound_at IS DISTINCT FROM OLD.fairness_bound_at
|
||||
OR (OLD.fairness_consumed_at IS NOT NULL
|
||||
AND NEW.fairness_consumed_at IS DISTINCT FROM OLD.fairness_consumed_at)
|
||||
) THEN
|
||||
RAISE EXCEPTION 'payment fairness binding is immutable for payment %', OLD.id
|
||||
USING ERRCODE = '23514';
|
||||
END IF;
|
||||
IF OLD.fairness_bound_at IS NULL AND NEW.fairness_bound_at IS NOT NULL AND (
|
||||
NEW.user_id IS DISTINCT FROM OLD.user_id
|
||||
OR NEW.payment_type IS DISTINCT FROM OLD.payment_type
|
||||
OR NEW.expected_amount IS DISTINCT FROM OLD.expected_amount
|
||||
OR NEW.subaddress IS DISTINCT FROM OLD.subaddress
|
||||
OR NEW.address_index IS DISTINCT FROM OLD.address_index
|
||||
) THEN
|
||||
RAISE EXCEPTION 'payment identity cannot change while binding fairness proof for payment %', OLD.id
|
||||
USING ERRCODE = '23514';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
DROP TRIGGER IF EXISTS trg_payments_immutable_fairness_binding ON payments;
|
||||
CREATE TRIGGER trg_payments_immutable_fairness_binding
|
||||
BEFORE UPDATE ON payments
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION reject_payment_fairness_binding_mutation();
|
||||
|
||||
-- Runtime fallback queries still recognize the legacy reason key, but backfill it into the
|
||||
-- canonical marker and ledger FK so upgraded installations immediately get the same invariant.
|
||||
WITH recovered AS (
|
||||
SELECT DISTINCT ON ((substring(ct.reason FROM 'single_game_recovered:([0-9]+)'))::integer)
|
||||
(substring(ct.reason FROM 'single_game_recovered:([0-9]+)'))::integer AS payment_id,
|
||||
ct.user_id,
|
||||
GREATEST(ct.amount, 0)::bigint AS credits_granted,
|
||||
ct.id AS credit_transaction_id
|
||||
FROM credit_transactions ct
|
||||
WHERE ct.reason ~ '^single_game_recovered:[0-9]+$'
|
||||
ORDER BY (substring(ct.reason FROM 'single_game_recovered:([0-9]+)'))::integer, ct.id
|
||||
)
|
||||
INSERT INTO payment_entitlement_grants (
|
||||
payment_id, user_id, source, credits_granted, metadata
|
||||
)
|
||||
SELECT r.payment_id, r.user_id, 'single_game_recovery', r.credits_granted,
|
||||
jsonb_build_object('legacyBackfill', true, 'creditTransactionId', r.credit_transaction_id)
|
||||
FROM recovered r
|
||||
JOIN payments p ON p.id = r.payment_id AND p.user_id = r.user_id
|
||||
ON CONFLICT (payment_id) DO NOTHING;
|
||||
|
||||
-- Some legacy deployments may already contain duplicate recovery ledger rows from a race
|
||||
-- between instances. Attach only the earliest row to the invoice; the unique payment ledger
|
||||
-- index then remains a backstop instead of making this upgrade itself fail.
|
||||
WITH canonical_recovery_ledger AS (
|
||||
SELECT DISTINCT ON ((substring(ct.reason FROM 'single_game_recovered:([0-9]+)'))::integer)
|
||||
ct.id,
|
||||
(substring(ct.reason FROM 'single_game_recovered:([0-9]+)'))::integer AS payment_id
|
||||
FROM credit_transactions ct
|
||||
JOIN payments p
|
||||
ON p.id = (substring(ct.reason FROM 'single_game_recovered:([0-9]+)'))::integer
|
||||
AND p.user_id = ct.user_id
|
||||
WHERE ct.payment_id IS NULL
|
||||
AND ct.reason ~ '^single_game_recovered:[0-9]+$'
|
||||
ORDER BY (substring(ct.reason FROM 'single_game_recovered:([0-9]+)'))::integer, ct.id
|
||||
)
|
||||
UPDATE credit_transactions ct
|
||||
SET payment_id = canonical.payment_id
|
||||
FROM canonical_recovery_ledger canonical
|
||||
WHERE ct.id = canonical.id;
|
||||
|
||||
-- Historical confirmed products did not have an entitlement marker. Snapshot the durable grant
|
||||
-- JSON conservatively; pack revocation still requires payment-specific entitlement provenance,
|
||||
-- otherwise the refund service sends the row to manual review.
|
||||
INSERT INTO payment_entitlement_grants (
|
||||
payment_id, user_id, source, credits_granted, purchase_progress_granted,
|
||||
race_entries_granted, packs_granted, premium_level_granted, metadata
|
||||
)
|
||||
SELECT
|
||||
p.id,
|
||||
p.user_id,
|
||||
'legacy_product_backfill',
|
||||
CASE
|
||||
WHEN COALESCE(p.product_grants->>'credits', '') ~ '^[0-9]+$'
|
||||
THEN (p.product_grants->>'credits')::bigint
|
||||
ELSE GREATEST(COALESCE(p.credits_purchased, 0), 0)::bigint
|
||||
END,
|
||||
GREATEST(COALESCE(p.credits_purchased, 0), 0)::bigint,
|
||||
CASE
|
||||
WHEN COALESCE(p.product_grants->>'raceEntries', '') ~ '^[0-9]+$'
|
||||
THEN (p.product_grants->>'raceEntries')::integer
|
||||
ELSE 0
|
||||
END,
|
||||
CASE WHEN jsonb_typeof(p.product_grants->'packs') = 'array'
|
||||
THEN p.product_grants->'packs' ELSE '[]'::jsonb END,
|
||||
NULLIF(p.product_grants->>'premiumLevel', ''),
|
||||
jsonb_build_object('legacyBackfill', true)
|
||||
FROM payments p
|
||||
WHERE p.status = 'confirmed'
|
||||
AND p.payment_type IN ('credits_package', 'cosmetic_pack')
|
||||
AND p.user_id IS NOT NULL
|
||||
ON CONFLICT (payment_id) DO NOTHING;
|
||||
@@ -0,0 +1,36 @@
|
||||
-- Bind Smirk authentication nonces to a stable authenticated user, not merely to the
|
||||
-- public Socket.IO id that Tavern/match state broadcasts to other players.
|
||||
|
||||
ALTER TABLE smirk_challenges
|
||||
ADD COLUMN IF NOT EXISTS user_id INTEGER REFERENCES users(id) ON DELETE CASCADE;
|
||||
|
||||
-- Challenges are five-minute ephemeral nonces. Invalidate any nonce issued by the old,
|
||||
-- socket-only application before making the stable binding mandatory; clients simply retry.
|
||||
DELETE FROM smirk_challenges WHERE user_id IS NULL;
|
||||
|
||||
ALTER TABLE smirk_challenges
|
||||
ALTER COLUMN user_id SET NOT NULL;
|
||||
|
||||
-- Socket ownership is an authentication relation throughout the paid-play code. Refuse to
|
||||
-- continue an upgrade with ambiguous historical rows, then make that invariant structural.
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (
|
||||
SELECT socket_id
|
||||
FROM users
|
||||
WHERE socket_id IS NOT NULL
|
||||
GROUP BY socket_id
|
||||
HAVING COUNT(*) > 1
|
||||
) THEN
|
||||
RAISE EXCEPTION 'cannot enforce unique socket ownership: duplicate users.socket_id rows exist'
|
||||
USING ERRCODE = '23505';
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_users_socket_id_unique_nonnull
|
||||
ON users (socket_id)
|
||||
WHERE socket_id IS NOT NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_smirk_challenges_user_active
|
||||
ON smirk_challenges (user_id, expires_at)
|
||||
WHERE used = FALSE;
|
||||
@@ -0,0 +1,134 @@
|
||||
-- Incoming-payment evidence must be unique per chain output, not per transaction or address.
|
||||
-- One Monero transaction may contain several incoming outputs (including several for the same
|
||||
-- subaddress), and one invoice may be completed by several top-up transactions.
|
||||
|
||||
ALTER TABLE payments
|
||||
ADD COLUMN IF NOT EXISTS provider_id VARCHAR(40) NOT NULL DEFAULT 'native-monero',
|
||||
ADD COLUMN IF NOT EXISTS provider_invoice_id VARCHAR(160),
|
||||
ADD COLUMN IF NOT EXISTS confirmation_evidence_at TIMESTAMPTZ,
|
||||
ADD COLUMN IF NOT EXISTS late_receipt_checked_at TIMESTAMPTZ;
|
||||
|
||||
-- Migration 008 assumed one incoming transaction == one invoice. Keep tx_hash as display/search
|
||||
-- evidence only. Legacy data also contains expired/retried rows that intentionally reused an
|
||||
-- address, so neither transaction hashes nor invoice destinations are unique payment identities.
|
||||
DROP INDEX IF EXISTS idx_payments_tx_hash_unique;
|
||||
DROP INDEX IF EXISTS idx_payments_tx_hash_output_unique;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS payment_receipts (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
payment_id INTEGER NOT NULL REFERENCES payments(id) ON DELETE RESTRICT,
|
||||
provider_id VARCHAR(40) NOT NULL,
|
||||
evidence_type VARCHAR(24) NOT NULL
|
||||
CHECK (evidence_type IN ('chain_output', 'provider_invoice')),
|
||||
evidence_id VARCHAR(160) NOT NULL,
|
||||
tx_hash VARCHAR(64),
|
||||
output_id VARCHAR(80),
|
||||
address_index INTEGER,
|
||||
amount BIGINT NOT NULL CHECK (amount > 0),
|
||||
confirmed BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
observed_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
CONSTRAINT payment_receipt_shape CHECK (
|
||||
(evidence_type = 'chain_output'
|
||||
AND provider_id = 'native-monero'
|
||||
AND tx_hash ~ '^[0-9a-f]{64}$'
|
||||
AND (output_id ~ '^[0-9a-f]{64}$' OR output_id ~ '^global:(0|[1-9][0-9]*)$')
|
||||
AND evidence_id = tx_hash || ':' || output_id
|
||||
AND address_index IS NOT NULL AND address_index >= 0)
|
||||
OR
|
||||
(evidence_type = 'provider_invoice'
|
||||
AND provider_id <> 'native-monero'
|
||||
AND tx_hash IS NULL
|
||||
AND output_id IS NULL
|
||||
AND address_index IS NULL
|
||||
AND LENGTH(evidence_id) > 0)
|
||||
)
|
||||
);
|
||||
|
||||
-- Output/invoice evidence is globally consumable once for its provider. In particular, tx_hash
|
||||
-- and address_index are deliberately absent: sibling outputs can share both values.
|
||||
DROP INDEX IF EXISTS idx_payment_receipts_chain_output_once;
|
||||
DROP INDEX IF EXISTS idx_payment_receipts_provider_invoice_once;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_payment_receipts_evidence_once
|
||||
ON payment_receipts(provider_id, evidence_id);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_payment_receipts_payment
|
||||
ON payment_receipts(payment_id, observed_at);
|
||||
|
||||
-- Late receipts are intentionally not entitlements. The bounded reconciliation worker records
|
||||
-- their durable output evidence here for an operator to refund or adjudicate manually, while the
|
||||
-- underlying payment remains expired.
|
||||
CREATE TABLE IF NOT EXISTS payment_late_reviews (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
payment_id INTEGER NOT NULL UNIQUE REFERENCES payments(id) ON DELETE RESTRICT,
|
||||
provider_id VARCHAR(40) NOT NULL,
|
||||
status VARCHAR(20) NOT NULL DEFAULT 'needs_review'
|
||||
CHECK (status IN ('needs_review', 'resolved', 'ignored')),
|
||||
reason VARCHAR(40) NOT NULL DEFAULT 'late_confirmed_receipt'
|
||||
CHECK (reason IN ('late_confirmed_receipt')),
|
||||
observed_amount BIGINT NOT NULL CHECK (observed_amount > 0),
|
||||
expected_amount BIGINT NOT NULL CHECK (expected_amount > 0),
|
||||
receipt_count INTEGER NOT NULL CHECK (receipt_count > 0),
|
||||
metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
first_observed_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
last_observed_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
resolved_at TIMESTAMPTZ
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_payment_late_reviews_status
|
||||
ON payment_late_reviews(status, last_observed_at);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_payments_late_receipt_scan
|
||||
ON payments(late_receipt_checked_at, expires_at)
|
||||
WHERE status IN ('pending', 'expired');
|
||||
|
||||
-- Forward-only guard. Existing confirmed legacy rows (including rows with NULL tx_hash or an
|
||||
-- old received_amount) remain readable because this trigger runs only on a new transition into
|
||||
-- confirmed. Every new confirmation must have exact durable evidence covering the invoice.
|
||||
CREATE OR REPLACE FUNCTION enforce_payment_confirmation_evidence()
|
||||
RETURNS TRIGGER AS $$
|
||||
DECLARE
|
||||
receipt_total BIGINT;
|
||||
receipt_count BIGINT;
|
||||
BEGIN
|
||||
IF TG_OP = 'INSERT' THEN
|
||||
IF NEW.status = 'confirmed' THEN
|
||||
RAISE EXCEPTION 'payment % must be inserted pending before receipt-backed confirmation', NEW.id
|
||||
USING ERRCODE = '23514';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
|
||||
IF NEW.status = 'confirmed' AND OLD.status IS DISTINCT FROM 'confirmed' THEN
|
||||
SELECT COALESCE(SUM(r.amount), 0), COUNT(*)
|
||||
INTO receipt_total, receipt_count
|
||||
FROM payment_receipts r
|
||||
WHERE r.payment_id = NEW.id
|
||||
AND r.provider_id = NEW.provider_id
|
||||
AND r.confirmed = TRUE
|
||||
AND (
|
||||
(NEW.provider_id = 'native-monero' AND r.evidence_type = 'chain_output')
|
||||
OR (NEW.provider_id <> 'native-monero' AND r.evidence_type = 'provider_invoice')
|
||||
);
|
||||
|
||||
IF receipt_count = 0 OR receipt_total < NEW.expected_amount THEN
|
||||
RAISE EXCEPTION 'payment % lacks confirmed receipt coverage (% / %)',
|
||||
NEW.id, receipt_total, NEW.expected_amount
|
||||
USING ERRCODE = '23514';
|
||||
END IF;
|
||||
IF NEW.received_amount IS NULL OR NEW.received_amount < NEW.expected_amount
|
||||
OR NEW.received_amount > receipt_total THEN
|
||||
RAISE EXCEPTION 'payment % received_amount is not supported by receipts', NEW.id
|
||||
USING ERRCODE = '23514';
|
||||
END IF;
|
||||
NEW.confirmation_evidence_at = COALESCE(NEW.confirmation_evidence_at, NOW());
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
DROP TRIGGER IF EXISTS trg_payments_require_confirmation_evidence ON payments;
|
||||
CREATE TRIGGER trg_payments_require_confirmation_evidence
|
||||
BEFORE INSERT OR UPDATE OF status ON payments
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION enforce_payment_confirmation_evidence();
|
||||
@@ -0,0 +1,181 @@
|
||||
-- Close economic-identity mutation gaps for databases that already applied migrations 032/035.
|
||||
-- Operational status, transaction evidence, retry counters, fees, and timestamps remain mutable;
|
||||
-- owners, promise amounts, linkage, and destinations do not.
|
||||
|
||||
CREATE OR REPLACE FUNCTION reject_game_payout_commitment_mutation()
|
||||
RETURNS TRIGGER AS $$
|
||||
BEGIN
|
||||
IF OLD.payout_committed_at IS NOT NULL AND (
|
||||
NEW.user_id IS DISTINCT FROM OLD.user_id
|
||||
OR NEW.payout_eligible IS DISTINCT FROM OLD.payout_eligible
|
||||
OR NEW.payout_terms IS DISTINCT FROM OLD.payout_terms
|
||||
OR NEW.payout_committed_at IS DISTINCT FROM OLD.payout_committed_at
|
||||
OR NEW.payout_escape_amount IS DISTINCT FROM OLD.payout_escape_amount
|
||||
OR NEW.payout_treasure_amount IS DISTINCT FROM OLD.payout_treasure_amount
|
||||
OR NEW.payout_escape_mult IS DISTINCT FROM OLD.payout_escape_mult
|
||||
OR NEW.payout_treasure_mult IS DISTINCT FROM OLD.payout_treasure_mult
|
||||
OR NEW.payout_address IS DISTINCT FROM OLD.payout_address
|
||||
OR NEW.game_mode IS DISTINCT FROM OLD.game_mode
|
||||
OR NEW.payment_id IS DISTINCT FROM OLD.payment_id
|
||||
) THEN
|
||||
RAISE EXCEPTION 'committed solo payout terms are immutable for game %', OLD.id
|
||||
USING ERRCODE = '23514';
|
||||
END IF;
|
||||
IF OLD.payout_committed_at IS NULL
|
||||
AND NEW.payout_committed_at IS NOT NULL
|
||||
AND NEW.user_id IS DISTINCT FROM OLD.user_id
|
||||
THEN
|
||||
RAISE EXCEPTION 'solo payout owner cannot change while committing game %', OLD.id
|
||||
USING ERRCODE = '23514';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
CREATE OR REPLACE FUNCTION reject_payment_fairness_binding_mutation()
|
||||
RETURNS TRIGGER AS $$
|
||||
DECLARE
|
||||
identity_locked BOOLEAN;
|
||||
BEGIN
|
||||
-- A receipt is authorization evidence even before the final status update. Once evidence
|
||||
-- exists (or the invoice has reached a terminal money state), its economic promise and
|
||||
-- provider/destination identity may no longer be rewritten. Operational settlement fields
|
||||
-- such as status, received_amount, confirmations, and refund timestamps remain mutable.
|
||||
identity_locked := OLD.fairness_bound_at IS NOT NULL
|
||||
OR OLD.status IN ('confirmed', 'refunded', 'expired')
|
||||
OR EXISTS (SELECT 1 FROM payment_receipts r WHERE r.payment_id = OLD.id);
|
||||
|
||||
IF identity_locked AND (
|
||||
NEW.user_id IS DISTINCT FROM OLD.user_id
|
||||
OR NEW.payment_type IS DISTINCT FROM OLD.payment_type
|
||||
OR NEW.expected_amount IS DISTINCT FROM OLD.expected_amount
|
||||
OR NEW.subaddress IS DISTINCT FROM OLD.subaddress
|
||||
OR NEW.address_index IS DISTINCT FROM OLD.address_index
|
||||
OR NEW.provider_id IS DISTINCT FROM OLD.provider_id
|
||||
OR NEW.provider_invoice_id IS DISTINCT FROM OLD.provider_invoice_id
|
||||
OR NEW.payment_mode IS DISTINCT FROM OLD.payment_mode
|
||||
OR NEW.credit_package_id IS DISTINCT FROM OLD.credit_package_id
|
||||
OR NEW.product_id IS DISTINCT FROM OLD.product_id
|
||||
OR NEW.product_grants IS DISTINCT FROM OLD.product_grants
|
||||
OR NEW.description IS DISTINCT FROM OLD.description
|
||||
OR NEW.expires_at IS DISTINCT FROM OLD.expires_at
|
||||
) THEN
|
||||
RAISE EXCEPTION 'payment economic identity is immutable for payment %', OLD.id
|
||||
USING ERRCODE = '23514';
|
||||
END IF;
|
||||
|
||||
IF OLD.fairness_bound_at IS NOT NULL AND (
|
||||
NEW.fairness_proof_version IS DISTINCT FROM OLD.fairness_proof_version
|
||||
OR NEW.fairness_offer_id IS DISTINCT FROM OLD.fairness_offer_id
|
||||
OR NEW.fairness_offer_issued_at IS DISTINCT FROM OLD.fairness_offer_issued_at
|
||||
OR NEW.fairness_commitment IS DISTINCT FROM OLD.fairness_commitment
|
||||
OR NEW.fairness_server_seed IS DISTINCT FROM OLD.fairness_server_seed
|
||||
OR NEW.fairness_client_seed IS DISTINCT FROM OLD.fairness_client_seed
|
||||
OR NEW.fairness_bound_at IS DISTINCT FROM OLD.fairness_bound_at
|
||||
OR (OLD.fairness_consumed_at IS NOT NULL
|
||||
AND NEW.fairness_consumed_at IS DISTINCT FROM OLD.fairness_consumed_at)
|
||||
) THEN
|
||||
RAISE EXCEPTION 'payment fairness binding is immutable for payment %', OLD.id
|
||||
USING ERRCODE = '23514';
|
||||
END IF;
|
||||
IF OLD.fairness_bound_at IS NULL AND NEW.fairness_bound_at IS NOT NULL AND (
|
||||
NEW.user_id IS DISTINCT FROM OLD.user_id
|
||||
OR NEW.payment_type IS DISTINCT FROM OLD.payment_type
|
||||
OR NEW.expected_amount IS DISTINCT FROM OLD.expected_amount
|
||||
OR NEW.subaddress IS DISTINCT FROM OLD.subaddress
|
||||
OR NEW.address_index IS DISTINCT FROM OLD.address_index
|
||||
OR NEW.provider_id IS DISTINCT FROM OLD.provider_id
|
||||
OR NEW.provider_invoice_id IS DISTINCT FROM OLD.provider_invoice_id
|
||||
OR NEW.payment_mode IS DISTINCT FROM OLD.payment_mode
|
||||
OR NEW.credit_package_id IS DISTINCT FROM OLD.credit_package_id
|
||||
OR NEW.product_id IS DISTINCT FROM OLD.product_id
|
||||
OR NEW.product_grants IS DISTINCT FROM OLD.product_grants
|
||||
OR NEW.description IS DISTINCT FROM OLD.description
|
||||
OR NEW.expires_at IS DISTINCT FROM OLD.expires_at
|
||||
) THEN
|
||||
RAISE EXCEPTION 'payment identity cannot change while binding fairness proof for payment %', OLD.id
|
||||
USING ERRCODE = '23514';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
-- Receipt evidence is an append-only authorization ledger. If an observation is later found to
|
||||
-- be wrong, add adjudication metadata elsewhere; never rewrite or erase the evidence that allowed
|
||||
-- an invoice to confirm.
|
||||
CREATE OR REPLACE FUNCTION reject_payment_receipt_mutation()
|
||||
RETURNS TRIGGER AS $$
|
||||
BEGIN
|
||||
RAISE EXCEPTION 'payment receipt evidence is append-only for receipt %', OLD.id
|
||||
USING ERRCODE = '23514';
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
DROP TRIGGER IF EXISTS trg_payment_receipts_append_only ON payment_receipts;
|
||||
CREATE TRIGGER trg_payment_receipts_append_only
|
||||
BEFORE UPDATE OR DELETE ON payment_receipts
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION reject_payment_receipt_mutation();
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint WHERE conname = 'payouts_no_address_review_shape'
|
||||
) THEN
|
||||
ALTER TABLE payouts
|
||||
ADD CONSTRAINT payouts_no_address_review_shape CHECK (
|
||||
payout_address <> 'PENDING_NO_ADDRESS'
|
||||
OR (
|
||||
status = 'needs_review'
|
||||
AND reason IN ('match_winner_no_address', 'solo_winner_no_address')
|
||||
AND tx_hash IS NULL
|
||||
)
|
||||
) NOT VALID;
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
CREATE OR REPLACE FUNCTION reject_payout_obligation_mutation()
|
||||
RETURNS TRIGGER AS $$
|
||||
DECLARE
|
||||
allowed_address_claim BOOLEAN := FALSE;
|
||||
BEGIN
|
||||
IF NEW.user_id IS DISTINCT FROM OLD.user_id
|
||||
OR NEW.game_id IS DISTINCT FROM OLD.game_id
|
||||
OR NEW.match_id IS DISTINCT FROM OLD.match_id
|
||||
OR NEW.amount IS DISTINCT FROM OLD.amount
|
||||
OR NEW.multiplier IS DISTINCT FROM OLD.multiplier
|
||||
OR NEW.reason IS DISTINCT FROM OLD.reason
|
||||
THEN
|
||||
RAISE EXCEPTION 'payout economic identity is immutable for payout %', OLD.id
|
||||
USING ERRCODE = '23514';
|
||||
END IF;
|
||||
|
||||
IF NEW.payout_address IS DISTINCT FROM OLD.payout_address THEN
|
||||
allowed_address_claim :=
|
||||
OLD.payout_address = 'PENDING_NO_ADDRESS'
|
||||
AND OLD.status = 'needs_review'
|
||||
AND OLD.reason IN ('match_winner_no_address', 'solo_winner_no_address')
|
||||
AND OLD.tx_hash IS NULL
|
||||
AND NEW.status = 'pending'
|
||||
AND NEW.tx_hash IS NULL
|
||||
AND BTRIM(COALESCE(NEW.payout_address, '')) <> ''
|
||||
AND NEW.payout_address <> 'PENDING_NO_ADDRESS'
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM users u
|
||||
WHERE u.id = OLD.user_id
|
||||
AND u.payout_address = NEW.payout_address
|
||||
);
|
||||
IF NOT allowed_address_claim THEN
|
||||
RAISE EXCEPTION 'payout destination is immutable for payout %', OLD.id
|
||||
USING ERRCODE = '23514';
|
||||
END IF;
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
DROP TRIGGER IF EXISTS trg_payouts_immutable_obligation ON payouts;
|
||||
CREATE TRIGGER trg_payouts_immutable_obligation
|
||||
BEFORE UPDATE ON payouts
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION reject_payout_obligation_mutation();
|
||||
@@ -0,0 +1,26 @@
|
||||
-- Migration 039: Preserve unresolved solo-win payout obligations for manual review.
|
||||
--
|
||||
-- completeGame records a paid win even when its committed user identity cannot be resolved. That
|
||||
-- row must remain a durable, non-dispatchable obligation rather than rolling back the terminal
|
||||
-- game transaction. Migration 038's first constraint omitted this explicit review reason.
|
||||
--
|
||||
-- This forward replacement deliberately changes only the accepted row shape. The immutable
|
||||
-- payout trigger continues to exclude solo_winner_identity_review from its saved-address claim
|
||||
-- exception, so an operator cannot accidentally turn an ownerless obligation into a transfer.
|
||||
|
||||
ALTER TABLE payouts
|
||||
DROP CONSTRAINT IF EXISTS payouts_no_address_review_shape;
|
||||
|
||||
ALTER TABLE payouts
|
||||
ADD CONSTRAINT payouts_no_address_review_shape CHECK (
|
||||
payout_address <> 'PENDING_NO_ADDRESS'
|
||||
OR (
|
||||
status = 'needs_review'
|
||||
AND reason IN (
|
||||
'match_winner_no_address',
|
||||
'solo_winner_no_address',
|
||||
'solo_winner_identity_review'
|
||||
)
|
||||
AND tx_hash IS NULL
|
||||
)
|
||||
) NOT VALID;
|
||||
@@ -0,0 +1,90 @@
|
||||
-- Migration 040: durable proof that a paid entrant freeze committed before its entropy block.
|
||||
--
|
||||
-- A pending match first commits its exact entrants and future target. Only after that transaction
|
||||
-- is durably visible may the server read a fresh daemon tip and record that the target still did
|
||||
-- not exist. These two columns are that post-commit witness. Legacy/unverified freezes are refunded
|
||||
-- at startup and may never activate.
|
||||
|
||||
ALTER TABLE matches
|
||||
ADD COLUMN IF NOT EXISTS entropy_precommit_tip_height BIGINT,
|
||||
ADD COLUMN IF NOT EXISTS entropy_precommit_verified_at TIMESTAMPTZ;
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint
|
||||
WHERE conname = 'matches_entropy_precommit_shape'
|
||||
AND conrelid = 'matches'::regclass
|
||||
) THEN
|
||||
ALTER TABLE matches
|
||||
ADD CONSTRAINT matches_entropy_precommit_shape CHECK (
|
||||
(entropy_precommit_tip_height IS NULL
|
||||
AND entropy_precommit_verified_at IS NULL)
|
||||
OR
|
||||
(entropy_precommit_tip_height IS NOT NULL
|
||||
AND entropy_precommit_verified_at IS NOT NULL
|
||||
AND entropy_precommit_tip_height >= 0
|
||||
AND start_block_height IS NOT NULL
|
||||
AND entropy_precommit_tip_height < start_block_height
|
||||
AND economy IN ('credits_prestige', 'crypto_race'))
|
||||
);
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
CREATE OR REPLACE FUNCTION reject_match_entropy_precommit_mutation()
|
||||
RETURNS TRIGGER AS $$
|
||||
BEGIN
|
||||
IF OLD.entropy_precommit_verified_at IS NOT NULL AND (
|
||||
NEW.entropy_precommit_tip_height IS DISTINCT FROM OLD.entropy_precommit_tip_height
|
||||
OR NEW.entropy_precommit_verified_at IS DISTINCT FROM OLD.entropy_precommit_verified_at
|
||||
) THEN
|
||||
RAISE EXCEPTION 'paid entropy precommit proof is immutable for match %', OLD.id
|
||||
USING ERRCODE = '23514';
|
||||
END IF;
|
||||
|
||||
-- Recording the proof locks the paid freeze identity. The one permitted identity-changing
|
||||
-- transition is the application's pending -> starting activation, whose conditional UPDATE
|
||||
-- proves the commitment, target, economy, and marker. Once starting, normal lifecycle writes
|
||||
-- change only status/times, seed reveal, winner, and liability fields.
|
||||
IF OLD.entropy_precommit_verified_at IS NOT NULL
|
||||
AND NOT (OLD.status = 'pending' AND NEW.status = 'starting')
|
||||
AND (
|
||||
NEW.id IS DISTINCT FROM OLD.id
|
||||
OR NEW.economy IS DISTINCT FROM OLD.economy
|
||||
OR NEW.variant IS DISTINCT FROM OLD.variant
|
||||
OR NEW.ruleset_id IS DISTINCT FROM OLD.ruleset_id
|
||||
OR NEW.difficulty_preset IS DISTINCT FROM OLD.difficulty_preset
|
||||
OR NEW.max_players IS DISTINCT FROM OLD.max_players
|
||||
OR NEW.seed_hash IS DISTINCT FROM OLD.seed_hash
|
||||
OR NEW.dungeon IS DISTINCT FROM OLD.dungeon
|
||||
OR NEW.start_block_height IS DISTINCT FROM OLD.start_block_height
|
||||
)
|
||||
THEN
|
||||
RAISE EXCEPTION 'paid match fairness identity is immutable after precommit for match %', OLD.id
|
||||
USING ERRCODE = '23514';
|
||||
END IF;
|
||||
|
||||
IF OLD.entropy_precommit_verified_at IS NULL
|
||||
AND NEW.entropy_precommit_verified_at IS NOT NULL
|
||||
AND (
|
||||
OLD.status <> 'pending'
|
||||
OR OLD.economy NOT IN ('credits_prestige', 'crypto_race')
|
||||
OR NEW.status IS DISTINCT FROM OLD.status
|
||||
OR NEW.economy IS DISTINCT FROM OLD.economy
|
||||
OR NEW.seed_hash IS DISTINCT FROM OLD.seed_hash
|
||||
OR NEW.dungeon IS DISTINCT FROM OLD.dungeon
|
||||
OR NEW.start_block_height IS DISTINCT FROM OLD.start_block_height
|
||||
)
|
||||
THEN
|
||||
RAISE EXCEPTION 'paid freeze identity cannot change while recording precommit proof for match %', OLD.id
|
||||
USING ERRCODE = '23514';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
DROP TRIGGER IF EXISTS trg_matches_immutable_entropy_precommit ON matches;
|
||||
CREATE TRIGGER trg_matches_immutable_entropy_precommit
|
||||
BEFORE UPDATE ON matches
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION reject_match_entropy_precommit_mutation();
|
||||
Reference in New Issue
Block a user