Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 18 additions & 15 deletions backend/src/features/battle/ledger/accept.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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<AcceptRejection, number> = {
'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 {
Expand Down
100 changes: 46 additions & 54 deletions backend/src/features/battle/ledger/accept.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -149,18 +119,19 @@ export async function acceptBattle(request: AcceptBattleRequest): Promise<Accept
// an intent never consumed) over a round choice that then turns out to be unobtainable.
const roundChoice = await chooseCommitmentRound(request.nowSeconds);
if (!roundChoice.ok) {
return reject('drand-unavailable', roundChoice.detail);
return reject(BATTLE_REFUSALS.DRAND_UNAVAILABLE, roundChoice.detail);
}

// Consumes one use of the defender's daily budget before the ledger row exists. A later
// pet-locked conflict (rare: it means a lock slipped past the readiness check above between
// here and Stage A) would then leave this use spent with no battle created. That is a
// conservative failure, not a permissive one — the cap is never exceeded, only occasionally
// reached one battle early — and fixing it needs threading a transaction client through
// consumeDailyBudget, which is not worth the added complexity for a race this narrow.
// Consumes one use of the defender's daily budget before the ledger row exists, so any
// refusal from `openBattle` leaves this use spent with no battle created. That is not rare:
// the readiness check above reads `readyAt`, which a battle only moves when it signs, so a
// pet still in another battle passes it and is refused at the lock (`pet-locked`) or at the
// progress recheck (`pet-progress-changed`). It is a conservative failure, not a permissive
// one: the cap is never exceeded, only reached early. Fixing it needs consumeDailyBudget to
// run inside the `openBattle` transaction.
const budget = await consumeDailyBudget(coverage.authorizationHash, coverage.maxBattlesPerDay, request.nowSeconds);
if (!budget.ok) {
return reject('daily-cap-reached', 'defender daily battle cap reached');
return reject(CONSENT_REFUSALS.DAILY_CAP_REACHED, 'defender daily battle cap reached');
}

const battleId = `btl_${randomUUID()}`;
Expand Down Expand Up @@ -219,7 +190,7 @@ export async function acceptBattle(request: AcceptBattleRequest): Promise<Accept
state: BattleState.rejected,
});
if (error instanceof SignerRefusedError) {
return reject('signer-unavailable', error.message);
return reject(BATTLE_REFUSALS.SIGNER_UNAVAILABLE, error.message);
}
throw error;
}
Expand Down Expand Up @@ -421,7 +392,7 @@ function reject(reason: AcceptRejection, detail: string): AcceptBattleResult {
*/
function catalogRejection(error: unknown): AcceptBattleResult {
if (error instanceof ItemCatalogError) {
return reject('item-catalog-stale', error.message);
return reject(BATTLE_REFUSALS.ITEM_CATALOG_STALE, error.message);
}
throw error;
}
Expand Down Expand Up @@ -449,13 +420,13 @@ type BattleIntentRow = NonNullable<Awaited<ReturnType<typeof prisma.battleIntent
async function loadAcceptableIntent(request: AcceptBattleRequest): Promise<Step<BattleIntentRow>> {
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);
}
Expand Down Expand Up @@ -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 });
}
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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),
};
}
9 changes: 5 additions & 4 deletions backend/src/features/battle/ledger/consent.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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 }
Expand Down Expand Up @@ -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';
Expand Down Expand Up @@ -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 () =>
Expand All @@ -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 } },
Expand Down
91 changes: 91 additions & 0 deletions backend/src/features/battle/ledger/constants.ts
Original file line number Diff line number Diff line change
@@ -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;
10 changes: 8 additions & 2 deletions backend/src/features/battle/ledger/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -101,8 +109,6 @@ export {
listDeadLetters,
nextOutboxDueAt,
requeueDeadLetter,
MAX_OUTBOX_ATTEMPTS,
OUTBOX_TOPICS,
type OutboxMessage,
type OutboxTopic,
rescheduleOutbox,
Expand Down
Loading
Loading