From ce7a184c700a7a8b4b5e66fa7a6f2adf32a61b56 Mon Sep 17 00:00:00 2001 From: Jubilee_001 Date: Mon, 23 Nov 2026 14:15:11 +0100 Subject: [PATCH] feat(relay): add nonce generation and submit endpoints for gasless meta-transaction relay (#1088) Expose REST endpoints for the gasless meta-transaction relay flow: - GET /relay/nonce/:wallet returns the next unused nonce for a wallet and reserves it for 5 minutes - POST /relay/submit accepts {wallet, nonce, signature, tx_params}, validates the nonce reservation and signature, then submits the transaction on-chain and returns the tx_hash - Expired nonce reservations are freed after 5 minutes - Rate limit of 10 relay requests per wallet per minute (429 when exceeded) Includes service layer with injectable signer/submitter, controllers, routes, rate-limit middleware, and unit + integration tests. --- src/app.ts | 3 + src/modules/relay/index.ts | 8 + src/modules/relay/relay.controllers.ts | 128 +++++++++ src/modules/relay/relay.errors.ts | 62 +++++ src/modules/relay/relay.middleware.ts | 62 +++++ src/modules/relay/relay.routes.test.ts | 258 +++++++++++++++++ src/modules/relay/relay.routes.ts | 52 ++++ src/modules/relay/relay.schemas.ts | 25 ++ src/modules/relay/relay.service.test.ts | 356 ++++++++++++++++++++++++ src/modules/relay/relay.service.ts | 352 +++++++++++++++++++++++ src/modules/relay/relay.types.ts | 52 ++++ 11 files changed, 1358 insertions(+) create mode 100644 src/modules/relay/index.ts create mode 100644 src/modules/relay/relay.controllers.ts create mode 100644 src/modules/relay/relay.errors.ts create mode 100644 src/modules/relay/relay.middleware.ts create mode 100644 src/modules/relay/relay.routes.test.ts create mode 100644 src/modules/relay/relay.routes.ts create mode 100644 src/modules/relay/relay.schemas.ts create mode 100644 src/modules/relay/relay.service.test.ts create mode 100644 src/modules/relay/relay.service.ts create mode 100644 src/modules/relay/relay.types.ts diff --git a/src/app.ts b/src/app.ts index 638fb684..62c574d3 100644 --- a/src/app.ts +++ b/src/app.ts @@ -9,6 +9,7 @@ import keysRouter from './modules/keys/keys.routes'; import tradesRouter from './modules/trades/trades.routes'; import tradersRouter from './modules/traders/traders.routes'; import nonceRouter from './modules/nonce/nonce.routes'; +import relayRouter from './modules/relay/relay.routes'; import swapsRouter from './modules/swaps/swaps.routes'; import milestonesRouter from './modules/keys/milestones.routes'; import internalRouter from './modules/admin/sequencer.routes'; @@ -112,6 +113,8 @@ app.get('/', (_, res: Response) => { // Routes app.use('/status', routeBodySizeLimit('default'), statusRouter); app.use('/nonce', routeBodySizeLimit('default'), nonceRouter); +// Gasless meta-transaction relay flow (#1088): POST /relay/submit, GET /relay/nonce/:wallet +app.use('/relay', routeBodySizeLimit('default'), relayRouter); app.use('/internal', routeBodySizeLimit('default'), internalRouter); app.use('/api/v1', router); app.use('/staking', routeBodySizeLimit('default'), stakingRouter); diff --git a/src/modules/relay/index.ts b/src/modules/relay/index.ts new file mode 100644 index 00000000..e79d2c60 --- /dev/null +++ b/src/modules/relay/index.ts @@ -0,0 +1,8 @@ +// src/modules/relay/index.ts +export * from './relay.types'; +export * from './relay.errors'; +export * from './relay.schemas'; +export * from './relay.service'; +export * from './relay.controllers'; +export * from './relay.middleware'; +export { default as relayRouter, createRelayRouter } from './relay.routes'; diff --git a/src/modules/relay/relay.controllers.ts b/src/modules/relay/relay.controllers.ts new file mode 100644 index 00000000..3f7b2812 --- /dev/null +++ b/src/modules/relay/relay.controllers.ts @@ -0,0 +1,128 @@ +// src/modules/relay/relay.controllers.ts +// HTTP controllers for the gasless meta-transaction relay flow (#1088). + +import type { Request, Response, NextFunction } from 'express'; +import { RelaySubmitBodySchema, RelayNonceParamsSchema } from './relay.schemas'; +import { + reserveWalletNonce, + submitRelayTransaction, + reservationToResponse, +} from './relay.service'; +import { + sendSuccess, + sendError, + sendValidationError, + sendConflict, + zodIssuesToDetails, +} from '../../utils/api-response.utils'; +import { ErrorCode } from '../../constants/error.constants'; +import { + RelayNonceExpiredError, + RelayNonceNotReservedError, + RelayNonceAlreadyUsedError, + RelayInvalidSignatureError, + RelaySubmissionError, +} from './relay.errors'; +import type { RelaySigner, RelaySubmitter } from './relay.types'; +import type { RelaySubmitBody } from './relay.schemas'; +import { defaultSigner, defaultSubmitter } from './relay.service'; + +/** + * GET /relay/nonce/:wallet + * Returns the next unused nonce for the wallet and reserves it for 5 minutes. + */ +export async function httpGetRelayNonce( + req: Request, + res: Response, + next: NextFunction +): Promise { + try { + const parsed = RelayNonceParamsSchema.safeParse(req.params); + if (!parsed.success) { + sendValidationError( + res, + 'Invalid wallet parameter', + zodIssuesToDetails(parsed.error.issues) + ); + return; + } + + const { wallet } = parsed.data; + const reservation = await reserveWalletNonce(wallet); + sendSuccess(res, reservationToResponse(reservation)); + } catch (error) { + next(error); + } +} + +/** + * POST /relay/submit + * Accepts {wallet, nonce, signature, tx_params}, validates the nonce + * reservation and signature, then submits the transaction on-chain. + * Returns the tx_hash on success. + * + * `signer` and `submitter` default to the production implementations but can + * be injected for testing. + */ +export async function httpSubmitRelayTransaction( + req: Request, + res: Response, + next: NextFunction, + signer: RelaySigner = defaultSigner, + submitter: RelaySubmitter = defaultSubmitter +): Promise { + try { + const parsed = RelaySubmitBodySchema.safeParse(req.body); + if (!parsed.success) { + sendValidationError( + res, + 'Invalid request body', + zodIssuesToDetails(parsed.error.issues) + ); + return; + } + + const data = parsed.data as unknown as RelaySubmitBody; + const result = await submitRelayTransaction( + data.wallet, + data.nonce, + data.signature, + data.tx_params, + signer, + submitter + ); + + sendSuccess( + res, + { + wallet: result.wallet, + nonce: result.nonce, + txHash: result.txHash, + }, + 200, + 'Transaction relayed successfully' + ); + } catch (error) { + if (error instanceof RelayNonceNotReservedError) { + sendError(res, 404, ErrorCode.NOT_FOUND, error.message); + return; + } + if (error instanceof RelayNonceExpiredError) { + sendError(res, 410, ErrorCode.GONE, error.message); + return; + } + if (error instanceof RelayNonceAlreadyUsedError) { + sendConflict(res, error.message); + return; + } + if (error instanceof RelayInvalidSignatureError) { + sendError(res, 400, ErrorCode.VALIDATION_ERROR, error.message); + return; + } + if (error instanceof RelaySubmissionError) { + sendError(res, 502, ErrorCode.SERVICE_UNAVAILABLE, error.message); + return; + } + next(error); + } +} diff --git a/src/modules/relay/relay.errors.ts b/src/modules/relay/relay.errors.ts new file mode 100644 index 00000000..9cd783f7 --- /dev/null +++ b/src/modules/relay/relay.errors.ts @@ -0,0 +1,62 @@ +// src/modules/relay/relay.errors.ts +// Domain errors for the gasless meta-transaction relay flow (#1088). + +export class RelayNonceNotReservedError extends Error { + public readonly status = 404; + + constructor( + public readonly wallet: string, + public readonly nonce: number + ) { + super( + `No active nonce reservation for wallet ${wallet} at nonce ${nonce}` + ); + this.name = 'RelayNonceNotReservedError'; + } +} + +export class RelayNonceExpiredError extends Error { + public readonly status = 410; + + constructor( + public readonly wallet: string, + public readonly nonce: number + ) { + super(`Nonce reservation ${nonce} for wallet ${wallet} has expired`); + this.name = 'RelayNonceExpiredError'; + } +} + +export class RelayNonceAlreadyUsedError extends Error { + public readonly status = 409; + + constructor( + public readonly wallet: string, + public readonly nonce: number + ) { + super(`Nonce ${nonce} for wallet ${wallet} has already been used`); + this.name = 'RelayNonceAlreadyUsedError'; + } +} + +export class RelayInvalidSignatureError extends Error { + public readonly status = 400; + + constructor(message = 'Invalid signature for the supplied transaction') { + super(message); + this.name = 'RelayInvalidSignatureError'; + } +} + +export class RelaySubmissionError extends Error { + public readonly status = 502; + + constructor(public readonly cause?: unknown) { + super( + `Relay transaction submission failed: ${ + cause instanceof Error ? cause.message : String(cause) + }` + ); + this.name = 'RelaySubmissionError'; + } +} diff --git a/src/modules/relay/relay.middleware.ts b/src/modules/relay/relay.middleware.ts new file mode 100644 index 00000000..e9606ec0 --- /dev/null +++ b/src/modules/relay/relay.middleware.ts @@ -0,0 +1,62 @@ +// src/modules/relay/relay.middleware.ts +// Middleware for enforcing the per-wallet relay rate limit (#1088). +// 10 relay requests per wallet per minute. + +import type { Request, Response, NextFunction } from 'express'; +import { checkRelayRateLimit } from './relay.service'; +import { sendError } from '../../utils/api-response.utils'; +import { ErrorCode } from '../../constants/error.constants'; +import { StellarAddressSchema } from '../wallet/wallet.schemas'; + +export interface RelayRateLimitedRequest extends Request { + relayWallet?: string; +} + +export function relayRateLimit() { + return async ( + req: RelayRateLimitedRequest, + res: Response, + next: NextFunction + ): Promise => { + const wallet = + req.params.wallet ?? + (req.body as Record | undefined)?.wallet; + + // Non-Stellar wallet values are rejected by the route schemas with 400; + // the rate limiter simply defers to them when the wallet is absent/invalid. + if ( + !wallet || + typeof wallet !== 'string' || + !StellarAddressSchema.safeParse(wallet).success + ) { + return next(); + } + + req.relayWallet = wallet; + + const { allowed, limit, remaining, resetInSeconds } = + await checkRelayRateLimit(wallet); + + res.setHeader('X-RateLimit-Limit', String(limit)); + res.setHeader('X-RateLimit-Remaining', String(remaining)); + + if (!allowed) { + res.setHeader('Retry-After', String(resetInSeconds)); + sendError( + res, + 429, + ErrorCode.RATE_LIMIT, + 'Relay rate limit exceeded: too many requests for this wallet', + [ + { + field: 'wallet', + message: `Maximum ${limit} relay requests per wallet per minute`, + }, + ] + ); + return; + } + + next(); + }; +} diff --git a/src/modules/relay/relay.routes.test.ts b/src/modules/relay/relay.routes.test.ts new file mode 100644 index 00000000..c888d6e6 --- /dev/null +++ b/src/modules/relay/relay.routes.test.ts @@ -0,0 +1,258 @@ +// src/modules/relay/relay.routes.test.ts +// Integration tests for the gasless meta-transaction relay API endpoints (#1088). + +const mockCache = new Map(); + +jest.mock('../../utils/redis.utils', () => ({ + cacheGet: jest.fn(async (key: string) => + mockCache.has(key) ? JSON.stringify(mockCache.get(key)) : null + ), + cacheGetJson: jest.fn(async (key: string) => + mockCache.has(key) ? mockCache.get(key) : null + ), + cacheSetJson: jest.fn(async (key: string, val: any) => { + mockCache.set(key, val); + }), + cacheInvalidate: jest.fn(async (...keys: string[]) => { + keys.forEach(key => mockCache.delete(key)); + }), +})); + +jest.mock('../../utils/logger.utils', () => ({ + logger: { + info: jest.fn(), + warn: jest.fn(), + error: jest.fn(), + debug: jest.fn(), + }, +})); + +import express from 'express'; +import supertest from 'supertest'; +import { createRelayRouter } from './relay.routes'; +import { resetNonceStateForTests } from '../nonce/nonce.service'; + +const VALID_WALLET = 'GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF'; +const INVALID_WALLET = 'not-a-stellar-address'; + +const mockSigner = { + verifySignature: jest.fn(async () => true), +}; +const mockSubmitter = { + submitTransaction: jest.fn(async () => ({ txHash: '0xdeadbeef12345678' })), +}; + +function buildApp() { + const app = express(); + app.use(express.json()); + app.use('/relay', createRelayRouter(mockSigner, mockSubmitter)); + return app; +} + +describe('Relay API Endpoints (#1088)', () => { + beforeEach(() => { + mockCache.clear(); + resetNonceStateForTests(); + jest.clearAllMocks(); + mockSigner.verifySignature.mockResolvedValue(true); + mockSubmitter.submitTransaction.mockResolvedValue({ + txHash: '0xdeadbeef12345678', + }); + }); + + describe('GET /relay/nonce/:wallet', () => { + it('returns 200 with the next unused nonce for the wallet', async () => { + const app = buildApp(); + const res = await supertest(app).get(`/relay/nonce/${VALID_WALLET}`); + + expect(res.status).toBe(200); + expect(res.body.success).toBe(true); + expect(res.body.data).toMatchObject({ + wallet: VALID_WALLET, + nonce: 0, + reserved: true, + }); + expect(res.body.data.expiresInSeconds).toBeGreaterThan(0); + expect(res.body.data.expiresInSeconds).toBeLessThanOrEqual(300); + }); + + it('returns the same reserved nonce on repeated calls within the window', async () => { + const app = buildApp(); + const first = await supertest(app).get(`/relay/nonce/${VALID_WALLET}`); + const second = await supertest(app).get( + `/relay/nonce/${VALID_WALLET}` + ); + + expect(second.status).toBe(200); + expect(second.body.data.nonce).toBe(first.body.data.nonce); + }); + + it('returns 400 when the wallet is not a valid Stellar address', async () => { + const app = buildApp(); + const res = await supertest(app).get(`/relay/nonce/${INVALID_WALLET}`); + + expect(res.status).toBe(400); + expect(res.body.success).toBe(false); + }); + }); + + describe('POST /relay/submit', () => { + async function reserveNonce(app: express.Application) { + const res = await supertest(app).get(`/relay/nonce/${VALID_WALLET}`); + expect(res.status).toBe(200); + return res.body.data.nonce; + } + + it('returns 200 and the tx_hash on successful relay', async () => { + const app = buildApp(); + const nonce = await reserveNonce(app); + + const res = await supertest(app).post('/relay/submit').send({ + wallet: VALID_WALLET, + nonce, + signature: 'valid-signature', + tx_params: 'eyJ0eXBlIjoicHJpY2UifQ==', + }); + + expect(res.status).toBe(200); + expect(res.body.success).toBe(true); + expect(res.body.data).toEqual({ + wallet: VALID_WALLET, + nonce, + txHash: '0xdeadbeef12345678', + }); + expect(mockSubmitter.submitTransaction).toHaveBeenCalledWith( + 'eyJ0eXBlIjoicHJpY2UifQ==' + ); + }); + + it('validates the signature before submitting on-chain', async () => { + const app = buildApp(); + const nonce = await reserveNonce(app); + mockSigner.verifySignature.mockResolvedValue(false); + + const res = await supertest(app).post('/relay/submit').send({ + wallet: VALID_WALLET, + nonce, + signature: 'invalid-signature', + tx_params: 'eyJ0eXBlIjoicHJpY2UifQ==', + }); + + expect(res.status).toBe(400); + expect(res.body.success).toBe(false); + expect(mockSubmitter.submitTransaction).not.toHaveBeenCalled(); + }); + + it('returns 404 when no nonce reservation exists', async () => { + const app = buildApp(); + + const res = await supertest(app).post('/relay/submit').send({ + wallet: VALID_WALLET, + nonce: 0, + signature: 'valid-signature', + tx_params: 'eyJ0eXBlIjoicHJpY2UifQ==', + }); + + expect(res.status).toBe(404); + expect(res.body.success).toBe(false); + }); + + it('returns 410 when the reservation has expired', async () => { + const app = buildApp(); + mockCache.set(`relay:nonce:reserved:${VALID_WALLET}`, { + wallet: VALID_WALLET, + nonce: 0, + reservedAt: new Date(0).toISOString(), + expiresAt: new Date(0).toISOString(), + }); + + const res = await supertest(app).post('/relay/submit').send({ + wallet: VALID_WALLET, + nonce: 0, + signature: 'valid-signature', + tx_params: 'eyJ0eXBlIjoicHJpY2UifQ==', + }); + + expect(res.status).toBe(410); + expect(res.body.success).toBe(false); + }); + + it('returns 409 when the nonce was already consumed', async () => { + const app = buildApp(); + mockCache.set(`relay:nonce:reserved:${VALID_WALLET}`, { + wallet: VALID_WALLET, + nonce: 0, + reservedAt: new Date().toISOString(), + expiresAt: new Date(Date.now() + 300_000).toISOString(), + }); + mockCache.set(`relay:nonce:consumed:${VALID_WALLET}:0`, { + wallet: VALID_WALLET, + nonce: 0, + consumedAt: new Date().toISOString(), + }); + + const res = await supertest(app).post('/relay/submit').send({ + wallet: VALID_WALLET, + nonce: 0, + signature: 'valid-signature', + tx_params: 'eyJ0eXBlIjoicHJpY2UifQ==', + }); + + expect(res.status).toBe(409); + expect(res.body.success).toBe(false); + }); + + it('returns 400 on invalid request body', async () => { + const app = buildApp(); + + const missing = await supertest(app).post('/relay/submit').send({}); + expect(missing.status).toBe(400); + + const badWallet = await supertest(app).post('/relay/submit').send({ + wallet: INVALID_WALLET, + nonce: 0, + signature: 'sig', + tx_params: 'data', + }); + expect(badWallet.status).toBe(400); + }); + }); + + describe('Rate limiting', () => { + it('returns 429 when a wallet exceeds 10 relay requests per minute', async () => { + const app = buildApp(); + + for (let i = 0; i < 10; i += 1) { + const res = await supertest(app).get( + `/relay/nonce/${VALID_WALLET}` + ); + expect(res.status).toBe(200); + } + + const res = await supertest(app).get(`/relay/nonce/${VALID_WALLET}`); + expect(res.status).toBe(429); + expect(res.body.success).toBe(false); + expect(res.body.error.code).toBe('RATE_LIMIT'); + }); + + it('tracks rate limits independently per wallet', async () => { + const app = buildApp(); + + for (let i = 0; i < 10; i += 1) { + await supertest(app).get(`/relay/nonce/${VALID_WALLET}`); + } + + // Exhausted wallet is rate limited + const exhausted = await supertest(app).get( + `/relay/nonce/${VALID_WALLET}` + ); + expect(exhausted.status).toBe(429); + + // A different wallet can still make requests + const other = await supertest(app).get( + `/relay/nonce/${'GBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB2KM'}` + ); + expect(other.status).toBe(200); + }); + }); +}); diff --git a/src/modules/relay/relay.routes.ts b/src/modules/relay/relay.routes.ts new file mode 100644 index 00000000..21a51a0d --- /dev/null +++ b/src/modules/relay/relay.routes.ts @@ -0,0 +1,52 @@ +// src/modules/relay/relay.routes.ts +// Route definitions for the gasless meta-transaction relay flow (#1088). +// +// GET /relay/nonce/:wallet - reserve the next unused nonce (5-minute TTL) +// POST /relay/submit - validate + submit a signed payload on-chain + +import { Router } from 'express'; +import type { RelaySigner, RelaySubmitter } from './relay.types'; +import { + httpGetRelayNonce, + httpSubmitRelayTransaction, +} from './relay.controllers'; +import { defaultSigner, defaultSubmitter } from './relay.service'; +import { relayRateLimit } from './relay.middleware'; + +/** + * Builds the relay router with injectable signer/submitter dependencies + * (defaults to the production implementations). + * + * Rate limiting is applied per route (rather than via `router.use`) so that + * `req.params.wallet` is already populated by Express route matching when the + * limiter reads the wallet for `GET /relay/nonce/:wallet`. + */ +export function createRelayRouter( + signer: RelaySigner = defaultSigner, + submitter: RelaySubmitter = defaultSubmitter +) { + const router = Router(); + + /** + * GET /relay/nonce/:wallet + * Returns the next unused nonce for the wallet, reserved for 5 minutes. + * Rate limited: 10 requests per wallet per minute. + */ + router.get('/nonce/:wallet', relayRateLimit(), httpGetRelayNonce); + + /** + * POST /relay/submit + * Accepts {wallet, nonce, signature, tx_params}, validates the nonce + * reservation and signature, then submits the transaction on-chain. + * Rate limited: 10 requests per wallet per minute. + */ + router.post('/submit', relayRateLimit(), (req, res, next) => + httpSubmitRelayTransaction(req, res, next, signer, submitter) + ); + + return router; +} + +export const relayRouter = createRelayRouter(); + +export default relayRouter; diff --git a/src/modules/relay/relay.schemas.ts b/src/modules/relay/relay.schemas.ts new file mode 100644 index 00000000..a3119739 --- /dev/null +++ b/src/modules/relay/relay.schemas.ts @@ -0,0 +1,25 @@ +// src/modules/relay/relay.schemas.ts +import { z } from 'zod'; +import { StellarAddressSchema } from '../wallet/wallet.schemas'; + +export const RelayNonceParamsSchema = z.object({ + wallet: StellarAddressSchema, +}); + +export type RelayNonceParams = z.infer; + +export const RelaySubmitBodySchema = z.object({ + wallet: StellarAddressSchema, + nonce: z + .number({ required_error: 'nonce is required' }) + .int('nonce must be an integer') + .nonnegative('nonce must be a non-negative integer'), + signature: z + .string({ required_error: 'signature is required' }) + .min(1, 'signature cannot be empty'), + tx_params: z + .string({ required_error: 'tx_params is required' }) + .min(1, 'tx_params cannot be empty'), +}); + +export type RelaySubmitBody = z.infer; diff --git a/src/modules/relay/relay.service.test.ts b/src/modules/relay/relay.service.test.ts new file mode 100644 index 00000000..aed6adcf --- /dev/null +++ b/src/modules/relay/relay.service.test.ts @@ -0,0 +1,356 @@ +// src/modules/relay/relay.service.test.ts +// Unit tests for the gasless meta-transaction relay service (#1088). + +const mockCache = new Map(); + +jest.mock('../../utils/redis.utils', () => ({ + cacheGet: jest.fn(async (key: string) => + mockCache.has(key) ? JSON.stringify(mockCache.get(key)) : null + ), + cacheGetJson: jest.fn(async (key: string) => + mockCache.has(key) ? mockCache.get(key) : null + ), + cacheSetJson: jest.fn(async (key: string, val: any) => { + mockCache.set(key, val); + }), + cacheInvalidate: jest.fn(async (...keys: string[]) => { + keys.forEach(key => mockCache.delete(key)); + }), +})); + +jest.mock('../../utils/logger.utils', () => ({ + logger: { + info: jest.fn(), + warn: jest.fn(), + error: jest.fn(), + debug: jest.fn(), + }, +})); + +import { + reserveWalletNonce, + submitRelayTransaction, + checkRelayRateLimit, + reservationToResponse, + defaultSigner, + defaultSubmitter, + RELAY_NONCE_RESERVATION_TTL_SECONDS, +} from './relay.service'; +import { + RelayNonceExpiredError, + RelayNonceNotReservedError, + RelayNonceAlreadyUsedError, + RelayInvalidSignatureError, + RelaySubmissionError, +} from './relay.errors'; +import { resetNonceStateForTests } from '../nonce/nonce.service'; + +const VALID_WALLET = 'GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF'; +const ANOTHER_WALLET = + 'GBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB2KM'; + +const validSignature = 'valid-signature'; +const validTxParams = 'eyJ0eXBlIjoicHJpY2UifQ=='; // arbitrary payload + +describe('Relay Service (#1088)', () => { + beforeEach(() => { + mockCache.clear(); + resetNonceStateForTests(); + jest.clearAllMocks(); + }); + + describe('reserveWalletNonce', () => { + it('returns the next unused nonce (0) for a wallet with no contract configured', async () => { + const reservation = await reserveWalletNonce(VALID_WALLET); + + expect(reservation).toEqual({ + wallet: VALID_WALLET, + nonce: 0, + reservedAt: expect.any(String), + expiresAt: expect.any(String), + }); + + // It is persisted in Redis with the 5-minute TTL + const stored = mockCache.get(`relay:nonce:reserved:${VALID_WALLET}`); + expect(stored).toEqual(reservation); + }); + + it('uses a 5-minute reservation TTL', async () => { + await reserveWalletNonce(VALID_WALLET); + + const { cacheSetJson } = require('../../utils/redis.utils'); + const lastCall = (cacheSetJson as jest.Mock).mock.calls.at(-1); + expect(lastCall[0]).toBe(`relay:nonce:reserved:${VALID_WALLET}`); + expect(lastCall[2]).toBe(RELAY_NONCE_RESERVATION_TTL_SECONDS); // 300 seconds + }); + + it('returns the existing active reservation instead of creating a new one', async () => { + const first = await reserveWalletNonce(VALID_WALLET); + const second = await reserveWalletNonce(VALID_WALLET); + + expect(second.nonce).toBe(first.nonce); + expect(second.expiresAt).toBe(first.expiresAt); + }); + + it('reserves nonces independently per wallet', async () => { + const resA = await reserveWalletNonce(VALID_WALLET); + const resB = await reserveWalletNonce(ANOTHER_WALLET); + + expect(resA.wallet).toBe(VALID_WALLET); + expect(resB.wallet).toBe(ANOTHER_WALLET); + expect(resA.nonce).toBe(0); + expect(resB.nonce).toBe(0); + }); + + it('frees an expired reservation and creates a fresh one', async () => { + const expiredReservation = { + wallet: VALID_WALLET, + nonce: 7, + reservedAt: new Date(0).toISOString(), + expiresAt: new Date(0).toISOString(), // long expired + }; + mockCache.set( + `relay:nonce:reserved:${VALID_WALLET}`, + expiredReservation + ); + + const fresh = await reserveWalletNonce(VALID_WALLET); + + expect(fresh.nonce).toBe(0); // tracked on-chain nonce, not the expired 7 + expect(mockCache.has(`relay:nonce:reserved:${VALID_WALLET}`)).toBe( + true + ); + expect( + mockCache.get(`relay:nonce:reserved:${VALID_WALLET}`).nonce + ).toBe(0); + }); + }); + + describe('reservationToResponse', () => { + it('reports remaining TTL and reserved flag', () => { + const reservation = { + wallet: VALID_WALLET, + nonce: 3, + reservedAt: new Date().toISOString(), + expiresAt: new Date(Date.now() + 60_000).toISOString(), // 1 minute from now + }; + + const response = reservationToResponse(reservation); + + expect(response.wallet).toBe(VALID_WALLET); + expect(response.nonce).toBe(3); + expect(response.reserved).toBe(true); + expect(response.expiresInSeconds).toBeGreaterThan(50); + expect(response.expiresInSeconds).toBeLessThanOrEqual(60); + }); + + it('reports reserved: false when the TTL has elapsed', () => { + const reservation = { + wallet: VALID_WALLET, + nonce: 3, + reservedAt: new Date().toISOString(), + expiresAt: new Date(0).toISOString(), + }; + + expect(reservationToResponse(reservation).reserved).toBe(false); + }); + }); + + describe('checkRelayRateLimit', () => { + it('allows the first 10 requests per wallet per minute', async () => { + for (let i = 1; i <= 10; i += 1) { + const result = await checkRelayRateLimit(VALID_WALLET); + expect(result.allowed).toBe(true); + expect(result.remaining).toBe(10 - i); + } + }); + + it('rejects the 11th request within the same minute', async () => { + for (let i = 0; i < 10; i += 1) { + await checkRelayRateLimit(VALID_WALLET); + } + + const result = await checkRelayRateLimit(VALID_WALLET); + expect(result.allowed).toBe(false); + expect(result.remaining).toBe(0); + }); + + it('tracks rate limits independently per wallet', async () => { + for (let i = 0; i < 10; i += 1) { + await checkRelayRateLimit(VALID_WALLET); + } + + const exhausted = await checkRelayRateLimit(VALID_WALLET); + expect(exhausted.allowed).toBe(false); + + const fresh = await checkRelayRateLimit(ANOTHER_WALLET); + expect(fresh.allowed).toBe(true); + }); + }); + + describe('submitRelayTransaction', () => { + const mockSigner = { + verifySignature: jest.fn(async () => true), + }; + const mockSubmitter = { + submitTransaction: jest.fn(async () => ({ + txHash: '0xabcdef1234567890', + })), + }; + + it('validates the reservation and signature, then submits and returns tx_hash', async () => { + await reserveWalletNonce(VALID_WALLET); + + const result = await submitRelayTransaction( + VALID_WALLET, + 0, + validSignature, + validTxParams, + mockSigner, + mockSubmitter + ); + + expect(result).toEqual({ + wallet: VALID_WALLET, + nonce: 0, + txHash: '0xabcdef1234567890', + }); + expect(mockSigner.verifySignature).toHaveBeenCalledWith( + VALID_WALLET, + validSignature, + validTxParams + ); + expect(mockSubmitter.submitTransaction).toHaveBeenCalledWith( + validTxParams + ); + }); + + it('does not submit when the signature is invalid', async () => { + await reserveWalletNonce(VALID_WALLET); + const failingSigner = { verifySignature: jest.fn(async () => false) }; + + await expect( + submitRelayTransaction( + VALID_WALLET, + 0, + 'bad-signature', + validTxParams, + failingSigner, + mockSubmitter + ) + ).rejects.toThrow(RelayInvalidSignatureError); + + expect(mockSubmitter.submitTransaction).not.toHaveBeenCalled(); + }); + + it('throws RelayNonceNotReservedError when no reservation exists', async () => { + await expect( + submitRelayTransaction( + VALID_WALLET, + 0, + validSignature, + validTxParams, + mockSigner, + mockSubmitter + ) + ).rejects.toThrow(RelayNonceNotReservedError); + }); + + it('throws RelayNonceExpiredError when the reservation expired', async () => { + mockCache.set(`relay:nonce:reserved:${VALID_WALLET}`, { + wallet: VALID_WALLET, + nonce: 0, + reservedAt: new Date(0).toISOString(), + expiresAt: new Date(0).toISOString(), + }); + + await expect( + submitRelayTransaction( + VALID_WALLET, + 0, + validSignature, + validTxParams, + mockSigner, + mockSubmitter + ) + ).rejects.toThrow(RelayNonceExpiredError); + }); + + it('throws RelayNonceAlreadyUsedError when the nonce was already consumed', async () => { + mockCache.set(`relay:nonce:reserved:${VALID_WALLET}`, { + wallet: VALID_WALLET, + nonce: 0, + reservedAt: new Date().toISOString(), + expiresAt: new Date(Date.now() + 300_000).toISOString(), + }); + mockCache.set(`relay:nonce:consumed:${VALID_WALLET}:0`, { + wallet: VALID_WALLET, + nonce: 0, + consumedAt: new Date().toISOString(), + }); + + await expect( + submitRelayTransaction( + VALID_WALLET, + 0, + validSignature, + validTxParams, + mockSigner, + mockSubmitter + ) + ).rejects.toThrow(RelayNonceAlreadyUsedError); + }); + + it('throws RelaySubmissionError when on-chain submission fails', async () => { + await reserveWalletNonce(VALID_WALLET); + const failingSubmitter = { + submitTransaction: jest.fn(async () => { + throw new RelaySubmissionError(new Error('rpc down')); + }), + }; + + await expect( + submitRelayTransaction( + VALID_WALLET, + 0, + validSignature, + validTxParams, + mockSigner, + failingSubmitter + ) + ).rejects.toThrow(RelaySubmissionError); + }); + + it('invalidates the reservation after a successful submission', async () => { + await reserveWalletNonce(VALID_WALLET); + + await submitRelayTransaction( + VALID_WALLET, + 0, + validSignature, + validTxParams, + mockSigner, + mockSubmitter + ); + + // The reservation is released; a repeat submit finds no active reservation + await expect( + submitRelayTransaction( + VALID_WALLET, + 0, + validSignature, + validTxParams, + mockSigner, + mockSubmitter + ) + ).rejects.toThrow(RelayNonceNotReservedError); + }); + }); + + describe('defaultSigner / defaultSubmitter construction', () => { + it('instantiates without configuration so the module loads in any environment', () => { + expect(defaultSigner).toBeInstanceOf(defaultSigner.constructor); + expect(defaultSubmitter).toBeInstanceOf(defaultSubmitter.constructor); + }); + }); +}); diff --git a/src/modules/relay/relay.service.ts b/src/modules/relay/relay.service.ts new file mode 100644 index 00000000..82ece179 --- /dev/null +++ b/src/modules/relay/relay.service.ts @@ -0,0 +1,352 @@ +// src/modules/relay/relay.service.ts +// Service layer for the gasless meta-transaction relay flow (#1088). +// +// Responsibilities: +// - Generate and reserve the next unused nonce for a wallet (5-minute TTL) +// - Validate and consume a reservation when a signed payload is submitted +// - Enforce per-wallet rate limiting (10 relay requests / wallet / minute) +// +// All side effects (Redis, on-chain submission, signature verification) go +// through injectable dependencies so the module can be tested in isolation. + +import { envConfig } from '../../config'; +import { + cacheGetJson, + cacheSetJson, + cacheInvalidate, +} from '../../utils/redis.utils'; +import { logger } from '../../utils/logger.utils'; +import { getWalletNonce } from '../nonce/nonce.service'; +import { + RelayInvalidSignatureError, + RelayNonceAlreadyUsedError, + RelayNonceExpiredError, + RelayNonceNotReservedError, + RelaySubmissionError, +} from './relay.errors'; +import type { + RelayNonceReservation, + RelayNonceResponse, + RelayRateLimitInfo, + RelaySigner, + RelaySubmitResult, + RelaySubmitter, +} from './relay.types'; + +const RELAY_NONCE_RESERVATION_TTL_SECONDS = 5 * 60; // 5 minutes +const RELAY_RATE_LIMIT_WINDOW_SECONDS = 60; +const RELAY_RATE_LIMIT_MAX_REQUESTS = 10; +const RELAY_CONSUMED_NONCE_TTL_SECONDS = 86400; // 24 hours + +export function relayNonceReservationKey(wallet: string): string { + return `relay:nonce:reserved:${wallet}`; +} + +export function relayRateLimitKey(wallet: string): string { + return `relay:ratelimit:${wallet}`; +} + +export function relayConsumedNonceKey(wallet: string, nonce: number): string { + return `relay:nonce:consumed:${wallet}:${nonce}`; +} + +function nowMs(): number { + return Date.now(); +} + +/** + * Default signature verifier. Validates that `signature` is an ed25519 + * signature from the wallet's Stellar public key over the raw transaction + * payload bytes. Falls back to `false` (reject) when Stellar primitives are + * unavailable or the inputs are malformed, so invalid signatures never result + * in an on-chain submission. + */ +class DefaultRelaySigner implements RelaySigner { + async verifySignature( + wallet: string, + signature: string, + txParams: string + ): Promise { + try { + // Imported statically at module load via the namespace import below. + const { StrKey, verify } = await import('@stellar/stellar-base'); + if (!StrKey.isValidEd25519PublicKey(wallet)) { + return false; + } + const publicKey = StrKey.decodeEd25519PublicKey(wallet); + const data = Buffer.from(txParams, 'utf8'); + let signatureBytes: Buffer; + try { + signatureBytes = Buffer.from(signature, 'base64'); + } catch { + signatureBytes = Buffer.from(signature, 'hex'); + } + return verify(data, signatureBytes, publicKey); + } catch (error) { + logger.warn({ error, wallet }, 'Relay signature verification errored'); + return false; + } + } +} + +/** + * Default on-chain submitter. Forwards the signed payload to the configured + * Soroban RPC `sendTransaction` method and returns the transaction hash. + * Fails closed (throws RelaySubmissionError) when the RPC is not configured + * or the submission is rejected, so a relay never succeeds without an + * on-chain transaction hash. + */ +class DefaultRelaySubmitter implements RelaySubmitter { + async submitTransaction(signedPayload: string): Promise<{ txHash: string }> { + const rpcUrl = (envConfig as any).STELLAR_SOROBAN_RPC_URL; + if (!rpcUrl) { + throw new RelaySubmissionError( + 'Stellar Soroban RPC URL is not configured' + ); + } + + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), 30000); + + try { + const response = await fetch(rpcUrl, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + jsonrpc: '2.0', + id: 'relay-submit-transaction', + method: 'sendTransaction', + params: { transaction: signedPayload }, + }), + signal: controller.signal, + }); + + const envelope = (await response.json()) as { + error?: { message?: string }; + result?: { hash?: string }; + }; + + if (!response.ok || envelope.error) { + throw new RelaySubmissionError( + envelope.error?.message ?? + `Soroban RPC returned HTTP ${response.status}` + ); + } + + const txHash = envelope.result?.hash; + if (!txHash || typeof txHash !== 'string') { + throw new RelaySubmissionError( + 'Soroban RPC did not return a transaction hash' + ); + } + + return { txHash }; + } catch (error) { + if (error instanceof RelaySubmissionError) { + throw error; + } + throw new RelaySubmissionError(error); + } finally { + clearTimeout(timeout); + } + } +} + +const defaultSigner = new DefaultRelaySigner(); +const defaultSubmitter = new DefaultRelaySubmitter(); + +/** + * Returns the next unused nonce for a wallet and reserves it for + * `RELAY_NONCE_RESERVATION_TTL_SECONDS` (5 minutes). + * + * If an active, non-expired reservation already exists for the wallet it is + * returned as-is; otherwise a fresh reservation is created from the wallet's + * current on-chain nonce (tracked state falls back to 0 when no contract is + * configured). + */ +async function reserveWalletNonce( + wallet: string +): Promise { + const existing = await cacheGetJson( + relayNonceReservationKey(wallet) + ); + + if (existing) { + if (new Date(existing.expiresAt).getTime() > nowMs()) { + return existing; + } + // Reservation expired: free it so the nonce can be re-reserved. + await cacheInvalidate(relayNonceReservationKey(wallet)); + logger.info( + { wallet, nonce: existing.nonce }, + 'Expired relay nonce reservation freed' + ); + } + + const currentNonce = await getWalletNonce(wallet); + const nonce = currentNonce.nonce; + const reservedAt = new Date(); + const expiresAt = new Date( + reservedAt.getTime() + RELAY_NONCE_RESERVATION_TTL_SECONDS * 1000 + ); + + const reservation: RelayNonceReservation = { + wallet, + nonce, + reservedAt: reservedAt.toISOString(), + expiresAt: expiresAt.toISOString(), + }; + + await cacheSetJson( + relayNonceReservationKey(wallet), + reservation, + RELAY_NONCE_RESERVATION_TTL_SECONDS + ); + + logger.info( + { wallet, nonce, expiresAt: expiresAt.toISOString() }, + 'Reserved relay nonce for wallet' + ); + + return reservation; +} + +/** + * Converts a reservation into the HTTP response shape for GET /relay/nonce/:wallet. + */ +function reservationToResponse( + reservation: RelayNonceReservation +): RelayNonceResponse { + const ttlSeconds = Math.max( + 0, + Math.ceil((new Date(reservation.expiresAt).getTime() - nowMs()) / 1000) + ); + return { + wallet: reservation.wallet, + nonce: reservation.nonce, + reserved: ttlSeconds > 0, + expiresInSeconds: ttlSeconds, + expiresAt: reservation.expiresAt, + }; +} + +/** + * Checks the per-wallet relay rate limit (10 requests per minute). + * Returns whether the request is allowed plus limit/remaining/reset metadata. + */ +async function checkRelayRateLimit( + wallet: string +): Promise { + const key = relayRateLimitKey(wallet); + const current = (await cacheGetJson<{ count: number }>(key)) ?? { + count: 0, + }; + const count = current.count; + + if (count >= RELAY_RATE_LIMIT_MAX_REQUESTS) { + return { + allowed: false, + limit: RELAY_RATE_LIMIT_MAX_REQUESTS, + remaining: 0, + resetInSeconds: RELAY_RATE_LIMIT_WINDOW_SECONDS, + }; + } + + const nextCount = count + 1; + await cacheSetJson( + key, + { count: nextCount, wallet, updatedAt: new Date().toISOString() }, + RELAY_RATE_LIMIT_WINDOW_SECONDS + ); + + return { + allowed: true, + limit: RELAY_RATE_LIMIT_MAX_REQUESTS, + remaining: Math.max(0, RELAY_RATE_LIMIT_MAX_REQUESTS - nextCount), + resetInSeconds: RELAY_RATE_LIMIT_WINDOW_SECONDS, + }; +} + +/** + * Validates and consumes a nonce reservation, verifies the signature, then + * submits the transaction on-chain. Returns the transaction hash on success. + * + * Rejects (in order): + * - 404 when no active reservation exists for the (wallet, nonce) + * - 410 when the reservation has expired + * - 400 when the signature does not validate + * - 502 when on-chain submission fails + */ +async function submitRelayTransaction( + wallet: string, + nonce: number, + signature: string, + txParams: string, + signer: RelaySigner = defaultSigner, + submitter: RelaySubmitter = defaultSubmitter +): Promise { + const reservation = await cacheGetJson( + relayNonceReservationKey(wallet) + ); + + if (!reservation) { + throw new RelayNonceNotReservedError(wallet, nonce); + } + + if (reservation.nonce !== nonce) { + throw new RelayNonceNotReservedError(wallet, nonce); + } + + if (new Date(reservation.expiresAt).getTime() <= nowMs()) { + throw new RelayNonceExpiredError(wallet, nonce); + } + + const signatureValid = await signer.verifySignature( + wallet, + signature, + txParams + ); + if (!signatureValid) { + throw new RelayInvalidSignatureError(); + } + + // Mark the nonce as consumed so the same reservation cannot be replayed. + const consumedKey = relayConsumedNonceKey(wallet, nonce); + const alreadyConsumed = await cacheGetJson<{ consumedAt: string }>( + consumedKey + ); + if (alreadyConsumed) { + throw new RelayNonceAlreadyUsedError(wallet, nonce); + } + await cacheSetJson( + consumedKey, + { wallet, nonce, consumedAt: new Date().toISOString() }, + RELAY_CONSUMED_NONCE_TTL_SECONDS + ); + // Release the reservation now that it has been consumed. + await cacheInvalidate(relayNonceReservationKey(wallet)); + + const { txHash } = await submitter.submitTransaction(txParams); + + logger.info({ wallet, nonce, txHash }, 'Relay transaction submitted'); + + return { + wallet, + nonce, + txHash, + }; +} + +export { + reserveWalletNonce, + submitRelayTransaction, + checkRelayRateLimit, + reservationToResponse, + DefaultRelaySigner, + DefaultRelaySubmitter, + defaultSigner, + defaultSubmitter, + RELAY_NONCE_RESERVATION_TTL_SECONDS, + RELAY_RATE_LIMIT_MAX_REQUESTS, + RELAY_RATE_LIMIT_WINDOW_SECONDS, +}; diff --git a/src/modules/relay/relay.types.ts b/src/modules/relay/relay.types.ts new file mode 100644 index 00000000..5c1ce1c2 --- /dev/null +++ b/src/modules/relay/relay.types.ts @@ -0,0 +1,52 @@ +// src/modules/relay/relay.types.ts +// Shared types for the gasless meta-transaction relay flow (#1088). + +export interface RelayNonceReservation { + wallet: string; + nonce: number; + reservedAt: string; + expiresAt: string; +} + +export interface RelayNonceResponse { + wallet: string; + nonce: number; + reserved: boolean; + expiresInSeconds: number; + expiresAt: string; +} + +export interface RelaySubmitResult { + wallet: string; + nonce: number; + txHash: string; +} + +export interface RelayRateLimitInfo { + allowed: boolean; + limit: number; + remaining: number; + resetInSeconds: number; +} + +/** + * Pluggable signer: verifies that `signature` is a valid authorization from + * `wallet` over `txParams`. Injected so tests can control signature outcomes + * without depending on the network or a real keypair. + */ +export interface RelaySigner { + verifySignature( + wallet: string, + signature: string, + txParams: string + ): Promise; +} + +/** + * Pluggable submitter: transmits a signed transaction payload to the network + * and returns the on-chain transaction hash. Injected so tests can confirm + * submission only happens after successful validation. + */ +export interface RelaySubmitter { + submitTransaction(signedPayload: string): Promise<{ txHash: string }>; +}