feat(m1): add replay v1 with verification, determinism gate and status docs
This commit is contained in:
@@ -13,6 +13,8 @@ extern crate alloc;
|
||||
|
||||
pub mod fixed;
|
||||
pub mod hash;
|
||||
#[cfg(feature = "serde")]
|
||||
pub mod replay;
|
||||
pub mod rng;
|
||||
pub mod state;
|
||||
pub mod terrain;
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
//! Replay format v1 (see docs/protocol.md).
|
||||
//!
|
||||
//! A replay is the complete proof of a match: seed, loadouts, timestamped
|
||||
//! commands and the resulting state hash.
|
||||
|
||||
use alloc::format;
|
||||
use alloc::string::{String, ToString};
|
||||
use alloc::vec::Vec;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::state::{Command, Sim, TankSpec};
|
||||
use crate::terrain::WORLD_W;
|
||||
use crate::SIM_VERSION;
|
||||
|
||||
/// Loadout of one player.
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
|
||||
pub struct PlayerLoadout {
|
||||
/// Tank identifier (content id).
|
||||
pub tank: String,
|
||||
/// Weapon ids in slot order.
|
||||
pub loadout: [u8; 3],
|
||||
}
|
||||
|
||||
/// Serialisable command representation.
|
||||
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case")]
|
||||
pub enum CommandDto {
|
||||
/// Fire a weapon.
|
||||
Fire { angle: u32, power: i32, w: u8 },
|
||||
/// Raise the shield.
|
||||
Shield,
|
||||
/// End the turn.
|
||||
EndTurn,
|
||||
}
|
||||
|
||||
impl CommandDto {
|
||||
/// Converts a simulation command into its wire form.
|
||||
pub fn from_command(cmd: Command) -> Self {
|
||||
match cmd {
|
||||
Command::Fire {
|
||||
angle_mdeg,
|
||||
power,
|
||||
weapon,
|
||||
} => CommandDto::Fire {
|
||||
angle: angle_mdeg,
|
||||
power,
|
||||
w: weapon,
|
||||
},
|
||||
Command::Shield => CommandDto::Shield,
|
||||
Command::EndTurn => CommandDto::EndTurn,
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts the wire form back into a simulation command.
|
||||
pub fn to_command(self) -> Command {
|
||||
match self {
|
||||
CommandDto::Fire { angle, power, w } => Command::Fire {
|
||||
angle_mdeg: angle,
|
||||
power,
|
||||
weapon: w,
|
||||
},
|
||||
CommandDto::Shield => Command::Shield,
|
||||
CommandDto::EndTurn => Command::EndTurn,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One recorded command.
|
||||
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct CommandRecord {
|
||||
/// Tick at which the command was submitted.
|
||||
pub t: u32,
|
||||
/// Player index.
|
||||
pub p: u8,
|
||||
/// The command itself.
|
||||
pub c: CommandDto,
|
||||
}
|
||||
|
||||
/// Replay of a complete match.
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ReplayV1 {
|
||||
/// Format version.
|
||||
pub v: u8,
|
||||
/// Simulation version that produced the replay.
|
||||
pub sim_version: String,
|
||||
/// Content hash of the ruleset.
|
||||
pub content_hash: String,
|
||||
/// Match seed.
|
||||
pub seed: u64,
|
||||
/// Game mode (`ranked`, `async`, `daily`, `hotseat`, `campaign`).
|
||||
pub mode: String,
|
||||
/// Player loadouts.
|
||||
pub players: Vec<PlayerLoadout>,
|
||||
/// Timestamped commands.
|
||||
pub commands: Vec<CommandRecord>,
|
||||
/// Resulting state hash.
|
||||
pub final_hash: u64,
|
||||
/// Match length in ticks.
|
||||
pub duration_ticks: u32,
|
||||
}
|
||||
|
||||
impl ReplayV1 {
|
||||
/// Builds a replay from a finished (or in-flight) simulation.
|
||||
pub fn capture(sim: &Sim, content_hash: &str, mode: &str, duration_ticks: u32) -> Self {
|
||||
let commands = sim
|
||||
.recorded_commands()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, (tick, cmd))| CommandRecord {
|
||||
t: *tick,
|
||||
p: if i % 2 == 0 { 0 } else { 1 },
|
||||
c: CommandDto::from_command(*cmd),
|
||||
})
|
||||
.collect();
|
||||
|
||||
let players = [
|
||||
PlayerLoadout {
|
||||
tank: "vanguard".to_string(),
|
||||
loadout: sim.tanks[0].loadout,
|
||||
},
|
||||
PlayerLoadout {
|
||||
tank: "longshot".to_string(),
|
||||
loadout: sim.tanks[1].loadout,
|
||||
},
|
||||
]
|
||||
.to_vec();
|
||||
|
||||
Self {
|
||||
v: 1,
|
||||
sim_version: SIM_VERSION.to_string(),
|
||||
content_hash: content_hash.to_string(),
|
||||
seed: sim.seed,
|
||||
mode: mode.to_string(),
|
||||
players,
|
||||
commands,
|
||||
final_hash: sim.state_hash(),
|
||||
duration_ticks,
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-simulates the replay and returns the resulting state hash.
|
||||
pub fn verify(&self) -> Result<u64, String> {
|
||||
if self.v != 1 {
|
||||
return Err(format!("unsupported replay version {}", self.v));
|
||||
}
|
||||
if self.sim_version != SIM_VERSION {
|
||||
return Err(format!(
|
||||
"sim_version mismatch: replay {} vs server {}",
|
||||
self.sim_version, SIM_VERSION
|
||||
));
|
||||
}
|
||||
if self.players.len() != 2 {
|
||||
return Err(format!("expected 2 players, got {}", self.players.len()));
|
||||
}
|
||||
if self.commands.len() > 50_000 {
|
||||
return Err(format!("too many commands: {}", self.commands.len()));
|
||||
}
|
||||
|
||||
let specs = [
|
||||
TankSpec {
|
||||
x: 220,
|
||||
loadout: self.players[0].loadout,
|
||||
},
|
||||
TankSpec {
|
||||
x: WORLD_W - 220,
|
||||
loadout: self.players[1].loadout,
|
||||
},
|
||||
];
|
||||
let mut sim = Sim::new(self.seed, specs);
|
||||
|
||||
let mut projected = 0u8;
|
||||
for (i, rec) in self.commands.iter().enumerate() {
|
||||
if rec.p != projected {
|
||||
return Err(format!(
|
||||
"command {i} by player {} while {} is to move",
|
||||
rec.p, projected
|
||||
));
|
||||
}
|
||||
while sim.tick < rec.t {
|
||||
sim.tick();
|
||||
}
|
||||
sim.submit(rec.c.to_command())
|
||||
.map_err(|e| format!("illegal command {i}: {e:?}"))?;
|
||||
projected = 1 - projected;
|
||||
}
|
||||
|
||||
while sim.tick < self.duration_ticks {
|
||||
sim.tick();
|
||||
}
|
||||
Ok(sim.state_hash())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::fixed::from_int;
|
||||
|
||||
fn sample_replay() -> ReplayV1 {
|
||||
let mut sim = Sim::default_match(4242);
|
||||
sim.submit(Command::Fire {
|
||||
angle_mdeg: 45_000,
|
||||
power: from_int(1),
|
||||
weapon: 1,
|
||||
})
|
||||
.unwrap();
|
||||
for _ in 0..300 {
|
||||
sim.tick();
|
||||
}
|
||||
ReplayV1::capture(&sim, "b3:test", "hotseat", sim.tick)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replay_verifies_and_matches_hash() {
|
||||
let replay = sample_replay();
|
||||
assert_eq!(replay.verify().unwrap(), replay.final_hash);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_roundtrip_is_stable() {
|
||||
let replay = sample_replay();
|
||||
let json = serde_json::to_string(&replay).unwrap();
|
||||
let back: ReplayV1 = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!(replay, back);
|
||||
assert_eq!(serde_json::to_string(&back).unwrap(), json);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tampering_is_detected() {
|
||||
let mut replay = sample_replay();
|
||||
replay.seed = replay.seed.wrapping_add(1);
|
||||
assert_ne!(replay.verify().unwrap(), replay.final_hash);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_mismatch_is_rejected() {
|
||||
let mut replay = sample_replay();
|
||||
replay.sim_version = "0.0.9".to_string();
|
||||
assert!(replay.verify().is_err());
|
||||
}
|
||||
}
|
||||
@@ -626,4 +626,24 @@ mod tests {
|
||||
assert_eq!(sim.phase, Phase::Finished);
|
||||
assert!(sim.turn > MAX_TURNS, "turn={}", sim.turn);
|
||||
}
|
||||
#[test]
|
||||
fn thousand_seeds_are_reproducible() {
|
||||
for seed in 0..1000u64 {
|
||||
let mut a = Sim::default_match(seed);
|
||||
let mut b = Sim::default_match(seed);
|
||||
let angle = 30_000 + (seed % 20_000) as u32;
|
||||
let power = from_ratio(50 + (seed % 50) as i32, 100);
|
||||
for sim in [&mut a, &mut b] {
|
||||
sim.submit(Command::Fire {
|
||||
angle_mdeg: angle,
|
||||
power,
|
||||
weapon: 1,
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
run(&mut a, 120);
|
||||
run(&mut b, 120);
|
||||
assert_eq!(a.state_hash(), b.state_hash(), "seed {seed} diverged");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user