Skip to content
Merged
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
8 changes: 8 additions & 0 deletions microservices/slot-machine-service/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
FROM node:18-alpine
WORKDIR /app
COPY package.json tsconfig.json ./
COPY src ./src
RUN npm install --production
RUN npm run build || true
EXPOSE 3333
CMD ["node", "dist/main.js"]
24 changes: 24 additions & 0 deletions microservices/slot-machine-service/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Slot Machine Service

Simple NestJS-style microservice that provides provably-fair slot-machine spins.

Endpoints:
- GET /slot/seed-hash -> returns current server seed hash
- GET /slot/reveal-seed -> reveal last server seed (rotates seed)
- POST /slot/spin -> { userId, clientSeed, betAmount }
- GET /slot/history/:userId -> returns spin history

Run locally:

```bash
cd microservices/slot-machine-service
npm install
npm run dev
```

Docker:

```bash
docker build -t slot-machine-service .
docker run -p 3333:3333 slot-machine-service
```
8 changes: 8 additions & 0 deletions microservices/slot-machine-service/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
version: '3.8'
services:
slot-machine-service:
build: .
ports:
- "3333:3333"
environment:
- NODE_ENV=production
24 changes: 24 additions & 0 deletions microservices/slot-machine-service/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"name": "slot-machine-service",
"version": "0.1.0",
"description": "Slot machine microservice with provably-fair spins",
"main": "dist/main.js",
"scripts": {
"start": "ts-node -r tsconfig-paths/register src/main.ts",
"build": "tsc -p tsconfig.json",
"start:prod": "node dist/main.js",
"dev": "ts-node-dev --respawn --transpile-only src/main.ts"
},
"dependencies": {
"@nestjs/common": "^10.0.0",
"@nestjs/core": "^10.0.0",
"@nestjs/platform-express": "^10.0.0",
"reflect-metadata": "^0.1.13",
"rxjs": "^7.8.0"
},
"devDependencies": {
"ts-node": "^10.9.1",
"ts-node-dev": "^2.0.0",
"typescript": "^5.0.0"
}
}
7 changes: 7 additions & 0 deletions microservices/slot-machine-service/src/app.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { Module } from '@nestjs/common';
import { SlotModule } from './slot/slot.module';

@Module({
imports: [SlotModule],
})
export class AppModule {}
13 changes: 13 additions & 0 deletions microservices/slot-machine-service/src/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import 'reflect-metadata';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.enableCors();
const port = process.env.PORT ? Number(process.env.PORT) : 3333;
await app.listen(port);
console.log(`Slot-machine-service running on http://localhost:${port}`);
}

bootstrap();
5 changes: 5 additions & 0 deletions microservices/slot-machine-service/src/slot/dto/spin.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export class SpinDto {
userId: string;
clientSeed: string;
betAmount: number;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export interface SpinHistoryEntry {
id: string;
userId: string;
result: any;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export interface RewardDefinition {
symbol: string;
weight: number;
payoutMultiplier: number;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
export interface SpinResult {
userId: string;
nonce: number;
reels: string[][];
payline: string[];
payout: number;
multiplier: number;
timestamp: number;
serverSeedHash: string;
serverSeed?: string;
clientSeed: string;
proof: string; // HMAC or signature
}
33 changes: 33 additions & 0 deletions microservices/slot-machine-service/src/slot/seed.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { Injectable } from '@nestjs/common';
import * as crypto from 'crypto';

@Injectable()
export class SeedService {
private serverSeed: string;
private serverSeedHash: string;

constructor() {
this.rotateSeed();
}

rotateSeed() {
this.serverSeed = crypto.randomBytes(32).toString('hex');
this.serverSeedHash = crypto.createHash('sha256').update(this.serverSeed).digest('hex');
return this.serverSeedHash;
}

getHash() {
return this.serverSeedHash;
}

reveal() {
const seed = this.serverSeed;
// rotate after reveal to keep forward secrecy
this.rotateSeed();
return seed;
}

computeHMAC(message: string) {
return crypto.createHmac('sha256', this.serverSeed).update(message).digest('hex');
}
}
28 changes: 28 additions & 0 deletions microservices/slot-machine-service/src/slot/slot.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { Controller, Get, Post, Body, Param } from '@nestjs/common';
import { SlotService } from './slot.service';
import { SpinDto } from './dto/spin.dto';

@Controller('slot')
export class SlotController {
constructor(private readonly slotService: SlotService) {}

@Get('seed-hash')
getSeedHash() {
return { seedHash: this.slotService.getSeedHash() };
}

@Get('reveal-seed')
reveal() {
return { seed: this.slotService.revealSeed() };
}

@Post('spin')
spin(@Body() body: SpinDto) {
return this.slotService.spin(body);
}

@Get('history/:userId')
history(@Param('userId') userId: string) {
return this.slotService.getHistoryForUser(userId);
}
}
10 changes: 10 additions & 0 deletions microservices/slot-machine-service/src/slot/slot.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { SlotService } from './slot.service';
import { SlotController } from './slot.controller';
import { SeedService } from './seed.service';

@Module({
providers: [SlotService, SeedService],
controllers: [SlotController],
})
export class SlotModule {}
166 changes: 166 additions & 0 deletions microservices/slot-machine-service/src/slot/slot.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
import { Injectable, ConflictException, BadRequestException } from '@nestjs/common';
import { RewardDefinition } from './entities/reward.entity';
import { SpinDto } from './dto/spin.dto';
import * as crypto from 'crypto';
import { SeedService } from './seed.service';
import { v4 as uuidv4 } from 'uuid';
import * as fs from 'fs';
import * as path from 'path';

@Injectable()
export class SlotService {
private symbols: RewardDefinition[] = [];
private reels = 3;
private rows = 3;
private history: any[] = [];
private lastSpinByUser: Map<string, number> = new Map();
private cooldownMs = 3000; // 3 seconds cooldown
private dataDir: string;

constructor(private seedService: SeedService) {
this.dataDir = path.join(process.cwd(), 'microservices', 'slot-machine-service', 'data');
if (!fs.existsSync(this.dataDir)) fs.mkdirSync(this.dataDir, { recursive: true });
this.loadDefaults();
this.loadHistory();
}

private loadDefaults() {
this.symbols = [
{ symbol: 'CHERRY', weight: 30, payoutMultiplier: 2 },
{ symbol: 'LEMON', weight: 25, payoutMultiplier: 1.5 },
{ symbol: 'ORANGE', weight: 20, payoutMultiplier: 3 },
{ symbol: 'PLUM', weight: 12, payoutMultiplier: 5 },
{ symbol: 'BELL', weight: 8, payoutMultiplier: 10 },
{ symbol: '7', weight: 5, payoutMultiplier: 50 },
];
}

private loadHistory() {
const file = path.join(this.dataDir, 'history.json');
try {
if (fs.existsSync(file)) {
const raw = fs.readFileSync(file, 'utf8');
this.history = JSON.parse(raw || '[]');
}
} catch (err) {
console.warn('Failed to load history', err);
this.history = [];
}
}

private persistHistory() {
const file = path.join(this.dataDir, 'history.json');
fs.writeFileSync(file, JSON.stringify(this.history, null, 2));
}

getSeedHash() {
return this.seedService.getHash();
}

revealSeed() {
return this.seedService.reveal();
}

getHistoryForUser(userId: string) {
return this.history.filter((h) => h.userId === userId).slice().reverse();
}

private weightedChoice(list: RewardDefinition[], rand: number) {
const total = list.reduce((s, i) => s + i.weight, 0);
let acc = 0;
const r = rand * total;
for (const item of list) {
acc += item.weight;
if (r <= acc) return item;
}
return list[list.length - 1];
}

private randomBytes(hex: string, offset: number, length: number) {
// take part of hex string
const slice = hex.slice(offset, offset + length);
return parseInt(slice, 16);
}

spin(dto: SpinDto) {
if (!dto.userId) throw new BadRequestException('userId required');
const now = Date.now();
const last = this.lastSpinByUser.get(dto.userId) || 0;
if (now - last < this.cooldownMs) throw new ConflictException('Cooldown active');
this.lastSpinByUser.set(dto.userId, now);

const nonce = this.getNonceForUser(dto.userId);
const message = `${dto.clientSeed}:${nonce}:${dto.betAmount}`;
const proof = this.seedService.computeHMAC(message);

// use proof hex to generate randomness
const reels: string[][] = [];
for (let r = 0; r < this.reels; r++) {
const reel: string[] = [];
for (let row = 0; row < this.rows; row++) {
// derive pseudo-random float from proof slice
const offset = (r * this.rows + row) * 8;
const intVal = this.randomBytes(proof, offset, 8) || 0;
const rand = (intVal % 1000000) / 1000000;
const choice = this.weightedChoice(this.symbols, rand);
reel.push(choice.symbol);
}
reels.push(reel);
}

// simple payline: middle row across all reels
const payline = reels.map((r) => r[1]);
const { multiplier } = this.evaluatePayline(payline);
const payout = dto.betAmount * multiplier;

const result = {
userId: dto.userId,
nonce,
reels,
payline,
payout,
multiplier,
timestamp: now,
serverSeedHash: this.seedService.getHash(),
clientSeed: dto.clientSeed,
proof,
animation: this.makeAnimationData(reels),
};

this.history.push({ id: uuidv4(), userId: dto.userId, result });
this.persistHistory();

return result;
}

private evaluatePayline(payline: string[]) {
// if all equal -> payout based on symbol multiplier
const first = payline[0];
const allSame = payline.every((s) => s === first);
if (allSame) {
const def = this.symbols.find((s) => s.symbol === first);
return { multiplier: def ? def.payoutMultiplier : 1 };
}
// two of a kind -> small multiplier
const counts = new Map<string, number>();
for (const s of payline) counts.set(s, (counts.get(s) || 0) + 1);
const max = Math.max(...Array.from(counts.values()));
if (max === 2) return { multiplier: 0.5 };
return { multiplier: 0 };
}

private makeAnimationData(reels: string[][]) {
// for each reel: stop positions and duration
return reels.map((r, idx) => ({
reel: idx,
stops: r,
durationMs: 800 + idx * 150,
}));
}

private getNonceForUser(userId: string) {
// simple nonce based on count of previous spins
const count = this.history.filter((h) => h.userId === userId).length;
return count + 1;
}
}
15 changes: 15 additions & 0 deletions microservices/slot-machine-service/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es2020",
"sourceMap": true,
"outDir": "dist",
"incremental": true,
"skipLibCheck": true
},
"include": ["src/**/*"]
}
Loading