From 058432130628d00764663ecf819a9adc6793768d Mon Sep 17 00:00:00 2001 From: salmonik Date: Sun, 8 Nov 2026 03:29:35 +0100 Subject: v5.0.0: protocol v5 and the browser frontend Protocol v5 replaces newline lines with bounded [u32 len][text] frames and REQ/RES/EVT envelopes. Requests carry correlation ids and the server replays the last 256 replies per connection, so a gateway retry cannot double-debit and a late reply cannot clobber a newer request. HELLO/PONG carry server time; crash rounds announce started_at and push coalesced 10 Hz ticks. Crash now commits sha256(seed) before a round and reveals the seed when it ends, so clients recompute the crash point. Adds the webd/ gateway: one blocking thread, one ClientCore and one pinned upstream TLS connection per session, an HttpOnly session cookie, takeover, and a 60-second grace window. The browser sends Command JSON and renders View JSON; it never speaks the game protocol or stores credentials. Adds the vanilla TypeScript browser app at /play/ (login, lobby, all four games, history, notices, crash verification), the nginx /play and /ws routes, and the headless DOM smoke test. webd and the app stay out of the TUI/GUI/server build graph. The client/server version moves to 5.0.0 in lockstep; v4 peers are refused at HELLO. --- src/server/core.rs | 81 +++++++++++++++++++++++++++++++++++++++++------ src/server/games/crash.rs | 76 ++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 140 insertions(+), 17 deletions(-) (limited to 'src/server') diff --git a/src/server/core.rs b/src/server/core.rs index 3cd6469..0b2efb4 100644 --- a/src/server/core.rs +++ b/src/server/core.rs @@ -1,22 +1,26 @@ -use bcrypt::{hash, verify, DEFAULT_COST}; +use bcrypt::{DEFAULT_COST, hash, verify}; use rusqlite::Connection; -use std::collections::HashMap; +use std::collections::{HashMap, VecDeque}; use std::sync::Arc; use crate::blackjack::BlackjackState; use crate::crash::CrashState; +use crate::protocol::{REPLAY_CACHE_LEN, Request}; use crate::server::database; -use crate::version::{download_url, hello_line, Version, VERSION}; use crate::server::games::blackjack::{BlackjackGame, BlackjackHand}; use crate::server::games::crash::{Clock, CrashGame, CrashRound, RealClock}; use crate::server::games::registry::GameRegistry; use crate::server::games::session::SessionManager; use crate::server::games::traits::{GameError, GamePhase, GameState}; +use crate::version::{VERSION, Version, download_url, hello_line, pong_line, unix_time_ms}; #[derive(Debug, Default)] pub struct ConnectionState { user: Option, greeted: bool, + /// Last replies on this connection, oldest first. Request ids are unique + /// while cached, so a retried request replays its first result. + replays: VecDeque<(u64, String, String)>, } /// Settle reservations left behind by a previous process. @@ -39,6 +43,27 @@ impl ConnectionState { pub fn greeted(&self) -> bool { self.greeted } + + fn replay(&self, id: u64, payload: &str) -> Option> { + self.replays + .iter() + .find(|(cached_id, _, _)| *cached_id == id) + .map(|(_, cached_payload, reply)| { + if cached_payload == payload { + Ok(reply.clone()) + } else { + Err("ERROR Request id reused with a different command".to_string()) + } + }) + } + + fn remember(&mut self, id: u64, payload: &str, reply: &str) { + if self.replays.len() >= REPLAY_CACHE_LEN { + self.replays.pop_front(); + } + self.replays + .push_back((id, payload.to_string(), reply.to_string())); + } } pub struct ServerCore { @@ -49,6 +74,8 @@ pub struct ServerCore { blackjack: BlackjackGame, crash: CrashGame, clock: Arc, + /// Last time a crash tick was pushed, in seconds on the game clock. + last_tick: HashMap, } impl ServerCore { @@ -65,6 +92,7 @@ impl ServerCore { blackjack: BlackjackGame::new(), crash: CrashGame::new(), clock: Arc::new(RealClock::new()), + last_tick: HashMap::new(), } } @@ -96,6 +124,21 @@ impl ServerCore { Ok(Self::new(conn)) } + /// Handle one enveloped request, replaying a cached reply for a repeated + /// request id. The payload grammar is unchanged; the envelope only adds + /// correlation and idempotency. + pub fn handle_request(&mut self, state: &mut ConnectionState, request: &Request) -> String { + if let Some(reply) = state.replay(request.id, &request.payload) { + return match reply { + Ok(reply) => reply, + Err(message) => message, + }; + } + let reply = self.handle_message(state, &request.payload); + state.remember(request.id, &request.payload, &reply); + reply + } + pub fn handle_message(&mut self, state: &mut ConnectionState, msg: &str) -> String { let parts: Vec<&str> = msg.splitn(5, ' ').collect(); @@ -201,7 +244,7 @@ impl ServerCore { } } } - "PING" => "PONG".to_string(), + "PING" => pong_line(unix_time_ms()), "INFO" => self.handle_info(state), _ => msg.to_string(), } @@ -212,7 +255,8 @@ impl ServerCore { return "ERROR Invalid HELLO format. Usage: HELLO ".to_string(); } - let (Some(client), Some(server)) = (Version::parse(parts[1]), Version::parse(VERSION)) else { + let (Some(client), Some(server)) = (Version::parse(parts[1]), Version::parse(VERSION)) + else { return "ERROR Invalid version".to_string(); }; @@ -225,7 +269,7 @@ impl ServerCore { } state.greeted = true; - hello_line(VERSION, VERSION, &download_url()) + hello_line(VERSION, VERSION, &download_url(), unix_time_ms()) } fn handle_register(&mut self, username: &str, credential: &str) -> String { @@ -529,8 +573,8 @@ impl ServerCore { // The session is the audit guard for the deduction, so it exists before // the balance is touched. - let crash_point = self.crash.next_crash_point(); - let round = CrashRound::new(bet as u64, crash_point, self.clock.now()); + let seed = self.crash.next_seed(); + let round = CrashRound::new(bet as u64, seed, self.clock.now(), unix_time_ms()); let mut data = HashMap::new(); data.insert("round".to_string(), round.to_json()); data.insert("balance".to_string(), balance.to_string()); @@ -643,11 +687,27 @@ impl ServerCore { if !round.is_running() { continue; } - let elapsed = (self.clock.now() - round.started_at).max(0.0); - if crate::crash::multiplier_at_secs(elapsed) < round.crash_point { + let now = self.clock.now(); + let elapsed = (now - round.started_at).max(0.0); + let multiplier = crate::crash::multiplier_at_secs(elapsed); + if multiplier < round.crash_point { + let last = self + .last_tick + .get(&session.session_id) + .copied() + .unwrap_or(f64::NEG_INFINITY); + if now - last >= 0.1 { + self.last_tick.insert(session.session_id.clone(), now); + out.push(format!( + "crash.tick session={} t={} m={multiplier:.4}", + session.session_id, + unix_time_ms() + )); + } continue; } round.crash(); + self.last_tick.remove(&session.session_id); match self.settle_crash(user, &session.session_id, &round, 0) { Ok(balance) => { let state = round.state(&session.session_id, balance); @@ -678,6 +738,7 @@ impl ServerCore { payout as i64, &details, ); + self.last_tick.remove(session_id); let _ = self.sessions.remove_session(session_id); result.map_err(|error| error.to_string()) } diff --git a/src/server/games/crash.rs b/src/server/games/crash.rs index ba73c7f..1728afc 100644 --- a/src/server/games/crash.rs +++ b/src/server/games/crash.rs @@ -1,5 +1,8 @@ use super::traits::{Game, GameError, GamePhase, GameResult, GameState}; -use crate::crash::{crash_point_from_uniform, payout, CrashState}; +use crate::crash::{ + CrashState, SEED_LEN, commit_seed, crash_point_from_seed, payout, seed_to_uniform, +}; +use rand::RngCore; use serde::{Deserialize, Serialize}; use std::collections::{HashMap, VecDeque}; use std::sync::{Arc, Mutex}; @@ -64,7 +67,14 @@ pub struct CrashRound { pub bet: u64, /// Drawn at start, revealed only when the round ends. pub crash_point: f64, + /// The 32 random bytes the crash point commits to, hex encoded. Kept on + /// the server until the round ends. + pub seed: String, + /// `sha256(seed)` in hex, sent with the start reply. + pub commit: String, pub started_at: f64, + /// Server Unix time at start, milliseconds, for clock sync. + pub started_at_ms: u64, /// `running`, `cashed`, `crashed` or `forfeit`. pub phase: String, pub result: String, @@ -74,11 +84,15 @@ pub struct CrashRound { } impl CrashRound { - pub fn new(bet: u64, crash_point: f64, started_at: f64) -> Self { + pub fn new(bet: u64, seed: [u8; SEED_LEN], started_at: f64, started_at_ms: u64) -> Self { + let crash_point = crash_point_from_seed(&seed); Self { bet, crash_point, + seed: seed_hex(&seed), + commit: commit_seed(&seed), started_at, + started_at_ms, phase: "running".to_string(), result: "playing".to_string(), multiplier: 1.0, @@ -120,6 +134,7 @@ impl CrashRound { balance, multiplier: self.multiplier, potential: payout(self.bet, self.multiplier), + started_at: self.started_at_ms, crash_point: if self.is_running() { None } else { @@ -127,6 +142,12 @@ impl CrashRound { }, payout: self.payout, result: self.result.clone(), + commit: Some(self.commit.clone()), + seed: if self.is_running() { + None + } else { + Some(self.seed.clone()) + }, } } @@ -146,6 +167,34 @@ pub struct CrashGame { uniforms: VecDeque, } +/// Hex encode a round seed. Lowercase, no separators. +fn seed_hex(seed: &[u8]) -> String { + let mut out = String::with_capacity(seed.len() * 2); + for byte in seed { + use std::fmt::Write as _; + let _ = write!(out, "{byte:02x}"); + } + out +} + +/// Draw a seed whose committed point matches a queued test uniform. +/// +/// The first eight bytes are the big-endian integer closest to +/// `uniform * 2^64`; the remaining bytes are zero. This keeps the existing +/// deterministic crash-point tests meaningful while every round still has a +/// real seed. +fn seed_from_uniform(uniform: f64) -> [u8; SEED_LEN] { + let uniform = if uniform.is_finite() { + uniform.clamp(0.0, 0.999_999_999_999_999_9) + } else { + 0.0 + }; + let value = (uniform * 18_446_744_073_709_551_616.0) as u64; + let mut seed = [0u8; SEED_LEN]; + seed[..8].copy_from_slice(&value.to_be_bytes()); + seed +} + impl CrashGame { pub fn new() -> Self { Self { @@ -163,12 +212,25 @@ impl CrashGame { } } + /// Draw the next round seed. Tests supply uniforms; production uses the + /// operating system's random source. + pub fn next_seed(&mut self) -> [u8; SEED_LEN] { + if let Some(uniform) = self.uniforms.pop_front() { + return seed_from_uniform(uniform); + } + let mut seed = [0u8; SEED_LEN]; + rand::thread_rng().fill_bytes(&mut seed); + seed + } + + /// Kept for callers that only need the point a queued uniform encodes. pub fn next_crash_point(&mut self) -> f64 { - let uniform = self - .uniforms - .pop_front() - .unwrap_or_else(rand::random::); - crash_point_from_uniform(uniform) + crash_point_from_seed(&self.next_seed()) + } + + /// The uniform encoded by a seed, exposed for verification tests. + pub fn uniform_of(seed: &[u8; SEED_LEN]) -> f64 { + seed_to_uniform(seed) } } -- cgit v1.2.3