Add 500km link cap, block-height-based claim expiry, and link count in score

- MAX_LINK_DISTANCE_KM (default 500): flat cap on link length. Real
  Ingress scales this off portal/resonator level (up to ~655km); Regress
  has no leveling system to scale off of, so this is a single ceiling.
- PORTAL_TIMEOUT_BLOCKS (default 2100): claims stamp the current Bitcoin
  block height (claimed_at_block, new migration) and expire back to
  neutral after this many blocks — the game's clock is block height, not
  wall-clock. Current height comes from mempool.space (BlockHeightService,
  60s cache), same trust model as the BTC Map dependency. A background
  sweep actively reverts timed-out claims (tearing down their links, same
  as a normal recapture); claim/link routes also check inline so
  correctness doesn't depend on sweep timing between runs.
- Pre-existing claims (already live in production) get backfilled with
  the real current block height once at startup rather than a guessed
  historical value — dry-run verified against an actual copy of the live
  production database before deploying.
- Score now reports link count per team alongside places/fields/area
  (backend already computed this; only the frontend display was missing).

22 new tests (53 total): pure expiry-logic unit tests plus full
claim/link/sweep integration tests using a network-free fake block-height
provider (BlockHeightProvider interface + FakeBlockHeight test double).
This commit is contained in:
2026-08-05 17:20:35 +00:00
parent 927997543d
commit 4fef930029
16 changed files with 451 additions and 23 deletions
+14 -9
View File
@@ -1,6 +1,7 @@
import type { FastifyInstance } from 'fastify';
import { z } from 'zod';
import { haversineMeters } from '../services/geo.js';
import { isClaimExpired } from '../services/expiry.js';
import type { Claim, Place, User } from '../types.js';
const claimBody = z.object({
@@ -13,18 +14,19 @@ function nowSecs(): number {
}
export default async function claimsRoutes(app: FastifyInstance) {
const { db, config } = app.ctx;
const { db, config, blockHeight } = app.ctx;
const getPlace = db.prepare('SELECT * FROM places WHERE id = ?');
const getUser = db.prepare('SELECT * FROM users WHERE pubkey = ?');
const getClaim = db.prepare('SELECT * FROM claims WHERE place_id = ?');
const deleteLinksTouching = db.prepare('DELETE FROM links WHERE from_place_id = ? OR to_place_id = ?');
const upsertClaim = db.prepare(`
INSERT INTO claims (place_id, team, claimed_by_pubkey, claimed_at) VALUES (?, ?, ?, ?)
INSERT INTO claims (place_id, team, claimed_by_pubkey, claimed_at, claimed_at_block) VALUES (?, ?, ?, ?, ?)
ON CONFLICT(place_id) DO UPDATE SET
team = excluded.team,
claimed_by_pubkey = excluded.claimed_by_pubkey,
claimed_at = excluded.claimed_at
claimed_at = excluded.claimed_at,
claimed_at_block = excluded.claimed_at_block
`);
app.post('/api/places/:id/claim', { preHandler: app.requireAuth }, async (req, reply) => {
@@ -45,19 +47,22 @@ export default async function claimsRoutes(app: FastifyInstance) {
});
}
const currentHeight = await blockHeight.getCurrent();
const existing = getClaim.get(placeId) as Claim | undefined;
if (existing?.team === user.team) {
const expired = isClaimExpired(existing, currentHeight, config.PORTAL_TIMEOUT_BLOCKS);
if (existing && !expired && existing.team === user.team) {
return reply.code(409).send({ error: 'already claimed by your team' });
}
// Recapturing (or freshly capturing a neutral place) tears down any links
// through it — a place can't stay part of an enemy field once it flips,
// and a neutral place never had links in the first place so this is a no-op then.
// Recapturing (or freshly capturing a neutral/timed-out place) tears down
// any links through it — a place can't stay part of a field once it
// flips or times out, and a genuinely neutral place never had links in
// the first place so this is a no-op then.
db.transaction(() => {
deleteLinksTouching.run(placeId, placeId);
upsertClaim.run(placeId, user.team, req.userPubkey, nowSecs());
upsertClaim.run(placeId, user.team, req.userPubkey, nowSecs(), currentHeight);
})();
return { placeId, team: user.team, claimedBy: req.userPubkey };
return { placeId, team: user.team, claimedBy: req.userPubkey, claimedAtBlock: currentHeight };
});
}
+20 -7
View File
@@ -1,6 +1,7 @@
import type { FastifyInstance } from 'fastify';
import { z } from 'zod';
import { haversineMeters, segmentsIntersect } from '../services/geo.js';
import { isClaimExpired } from '../services/expiry.js';
import type { Claim, LinkRow, Place, User } from '../types.js';
const linkBody = z.object({
@@ -15,7 +16,7 @@ function nowSecs(): number {
}
export default async function linksRoutes(app: FastifyInstance) {
const { db, config } = app.ctx;
const { db, config, blockHeight } = app.ctx;
const getPlace = db.prepare('SELECT * FROM places WHERE id = ?');
const getUser = db.prepare('SELECT * FROM users WHERE pubkey = ?');
@@ -43,19 +44,31 @@ export default async function linksRoutes(app: FastifyInstance) {
const toPlace = getPlace.get(toPlaceId) as Place | undefined;
if (!fromPlace || !toPlace) return reply.code(404).send({ error: 'place not found' });
const currentHeight = await blockHeight.getCurrent();
const fromClaim = getClaim.get(fromPlaceId) as Claim | undefined;
const toClaim = getClaim.get(toPlaceId) as Claim | undefined;
if (fromClaim?.team !== user.team || toClaim?.team !== user.team) {
const fromExpired = isClaimExpired(fromClaim, currentHeight, config.PORTAL_TIMEOUT_BLOCKS);
const toExpired = isClaimExpired(toClaim, currentHeight, config.PORTAL_TIMEOUT_BLOCKS);
if (fromExpired || toExpired || fromClaim?.team !== user.team || toClaim?.team !== user.team) {
return reply.code(403).send({ error: 'both places must be claimed by your team' });
}
// You must be physically at the origin portal to link out from it — same
// "hack a portal to get a key" presence requirement as Ingress. No range
// limit on the link's total length (per game design decision).
const distance = haversineMeters({ lat, lon }, fromPlace);
if (distance > config.CLAIM_RADIUS_METERS) {
// "hack a portal to get a key" presence requirement as Ingress.
const originDistance = haversineMeters({ lat, lon }, fromPlace);
if (originDistance > config.CLAIM_RADIUS_METERS) {
return reply.code(403).send({
error: `too far from the origin place: ${Math.round(distance)}m (must be within ${config.CLAIM_RADIUS_METERS}m)`,
error: `too far from the origin place: ${Math.round(originDistance)}m (must be within ${config.CLAIM_RADIUS_METERS}m)`,
});
}
// Flat cap on link length — Ingress scales this off portal/resonator
// level, which Regress has no equivalent of, so this is a single fixed
// ceiling instead (config.MAX_LINK_DISTANCE_KM).
const linkDistanceKm = haversineMeters(fromPlace, toPlace) / 1000;
if (linkDistanceKm > config.MAX_LINK_DISTANCE_KM) {
return reply.code(403).send({
error: `link too long: ${linkDistanceKm.toFixed(1)}km (max ${config.MAX_LINK_DISTANCE_KM}km)`,
});
}
+2 -2
View File
@@ -4,13 +4,13 @@ export default async function placesRoutes(app: FastifyInstance) {
const { db } = app.ctx;
const listPlaces = db.prepare(`
SELECT p.*, c.team AS claim_team, c.claimed_by_pubkey, c.claimed_at
SELECT p.*, c.team AS claim_team, c.claimed_by_pubkey, c.claimed_at, c.claimed_at_block
FROM places p
LEFT JOIN claims c ON c.place_id = p.id
ORDER BY p.id
`);
const getPlace = db.prepare(`
SELECT p.*, c.team AS claim_team, c.claimed_by_pubkey, c.claimed_at
SELECT p.*, c.team AS claim_team, c.claimed_by_pubkey, c.claimed_at, c.claimed_at_block
FROM places p
LEFT JOIN claims c ON c.place_id = p.id
WHERE p.id = ?