diff --git a/backend/src/features/battle/ledger/accept.controller.ts b/backend/src/features/battle/ledger/accept.controller.ts index 081ad048..5d5e8755 100644 --- a/backend/src/features/battle/ledger/accept.controller.ts +++ b/backend/src/features/battle/ledger/accept.controller.ts @@ -3,6 +3,7 @@ import type { Response } from 'express'; import type { AuthenticatedRequest } from '@middleware/auth'; import { acceptBattle, type AcceptRejection } from './accept.service'; +import { BATTLE_REFUSALS, CONSENT_REFUSALS } from './constants'; /** * 409 for "someone already acted on this", 404/403/422 for the client's own fault, and 503 for @@ -15,27 +16,29 @@ import { acceptBattle, type AcceptRejection } from './accept.service'; * and a client that backs off and retries is behaving correctly either way. */ export const STATUS_BY_REASON: Record = { - 'intent-not-found': 404, - 'intent-already-consumed': 409, - 'intent-expired': 422, - 'attacker-pet-missing': 404, - 'defender-pet-missing': 404, - 'attacker-not-ready': 409, - 'defender-not-ready': 409, + [BATTLE_REFUSALS.INTENT_NOT_FOUND]: 404, + [BATTLE_REFUSALS.INTENT_ALREADY_CONSUMED]: 409, + [BATTLE_REFUSALS.INTENT_EXPIRED]: 422, + [BATTLE_REFUSALS.ATTACKER_PET_MISSING]: 404, + [BATTLE_REFUSALS.DEFENDER_PET_MISSING]: 404, + [BATTLE_REFUSALS.ATTACKER_NOT_READY]: 409, + [BATTLE_REFUSALS.DEFENDER_NOT_READY]: 409, + // Coverage failures. `@cryptopets/protocol` owns these as its `CoverageFailure` type, and + // it exports no constants for them, so they are spelled here as the protocol spells them. 'not-yet-valid': 409, expired: 409, 'pet-not-covered': 403, 'attacker-level-below-band': 403, 'attacker-level-above-band': 403, 'ruleset-mismatch': 403, - 'no-authorization': 403, - revoked: 403, - 'daily-cap-reached': 429, - 'pet-locked': 409, - 'drand-unavailable': 503, - 'signer-unavailable': 503, - 'item-catalog-stale': 503, - 'equipment-catalog-mismatch': 503, + [CONSENT_REFUSALS.NO_AUTHORIZATION]: 403, + [CONSENT_REFUSALS.REVOKED]: 403, + [CONSENT_REFUSALS.DAILY_CAP_REACHED]: 429, + [BATTLE_REFUSALS.PET_LOCKED]: 409, + [BATTLE_REFUSALS.DRAND_UNAVAILABLE]: 503, + [BATTLE_REFUSALS.SIGNER_UNAVAILABLE]: 503, + [BATTLE_REFUSALS.ITEM_CATALOG_STALE]: 503, + [BATTLE_REFUSALS.EQUIPMENT_CATALOG_MISMATCH]: 503, }; interface AcceptBody { diff --git a/backend/src/features/battle/ledger/accept.service.ts b/backend/src/features/battle/ledger/accept.service.ts index bd3b6d25..cdf4a40c 100644 --- a/backend/src/features/battle/ledger/accept.service.ts +++ b/backend/src/features/battle/ledger/accept.service.ts @@ -26,10 +26,10 @@ import { chooseCommitmentRound, roundPublishTime } from '../randomness'; import { type ConsentFailure, consumeDailyBudget, findCoveringAuthorization } from './consent.service'; import { servedDeploymentId } from './domain'; -import { OUTBOX_TOPICS } from './outbox'; +import { BATTLE_REFUSALS, CONSENT_REFUSALS, OPEN_BATTLE_REFUSALS, OUTBOX_TOPICS } from './constants'; import { buildPetSnapshot } from './snapshot.builder'; import { servedRuleset, servedRulesetHash } from './ruleset.builder'; -import { applyTransition, openBattle } from './transitions'; +import { applyTransition, type ExpectedProgress, openBattle } from './transitions'; /** * The accept flow (§E, §J). @@ -68,37 +68,7 @@ export interface AcceptBattleRequest { roomId?: string; } -export type AcceptRejection = - | 'intent-not-found' - | 'intent-already-consumed' - | 'intent-expired' - | 'attacker-pet-missing' - | 'defender-pet-missing' - | 'attacker-not-ready' - | 'defender-not-ready' - | ConsentFailure - | 'pet-locked' - | 'drand-unavailable' - | 'signer-unavailable' - /** - * The item catalog cannot price something this battle needs priced: a pet wears an - * item with no catalog row, or an equipment row's modifier will not parse (roadmap §4). - * - * Its own reason rather than a 500, because it is an operational fault with an obvious - * remedy (run the seeder) and no fault of the player's. Refusing is the conservative - * end: the alternative is a fight under rules this deployment cannot state, recorded in - * a signed receipt that contradicts chain state. - */ - | 'item-catalog-stale' - /** - * The frozen gear disagrees with what the ruleset this battle names prices it at - * (roadmap §4, threat T13). Reachable when the catalog changes between resolving the - * snapshot and building the ruleset, and otherwise a bug. - * - * Refused rather than fought, because the verifier makes the same comparison on the - * finished receipt: accepting would produce a battle guaranteed to fail verification. - */ - | 'equipment-catalog-mismatch'; +export type AcceptRejection = (typeof BATTLE_REFUSALS)[keyof typeof BATTLE_REFUSALS] | ConsentFailure; export interface AcceptedBattle { battleId: string; @@ -149,18 +119,19 @@ export async function acceptBattle(request: AcceptBattleRequest): Promise> { const intent = await prisma.battleIntent.findUnique({ where: { intentHash: request.intentHash } }); if (!intent) { - return refuse('intent-not-found', `no intent ${request.intentHash}`); + return refuse(BATTLE_REFUSALS.INTENT_NOT_FOUND, `no intent ${request.intentHash}`); } if (intent.consumedAt) { - return refuse('intent-already-consumed', 'this intent already produced a battle'); + return refuse(BATTLE_REFUSALS.INTENT_ALREADY_CONSUMED, 'this intent already produced a battle'); } if (BigInt(request.nowSeconds) >= intent.expiresAt) { - return refuse('intent-expired', `intent expired at ${intent.expiresAt}`); + return refuse(BATTLE_REFUSALS.INTENT_EXPIRED, `intent expired at ${intent.expiresAt}`); } return proceed(intent); } @@ -483,18 +454,18 @@ async function freezeFighters( } if (!attacker) { - return refuse('attacker-pet-missing', `pet ${intent.attackerPetId} is not in the roster`); + return refuse(BATTLE_REFUSALS.ATTACKER_PET_MISSING, `pet ${intent.attackerPetId} is not in the roster`); } if (!defender) { - return refuse('defender-pet-missing', `pet ${intent.defenderPetId} is not in the roster`); + return refuse(BATTLE_REFUSALS.DEFENDER_PET_MISSING, `pet ${intent.defenderPetId} is not in the roster`); } // Both pets must be off cooldown, mirroring GameLogic.sol's requirement that neither side // of an on-chain battle is mid-recovery. if (!isBattleReady(attacker, nowSeconds)) { - return refuse('attacker-not-ready', `attacker ready at ${attacker.readyAt}`); + return refuse(BATTLE_REFUSALS.ATTACKER_NOT_READY, `attacker ready at ${attacker.readyAt}`); } if (!isBattleReady(defender, nowSeconds)) { - return refuse('defender-not-ready', `defender ready at ${defender.readyAt}`); + return refuse(BATTLE_REFUSALS.DEFENDER_NOT_READY, `defender ready at ${defender.readyAt}`); } return proceed({ attacker, defender }); } @@ -534,7 +505,7 @@ async function priceUnderServedRuleset( ruleset, ); if (mismatches.length > 0) { - return refuse('equipment-catalog-mismatch', mismatches.join('; ')); + return refuse(BATTLE_REFUSALS.EQUIPMENT_CATALOG_MISMATCH, mismatches.join('; ')); } const rulesetHash = await servedRulesetHash(); @@ -563,6 +534,7 @@ async function openAcceptedBattle(args: { const opened = await openBattle({ consumeIntentHash: args.intentHash, petIds: [attacker.petId.toString(), defender.petId.toString()], + expectedProgress: [progressOf(attacker), progressOf(defender)], ledger: { battleId: args.battleId, chainId: args.domain.chainId, @@ -590,7 +562,27 @@ async function openAcceptedBattle(args: { if (opened.ok) { return proceed(null); } - return opened.reason === 'pet-locked' - ? refuse('pet-locked', `pet ${opened.petId} already has an open battle`) - : refuse('intent-already-consumed', 'this intent already produced a battle'); + switch (opened.reason) { + case OPEN_BATTLE_REFUSALS.PET_LOCKED: + return refuse(BATTLE_REFUSALS.PET_LOCKED, `pet ${opened.petId} already has an open battle`); + case OPEN_BATTLE_REFUSALS.PET_PROGRESS_CHANGED: + // Reported as pet-locked, so the API keeps one code for "this pet is busy". The detail + // stays neutral: a signing battle is the usual cause, but an item can change progress + // too, and a battle that signed has also started a cooldown, so retrying at once fails. + return refuse(BATTLE_REFUSALS.PET_LOCKED, `pet ${opened.petId}'s progress changed during this accept`); + case OPEN_BATTLE_REFUSALS.INTENT_ALREADY_CONSUMED: + return refuse(BATTLE_REFUSALS.INTENT_ALREADY_CONSUMED, 'this intent already produced a battle'); + } +} + +/** The progress fields a snapshot froze, in the shape `pet_battle_progress` stores them. */ +function progressOf(pet: BattleSnapshot['attacker']): ExpectedProgress { + return { + petId: pet.petId.toString(), + level: pet.level, + xp: pet.xp, + streak: pet.streak, + lastOpponentId: pet.lastOpponentId.toString(), + readyAt: BigInt(pet.readyAt), + }; } diff --git a/backend/src/features/battle/ledger/consent.service.ts b/backend/src/features/battle/ledger/consent.service.ts index 2c3dc83e..a0e0b4b1 100644 --- a/backend/src/features/battle/ledger/consent.service.ts +++ b/backend/src/features/battle/ledger/consent.service.ts @@ -15,6 +15,7 @@ import { ethers } from 'ethers'; import { prisma } from '@config/prisma'; import { verifySolanaSignature } from '@features/auth/solana'; +import { CONSENT_REFUSALS } from './constants'; import { assertServedDomain, servedDeploymentId } from './domain'; import type { SignatureFormat } from './intent.service'; @@ -264,7 +265,7 @@ export interface CoverageRequest { nowSeconds: number; } -export type ConsentFailure = CoverageFailure | 'no-authorization' | 'daily-cap-reached' | 'revoked'; +export type ConsentFailure = CoverageFailure | (typeof CONSENT_REFUSALS)[keyof typeof CONSENT_REFUSALS]; export type ConsentResult = | { ok: true; authorizationHash: string; maxBattlesPerDay: number } @@ -294,7 +295,7 @@ export async function findCoveringAuthorization(request: CoverageRequest): Promi }); if (candidates.length === 0) { - return { ok: false, reason: 'no-authorization', detail: 'this defender has no live authorization' }; + return { ok: false, reason: CONSENT_REFUSALS.NO_AUTHORIZATION, detail: 'this defender has no live authorization' }; } let lastFailure: CoverageFailure = 'pet-not-covered'; @@ -339,7 +340,7 @@ export async function consumeDailyBudget( authorizationHash: string, maxBattlesPerDay: number, nowSeconds: number, -): Promise<{ ok: true; used: number } | { ok: false; reason: 'daily-cap-reached' }> { +): Promise<{ ok: true; used: number } | { ok: false; reason: typeof CONSENT_REFUSALS.DAILY_CAP_REACHED }> { const dayBucket = epochDay(nowSeconds); const bump = async () => @@ -362,7 +363,7 @@ export async function consumeDailyBudget( } } if (result.count === 0) { - return { ok: false, reason: 'daily-cap-reached' }; + return { ok: false, reason: CONSENT_REFUSALS.DAILY_CAP_REACHED }; } const row = await prisma.defenseUsage.findUnique({ where: { authorizationHash_dayBucket: { authorizationHash, dayBucket } }, diff --git a/backend/src/features/battle/ledger/constants.ts b/backend/src/features/battle/ledger/constants.ts new file mode 100644 index 00000000..b0a04d95 --- /dev/null +++ b/backend/src/features/battle/ledger/constants.ts @@ -0,0 +1,91 @@ +/** + * Constants shared across the battle ledger: outbox topics and limits, and the reasons + * `openBattle`, accept and consent refuse. + */ + +/** What the message tells a worker to do next. */ +export const OUTBOX_TOPICS = { + /** Wait for the committed drand round, then verify it and derive the seed. */ + awaitBeacon: 'await-beacon', + /** Run the fight through the canonical engine. */ + compute: 'compute', + /** Ask the independent Go verifier to recompute the result. */ + verify: 'verify', + /** Sign the receipt with the KMS key. */ + sign: 'sign', + /** Publish the receipt to the public corpus. */ + publish: 'publish', +} as const; + +/** + * Publishing is the last per-battle step. Batching and anchoring (§I) deliberately have no + * topic here: they aggregate across every publishable receipt on their own timer + * (`startBatchAnchor`), so there is no per-battle message to send. A `batch` topic was + * declared here for a while and never enqueued or handled, which was worse than absent — + * `claimOutbox` only claims topics `HANDLERS` lists, so anyone who took the declaration at + * face value would have enqueued a message no worker could ever claim, stranding the battle + * in a non-terminal state with both pets locked and nothing to dead-letter it. + */ + +/** Retries before an outbox message is dead-lettered. */ +export const MAX_OUTBOX_ATTEMPTS = 8; + +/** Age after which a claimed outbox message's lock is taken over. See `claimOutbox`. */ +export const STALE_LOCK_MS = 5 * 60 * 1000; + +/** Why `openBattle` refused. Accept maps each one onto its own refusal reason. */ +export const OPEN_BATTLE_REFUSALS = { + /** A pet already has an open battle. */ + PET_LOCKED: 'pet-locked', + /** A pet's progress changed after its snapshot was taken. */ + PET_PROGRESS_CHANGED: 'pet-progress-changed', + /** The originating intent already produced a battle. */ + INTENT_ALREADY_CONSUMED: 'intent-already-consumed', +} as const; + +/** + * Why accept refused a battle, as the API reports it. `accept.controller.ts` maps each one to + * an HTTP status, and clients map each one to player-facing text, so a value is part of the + * API and must not change. + * + * Consent refusals are not listed here: the backend's own are in `CONSENT_REFUSALS`, and the + * coverage ones are `CoverageFailure` in `@cryptopets/protocol`, which owns them. + */ +export const BATTLE_REFUSALS = { + INTENT_NOT_FOUND: 'intent-not-found', + INTENT_ALREADY_CONSUMED: 'intent-already-consumed', + INTENT_EXPIRED: 'intent-expired', + ATTACKER_PET_MISSING: 'attacker-pet-missing', + DEFENDER_PET_MISSING: 'defender-pet-missing', + ATTACKER_NOT_READY: 'attacker-not-ready', + DEFENDER_NOT_READY: 'defender-not-ready', + PET_LOCKED: 'pet-locked', + DRAND_UNAVAILABLE: 'drand-unavailable', + SIGNER_UNAVAILABLE: 'signer-unavailable', + /** + * The item catalog cannot price something this battle needs priced: a pet wears an + * item with no catalog row, or an equipment row's modifier will not parse (roadmap §4). + * + * Its own reason rather than a 500, because it is an operational fault with an obvious + * remedy (run the seeder) and no fault of the player's. Refusing is the conservative + * end: the alternative is a fight under rules this deployment cannot state, recorded in + * a signed receipt that contradicts chain state. + */ + ITEM_CATALOG_STALE: 'item-catalog-stale', + /** + * The frozen gear disagrees with what the ruleset this battle names prices it at + * (roadmap §4, threat T13). Reachable when the catalog changes between resolving the + * snapshot and building the ruleset, and otherwise a bug. + * + * Refused rather than fought, because the verifier makes the same comparison on the + * finished receipt: accepting would produce a battle guaranteed to fail verification. + */ + EQUIPMENT_CATALOG_MISMATCH: 'equipment-catalog-mismatch', +} as const; + +/** Consent refusals the backend decides itself, rather than the protocol's coverage rule. */ +export const CONSENT_REFUSALS = { + NO_AUTHORIZATION: 'no-authorization', + DAILY_CAP_REACHED: 'daily-cap-reached', + REVOKED: 'revoked', +} as const; diff --git a/backend/src/features/battle/ledger/index.ts b/backend/src/features/battle/ledger/index.ts index 0d061b66..d4635c2c 100644 --- a/backend/src/features/battle/ledger/index.ts +++ b/backend/src/features/battle/ledger/index.ts @@ -67,6 +67,14 @@ export { toProtocolAuthorization, verifyAuthorizationSignature, } from './consent.service'; +export { + BATTLE_REFUSALS, + CONSENT_REFUSALS, + MAX_OUTBOX_ATTEMPTS, + OPEN_BATTLE_REFUSALS, + OUTBOX_TOPICS, + STALE_LOCK_MS, +} from './constants'; export { assertServedDomain, servedChainIds, servedDeploymentId, servedDomain } from './domain'; export { deleteSessionDelegations, postSessionDelegation } from './session.controller'; export { @@ -101,8 +109,6 @@ export { listDeadLetters, nextOutboxDueAt, requeueDeadLetter, - MAX_OUTBOX_ATTEMPTS, - OUTBOX_TOPICS, type OutboxMessage, type OutboxTopic, rescheduleOutbox, diff --git a/backend/src/features/battle/ledger/outbox.ts b/backend/src/features/battle/ledger/outbox.ts index 33d1d881..5735caf9 100644 --- a/backend/src/features/battle/ledger/outbox.ts +++ b/backend/src/features/battle/ledger/outbox.ts @@ -2,6 +2,8 @@ import type { Prisma } from '@generated/prisma/client'; import { prisma } from '@config/prisma'; +import { MAX_OUTBOX_ATTEMPTS, OUTBOX_TOPICS, STALE_LOCK_MS } from './constants'; + /** * Transactional outbox for the battle workflow (§J). * @@ -14,34 +16,8 @@ import { prisma } from '@config/prisma'; * which is what `classifyTransition`'s `noop` case is for. */ -/** What the message tells a worker to do next. */ -export const OUTBOX_TOPICS = { - /** Wait for the committed drand round, then verify it and derive the seed. */ - awaitBeacon: 'await-beacon', - /** Run the fight through the canonical engine. */ - compute: 'compute', - /** Ask the independent Go verifier to recompute the result. */ - verify: 'verify', - /** Sign the receipt with the KMS key. */ - sign: 'sign', - /** Publish the receipt to the public corpus. */ - publish: 'publish', -} as const; - -/** - * Publishing is the last per-battle step. Batching and anchoring (§I) deliberately have no - * topic here: they aggregate across every publishable receipt on their own timer - * (`startBatchAnchor`), so there is no per-battle message to send. A `batch` topic was - * declared here for a while and never enqueued or handled, which was worse than absent — - * `claimOutbox` only claims topics `HANDLERS` lists, so anyone who took the declaration at - * face value would have enqueued a message no worker could ever claim, stranding the battle - * in a non-terminal state with both pets locked and nothing to dead-letter it. - */ - export type OutboxTopic = (typeof OUTBOX_TOPICS)[keyof typeof OUTBOX_TOPICS]; -/** Retries before a message is dead-lettered. */ -export const MAX_OUTBOX_ATTEMPTS = 8; /** First retry delay; doubles each attempt up to the cap. */ const BASE_RETRY_SECONDS = 2; const MAX_RETRY_SECONDS = 300; @@ -101,8 +77,6 @@ export async function enqueueOutbox(client: OutboxClient, messages: readonly Out * A takeover counts as an attempt, so a message that keeps killing its worker still ends * in the dead-letter path. */ -export const STALE_LOCK_MS = 5 * 60 * 1000; - export async function claimOutbox( topics: readonly OutboxTopic[], workerId: string, diff --git a/backend/src/features/battle/ledger/transitions.ts b/backend/src/features/battle/ledger/transitions.ts index 18ddb832..161e02d1 100644 --- a/backend/src/features/battle/ledger/transitions.ts +++ b/backend/src/features/battle/ledger/transitions.ts @@ -3,6 +3,7 @@ import type { Prisma } from '@generated/prisma/client'; import { prisma } from '@config/prisma'; +import { OPEN_BATTLE_REFUSALS } from './constants'; import { enqueueOutbox, type OutboxMessage } from './outbox'; import { canForfeitFrom, @@ -119,12 +120,32 @@ export interface OpenBattleRequest { * whichever loses this guard gets `intentAlreadyConsumed`, never a second ledger row. */ consumeIntentHash?: string; + /** + * The progress each pet's snapshot was built from, rechecked after the locks are taken. + * + * The snapshot is read before this transaction, so a pet still finishing another battle + * can be photographed mid-way: its lock is released when that battle signs, this + * transaction then takes the lock, and the snapshot holds progress from before that + * battle. Fighting on it would skip that battle's cooldown, and signing it would write + * progression computed from the old values over that battle's result. + */ + expectedProgress?: readonly ExpectedProgress[]; +} + +export interface ExpectedProgress { + petId: string; + level: number; + xp: number; + streak: number; + lastOpponentId: string; + readyAt: bigint; } export type OpenBattleResult = | { ok: true; battleId: string } - | { ok: false; reason: 'pet-locked'; petId: string } - | { ok: false; reason: 'intent-already-consumed' }; + | { ok: false; reason: typeof OPEN_BATTLE_REFUSALS.PET_LOCKED; petId: string } + | { ok: false; reason: typeof OPEN_BATTLE_REFUSALS.PET_PROGRESS_CHANGED; petId: string } + | { ok: false; reason: typeof OPEN_BATTLE_REFUSALS.INTENT_ALREADY_CONSUMED }; /** * Signals a clean, expected abort of the `openBattle` transaction. @@ -149,6 +170,12 @@ class OpenBattleAbort extends Error { * them fails cleanly on the primary key instead of the two deadlocking against each other * (threat T11). Numeric rather than lexicographic, because pet ids are decimal strings and * `"10" < "9"` as text. + * + * Read Committed, not Serializable. Every check here is a write that Postgres resolves + * against the latest committed row: the intent and progress guards are guarded updates, which + * re-evaluate their `where` once a concurrent writer commits, and the pet locks are inserts + * against a primary key. So a concurrent accept or a battle that signed meanwhile ends in its + * matching refusal rather than a serialization failure that would need a retry. */ export async function openBattle(request: OpenBattleRequest): Promise { const petIds = sortPetIds(request.petIds); @@ -162,7 +189,7 @@ export async function openBattle(request: OpenBattleRequest): Promise 0) { await enqueueOutbox(tx, request.outbox); } return { ok: true, battleId: ledger.battleId }; }, - { isolationLevel: 'Serializable' }, + { isolationLevel: 'ReadCommitted' }, ); } catch (error) { if (error instanceof OpenBattleAbort) { @@ -196,6 +226,44 @@ export async function openBattle(request: OpenBattleRequest): Promise { + const byPetId = new Map(expected.map((pet) => [pet.petId, pet])); + for (const petId of sortPetIds([...byPetId.keys()])) { + const pet = byPetId.get(petId)!; + const { count } = await tx.petBattleProgress.updateMany({ + where: { + chainId, + deploymentId, + petId, + level: pet.level, + xp: pet.xp, + streak: pet.streak, + lastOpponentId: pet.lastOpponentId, + readyAt: pet.readyAt, + }, + // Writes back the value it matched on: the point is the row lock and the + // conflict check, not a change. + data: { level: pet.level }, + }); + if (count === 0) { + throw new OpenBattleAbort({ ok: false, reason: OPEN_BATTLE_REFUSALS.PET_PROGRESS_CHANGED, petId }); + } + } +} + /** Ascending numeric order, which is the lock-acquisition order. */ export function sortPetIds(petIds: readonly string[]): string[] { return [...petIds].sort((a, b) => { diff --git a/backend/tests/features/battle/ledger/accept.service.test.ts b/backend/tests/features/battle/ledger/accept.service.test.ts index b3c1200c..2c5d4e26 100644 --- a/backend/tests/features/battle/ledger/accept.service.test.ts +++ b/backend/tests/features/battle/ledger/accept.service.test.ts @@ -372,6 +372,24 @@ describe('opening the ledger', () => { expect(sign).not.toHaveBeenCalled(); }); + it('has the progress each snapshot froze rechecked once the pets are locked', async () => { + await acceptBattle({ intentHash: INTENT.intentHash, nowSeconds: NOW }); + expect(vi.mocked(openBattle).mock.calls[0]![0].expectedProgress).toEqual([ + { petId: '1', level: 10, xp: 120, streak: 0, lastOpponentId: '0', readyAt: BigInt(NOW - 100) }, + { petId: '2', level: 10, xp: 120, streak: 2, lastOpponentId: '1', readyAt: BigInt(NOW - 100) }, + ]); + }); + + it('refuses as pet-locked when a pet\'s progress changed while this one was being accepted', async () => { + vi.mocked(openBattle).mockResolvedValue({ ok: false, reason: 'pet-progress-changed', petId: '1' }); + expect(await acceptBattle({ intentHash: INTENT.intentHash, nowSeconds: NOW })).toMatchObject({ + ok: false, + reason: 'pet-locked', + detail: "pet 1's progress changed during this accept", + }); + expect(sign).not.toHaveBeenCalled(); + }); + it('locks both pets, in numeric order, and consumes the originating intent atomically', async () => { await acceptBattle({ intentHash: INTENT.intentHash, nowSeconds: NOW }); const call = vi.mocked(openBattle).mock.calls[0]![0]; diff --git a/backend/tests/features/battle/ledger/outbox.test.ts b/backend/tests/features/battle/ledger/outbox.test.ts index 3069d8e9..5424e473 100644 --- a/backend/tests/features/battle/ledger/outbox.test.ts +++ b/backend/tests/features/battle/ledger/outbox.test.ts @@ -25,7 +25,7 @@ import { OUTBOX_TOPICS, retryDelaySeconds, } from '@features/battle/ledger'; -import { STALE_LOCK_MS } from '@features/battle/ledger/outbox'; +import { STALE_LOCK_MS } from '@features/battle/ledger/constants'; const NOW = new Date('2026-07-26T09:00:00.000Z'); diff --git a/backend/tests/features/battle/ledger/transitions.test.ts b/backend/tests/features/battle/ledger/transitions.test.ts index 76164888..53b3a37f 100644 --- a/backend/tests/features/battle/ledger/transitions.test.ts +++ b/backend/tests/features/battle/ledger/transitions.test.ts @@ -12,6 +12,7 @@ const tx = { battleOutbox: { createMany: vi.fn() }, petBattleLock: { create: vi.fn(), deleteMany: vi.fn() }, battleIntent: { updateMany: vi.fn() }, + petBattleProgress: { updateMany: vi.fn() }, }; vi.mock('@config/prisma', () => ({ @@ -37,8 +38,8 @@ import { beforeEach(() => { vi.clearAllMocks(); - // Run the callback inline with the fake client, and record the isolation level so the - // serializable requirement is testable. + // Run the callback inline with the fake client, and record the isolation level so each + // transaction's level is testable. vi.mocked(prisma.$transaction).mockImplementation(((callback: (client: typeof tx) => unknown) => Promise.resolve(callback(tx))) as never); tx.battleLedger.updateMany.mockResolvedValue({ count: 1 }); @@ -169,7 +170,7 @@ describe('openBattle', () => { expect(tx.battleLedger.create).toHaveBeenCalledTimes(1); expect(tx.petBattleLock.create).toHaveBeenCalledTimes(2); expect(tx.battleOutbox.createMany).toHaveBeenCalledTimes(1); - expect(vi.mocked(prisma.$transaction).mock.calls[0]![1]).toEqual({ isolationLevel: 'Serializable' }); + expect(vi.mocked(prisma.$transaction).mock.calls[0]![1]).toEqual({ isolationLevel: 'ReadCommitted' }); }); it('takes locks in ascending numeric pet-id order', async () => { @@ -218,6 +219,64 @@ describe('openBattle', () => { await expect( openBattle({ ledger: { chainId: 'eip155:84532' } as never, petIds: ['9', '10'] }), ).rejects.toThrow(/connection reset/); + // Once: a failed transaction is rethrown, not retried. + expect(prisma.$transaction).toHaveBeenCalledTimes(1); + }); + + describe('with the progress the snapshots froze', () => { + const PROGRESS_9 = { petId: '9', level: 5, xp: 40, streak: 1, lastOpponentId: '10', readyAt: 1_000n }; + const PROGRESS_10 = { petId: '10', level: 7, xp: 90, streak: 0, lastOpponentId: '0', readyAt: 900n }; + const request = () => ({ + ledger: { chainId: 'eip155:84532' } as never, + petIds: ['9', '10'], + expectedProgress: [PROGRESS_9, PROGRESS_10], + }); + + beforeEach(() => { + tx.battleLedger.create.mockResolvedValue({ + battleId: 'btl_1', + chainId: 'eip155:84532', + deploymentId: 'base-sepolia-v2', + }); + tx.petBattleProgress.updateMany.mockResolvedValue({ count: 1 }); + }); + + it('opens the battle when neither pet changed', async () => { + expect(await openBattle(request())).toEqual({ ok: true, battleId: 'btl_1' }); + }); + + it('guards each row on every frozen value, so any change matches nothing', async () => { + await openBattle(request()); + expect(tx.petBattleProgress.updateMany).toHaveBeenCalledWith({ + where: { + chainId: 'eip155:84532', + deploymentId: 'base-sepolia-v2', + petId: '9', + level: 5, + xp: 40, + streak: 1, + lastOpponentId: '10', + readyAt: 1_000n, + }, + data: { level: 5 }, + }); + }); + + it('rechecks after taking the locks, in the same numeric order', async () => { + await openBattle({ ...request(), expectedProgress: [PROGRESS_10, PROGRESS_9] }); + const lastLock = Math.max(...tx.petBattleLock.create.mock.invocationCallOrder); + expect(tx.petBattleProgress.updateMany.mock.invocationCallOrder[0]!).toBeGreaterThan(lastLock); + const order = tx.petBattleProgress.updateMany.mock.calls.map((call) => call[0].where.petId); + expect(order).toEqual(['9', '10']); + }); + + it('aborts when another battle moved a pet on after its snapshot was taken', async () => { + // The other battle signed and released its lock in between, so pet 10's row no + // longer holds the values its snapshot froze. + tx.petBattleProgress.updateMany.mockResolvedValueOnce({ count: 1 }).mockResolvedValueOnce({ count: 0 }); + expect(await openBattle(request())).toEqual({ ok: false, reason: 'pet-progress-changed', petId: '10' }); + expect(tx.battleOutbox.createMany).not.toHaveBeenCalled(); + }); }); });