diff --git a/pkgs/id/src/boards.rs b/pkgs/id/src/boards.rs index a006478d0c..b3ee35cd48 100644 --- a/pkgs/id/src/boards.rs +++ b/pkgs/id/src/boards.rs @@ -140,6 +140,58 @@ pub struct GamePost { pub genesis: serde_json::Value, } +/// Largest serialized package action accepted by one game turn. +pub const MAX_GAME_TURN_ACTION_BYTES: usize = 4 * 1024; +/// Largest serialized state frontier a game turn may name. +pub const MAX_GAME_FRONTIER_BYTES: usize = 16 * 1024; + +/// Signed acceptance of a game-post challenge by one assigned participant. +/// +/// The game post names the players; this object is how a named participant +/// agrees to play under its pinned package. A participant's first turn in a +/// game is accepted only after their acceptance is in the graph (#6160). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct GameAcceptance { + /// Board root hash. + pub board: ArtifactHash, + /// Hash of the `BoardObject::GamePost` being accepted. + pub game: ArtifactHash, + /// The package-defined role the signer accepts, as assigned in the post. + pub role: String, +} + +/// One signed asynchronous turn in a package-pinned game (#6160). +/// +/// A turn is bound to its game post and to the exact package the post pins, +/// is signed by the participant assigned the named role, and names both the +/// previous turn it builds on and the state frontier (the package snapshot +/// string) it saw. Two turns may build on the same predecessor: competing +/// branches stay in the graph as visible forks and each replays on its own. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct GameTurn { + /// Board root hash. + pub board: ArtifactHash, + /// Hash of the `BoardObject::GamePost` this turn belongs to. + pub game: ArtifactHash, + /// Package identity; must equal the game post's pin exactly. + pub package: GamePackageRef, + /// The package-defined role the signer plays, as assigned in the post. + pub role: String, + /// One-based turn index within the game; advances by one per predecessor. + pub index: u64, + /// Previous turn in this lineage, or `None` for the opening turn. + pub prev_turn: Option, + /// Package state frontier (snapshot string) this turn builds on: the + /// game post's genesis for an opening turn, the replayed state after + /// `prev_turn` otherwise. Replay rejects a turn naming any other value. + pub prev_frontier: String, + /// Package-defined action payload, carried as UTF-8 text; the pinned + /// package interprets it during replay. + pub action: String, +} + /// Stable identity root for one public board. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] @@ -421,6 +473,10 @@ pub enum BoardObject { Theme(Theme), /// Package-pinned playable game post metadata. GamePost(GamePost), + /// Signed acceptance of a game post by an assigned participant. + GameAcceptance(GameAcceptance), + /// One signed asynchronous game turn. + GameTurn(GameTurn), /// Signed opt-in host listing / withdrawal. BoardListing(BoardListing), } @@ -442,6 +498,8 @@ impl BoardObject { Self::Tombstone(_) => "tombstone", Self::Theme(_) => "theme", Self::GamePost(_) => "game_post", + Self::GameAcceptance(_) => "game_acceptance", + Self::GameTurn(_) => "game_turn", Self::BoardListing(_) => "board_listing", } } @@ -461,6 +519,8 @@ impl BoardObject { Self::Tombstone(value) => Some(&value.board), Self::BoardListing(value) => Some(&value.board), Self::GamePost(value) => Some(&value.board), + Self::GameAcceptance(value) => Some(&value.board), + Self::GameTurn(value) => Some(&value.board), } } @@ -575,6 +635,27 @@ impl BoardObject { validate_game_data("game configuration", &value.configuration)?; validate_game_data("game genesis state", &value.genesis)?; } + Self::GameAcceptance(value) => { + validate_game_role(&value.role)?; + } + Self::GameTurn(value) => { + validate_text("game package version", &value.package.version, false)?; + ensure!( + value.package.version.len() <= 128, + "game package version is at most 128 bytes" + ); + validate_game_role(&value.role)?; + ensure!(value.index > 0, "game turn indexes start at 1"); + ensure!( + !value.prev_frontier.is_empty() + && value.prev_frontier.len() <= MAX_GAME_FRONTIER_BYTES, + "game turn frontier must be 1 to {MAX_GAME_FRONTIER_BYTES} bytes" + ); + ensure!( + !value.action.is_empty() && value.action.len() <= MAX_GAME_TURN_ACTION_BYTES, + "game turn action must be 1 to {MAX_GAME_TURN_ACTION_BYTES} bytes" + ); + } Self::BoardListing(value) => { ensure!( is_public_key(&value.host), @@ -774,6 +855,53 @@ impl BoardGraph { BoardObject::GamePost(value) => { self.require_board(&value.board)?; } + BoardObject::GameAcceptance(value) => { + self.require_board(&value.board)?; + let game = self.require_game_post(&value.game, &value.board)?; + ensure!( + game_role_assigned(game, author, &value.role), + "game acceptance must be signed by the participant assigned its role" + ); + } + BoardObject::GameTurn(value) => { + self.require_board(&value.board)?; + let game = self.require_game_post(&value.game, &value.board)?; + ensure!( + value.package == game.package, + "game turn package does not match the game post pin" + ); + ensure!( + game_role_assigned(game, author, &value.role), + "game turn must be signed by the participant assigned its role" + ); + ensure!( + self.has_game_acceptance(&value.game, author, &value.role), + "game turn requires the signer's game acceptance in the graph" + ); + match &value.prev_turn { + None => ensure!( + value.index == 1, + "an opening game turn has index 1" + ), + Some(previous_hash) => { + let previous = self + .objects + .get(previous_hash) + .context("game turn predecessor reference is missing")?; + let BoardObject::GameTurn(previous_turn) = &previous.object else { + bail!("game turn predecessor is not a game turn"); + }; + ensure!( + previous_turn.board == value.board && previous_turn.game == value.game, + "game turn predecessor belongs to another game" + ); + ensure!( + value.index == previous_turn.index + 1, + "game turn index must advance by exactly one from its predecessor" + ); + } + } + } BoardObject::Attachment(value) => { self.require_board(&value.board)?; } @@ -954,6 +1082,44 @@ impl BoardGraph { .collect() } + /// All accepted turns of one game, in content-hash order. Callers pick a + /// lineage by following `prev_turn`; competing children of one + /// predecessor are all returned, so forks stay visible (#6160). + pub fn turns_for_game(&self, game: &ArtifactHash) -> Vec<(&ArtifactHash, &GameTurn)> { + self.objects + .iter() + .filter_map(|(hash, signed)| match &signed.object { + BoardObject::GameTurn(turn) if &turn.game == game => Some((hash, turn)), + _ => None, + }) + .collect() + } + + /// The accepted game post named by `reference`, scoped to `board`. + fn require_game_post( + &self, + reference: &ArtifactHash, + board: &ArtifactHash, + ) -> Result<&GamePost> { + let object = self.require_scoped(reference, board, "game_post")?; + let BoardObject::GamePost(game) = &object.object else { + unreachable!("require_scoped checked game post kind") + }; + Ok(game) + } + + /// Whether a signed acceptance of `game` by `author` for `role` is in + /// the graph. Existence-based, like role grants: the verdict does not + /// depend on arrival order among the accepted set. + fn has_game_acceptance(&self, game: &ArtifactHash, author: &str, role: &str) -> bool { + self.objects.values().any(|signed| { + signed.artifact.author == author + && matches!(&signed.object, + BoardObject::GameAcceptance(acceptance) + if &acceptance.game == game && acceptance.role == role) + }) + } + fn require_board(&self, reference: &ArtifactHash) -> Result<&SignedBoardObject> { let object = self .objects @@ -1130,6 +1296,29 @@ impl BoardGraph { .chain(body.supersedes.iter().cloned()) .collect(), BoardObject::GamePost(body) => vec![body.board.clone()], + BoardObject::GameAcceptance(body) => { + vec![body.board.clone(), body.game.clone()] + } + BoardObject::GameTurn(body) => std::iter::once(body.board.clone()) + .chain(std::iter::once(body.game.clone())) + .chain(body.prev_turn.iter().cloned()) + .chain(self.objects.iter().filter_map(|(hash, other)| { + // A turn is only acceptable with its signer's + // acceptance in the graph, so the acceptance is a + // closure dependency of the turn (the same pattern + // as moderator grants above). + match &other.object { + BoardObject::GameAcceptance(acceptance) + if acceptance.game == body.game + && acceptance.role == body.role + && other.artifact.author == signed.artifact.author => + { + Some(hash.clone()) + } + _ => None, + } + })) + .collect(), }; for dependency in dependencies { if self.objects.contains_key(&dependency) && set.insert(dependency.clone()) { @@ -1806,6 +1995,13 @@ fn validate_token_name(value: &str) -> Result<()> { validate_ascii_identifier("theme token name", value, 64) } +/// Whether `author` is assigned `role` in the game post's participant list. +fn game_role_assigned(game: &GamePost, author: &str, role: &str) -> bool { + game.participants + .iter() + .any(|participant| participant.author == author && participant.role == role) +} + fn validate_game_role(value: &str) -> Result<()> { validate_ascii_identifier("game role identifier", value, 64) } @@ -3861,6 +4057,162 @@ mod tests { } } + fn game_acceptance_object( + signer: &SigningKey, + board: ArtifactHash, + game: ArtifactHash, + role: &str, + ) -> SignedBoardObject { + SignedBoardObject::sign( + signer, + 1, + "", + BoardObject::GameAcceptance(GameAcceptance { + board, + game, + role: role.to_owned(), + }), + ) + .unwrap() + } + + fn game_turn_object( + signer: &SigningKey, + board: ArtifactHash, + game: ArtifactHash, + package: GamePackageRef, + role: &str, + index: u64, + prev_turn: Option, + action: &str, + ) -> SignedBoardObject { + SignedBoardObject::sign( + signer, + 1, + "", + BoardObject::GameTurn(GameTurn { + board, + game, + package, + role: role.to_owned(), + index, + prev_turn, + prev_frontier: "---------".to_owned(), + action: action.to_owned(), + }), + ) + .unwrap() + } + + #[test] + fn game_acceptances_and_turns_are_bound_to_the_post_and_its_players() { + // Oracle: the game post's participant list is the whole authority + // table — an acceptance or turn is valid exactly when its signer + // holds the named role, its package equals the post's pin, an + // acceptance by the signer precedes their turns, and indexes + // advance by one along prev_turn. Forks off one predecessor are + // legal and all stay in the graph. + let creator = key(7); + let opponent = key(9); + let stranger = key(3); + let mut graph = BoardGraph::default(); + let root = graph.insert(board(&creator)).unwrap(); + let game = graph + .insert(game_post_object(&creator, &opponent, root.clone())) + .unwrap(); + let package = match &graph.get(&game).unwrap().object { + BoardObject::GamePost(post) => post.package.clone(), + other => panic!("expected game post, got {other:?}"), + }; + + // An acceptance from an unassigned key, or for a role the signer + // does not hold, is refused. + assert!(graph + .insert(game_acceptance_object(&stranger, root.clone(), game.clone(), "o")) + .is_err()); + assert!(graph + .insert(game_acceptance_object(&opponent, root.clone(), game.clone(), "x")) + .is_err()); + graph + .insert(game_acceptance_object(&opponent, root.clone(), game.clone(), "o")) + .unwrap(); + + // The creator's opening turn waits for the creator's acceptance. + let opening = game_turn_object( + &creator, + root.clone(), + game.clone(), + package.clone(), + "x", + 1, + None, + "0", + ); + assert!(graph.insert(opening.clone()).is_err()); + graph + .insert(game_acceptance_object(&creator, root.clone(), game.clone(), "x")) + .unwrap(); + let opening_hash = graph.insert(opening).unwrap(); + + // Wrong signer for the role, a package that is not the pin, and a + // skipped index are all refused. + assert!(graph + .insert(game_turn_object( + &opponent, + root.clone(), + game.clone(), + package.clone(), + "x", + 2, + Some(opening_hash.clone()), + "3", + )) + .is_err()); + let mut wrong_package = package.clone(); + wrong_package.version = "0.2.0".to_owned(); + assert!(graph + .insert(game_turn_object( + &opponent, + root.clone(), + game.clone(), + wrong_package, + "o", + 2, + Some(opening_hash.clone()), + "3", + )) + .is_err()); + assert!(graph + .insert(game_turn_object( + &opponent, + root.clone(), + game.clone(), + package.clone(), + "o", + 3, + Some(opening_hash.clone()), + "3", + )) + .is_err()); + + // Two competing replies to the opening turn are both kept: a fork. + for action in ["3", "4"] { + graph + .insert(game_turn_object( + &opponent, + root.clone(), + game.clone(), + package.clone(), + "o", + 2, + Some(opening_hash.clone()), + action, + )) + .unwrap(); + } + assert_eq!(graph.turns_for_game(&game).len(), 3); + } + #[test] fn game_post_accepts_exact_limits_and_rejects_empty_version() { let author = key(60); diff --git a/pkgs/id/src/game_replay.rs b/pkgs/id/src/game_replay.rs new file mode 100644 index 0000000000..53ea0a38a0 --- /dev/null +++ b/pkgs/id/src/game_replay.rs @@ -0,0 +1,439 @@ +//! Deterministic replay of asynchronous game lineages (#6160). +//! +//! A [`GamePost`](crate::boards::GamePost) pins the exact package bytes a +//! game is played under. This module folds one signed lineage of +//! [`GameTurn`](crate::boards::GameTurn) objects through those bytes in the +//! existing sandbox: the post's genesis string is restored as the opening +//! frontier, each turn's action is applied by the participant number the +//! post's participant list assigns its signer, and the resulting snapshot +//! is the next frontier. A turn that names any frontier other than the one +//! replay has actually reached is rejected as stale, so a valid signed +//! lineage always replays to the same state from the same inputs. +//! +//! Replay is per lineage: competing turns that build on the same +//! predecessor are forks, each replayed on its own — replaying one branch +//! never erases or rewrites another. + +use anyhow::{ensure, Context, Result}; +use sha2::{Digest, Sha256}; + +use crate::boards::{ArtifactHash, BoardGraph, BoardObject, GameTurn}; +use crate::sandbox::{Sandbox, SandboxLimits}; +use crate::world::hex_encode; + +/// The state one replayed lineage reaches. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct GameReplay { + /// Package snapshot string after the last applied turn (the genesis + /// frontier when the lineage is empty). + pub frontier: String, + /// The package's `records` output at the final state, when it has one. + pub records: Option, + /// Number of turns applied. + pub turns_applied: usize, +} + +/// The hashes of the turns that directly build on `prev_turn` within one +/// game (`None` selects opening turns). More than one child is a fork: +/// every competing branch stays visible here. +pub fn game_turn_children( + graph: &BoardGraph, + game: &ArtifactHash, + prev_turn: Option<&ArtifactHash>, +) -> Vec { + graph + .turns_for_game(game) + .into_iter() + .filter(|(_, turn)| turn.prev_turn.as_ref() == prev_turn) + .map(|(hash, _)| hash.clone()) + .collect() +} + +/// Replay `lineage` (turn hashes in play order) for the game post named by +/// `game`, running the exact `package_bytes` the post pins. +/// +/// Oracle: replay is a pure function of (genesis, package bytes, lineage) — +/// the same inputs reach the same frontier and records on every run, and a +/// lineage whose turns name a signer, package, predecessor, index, or +/// frontier that does not match the post or the running state is rejected. +pub fn replay_game_lineage( + graph: &BoardGraph, + game: &ArtifactHash, + lineage: &[ArtifactHash], + package_bytes: &[u8], + seed: u64, +) -> Result { + let game_object = graph.get(game).context("game post is missing")?; + let BoardObject::GamePost(post) = &game_object.object else { + anyhow::bail!("reference is not a game post"); + }; + let package_hash = ArtifactHash::new(hex_encode(&Sha256::digest(package_bytes)))?; + ensure!( + package_hash == post.package.hash, + "package bytes do not match the game post pin" + ); + let genesis = post + .genesis + .as_str() + .context("game genesis is not a package snapshot string")?; + + let sandbox = Sandbox::compile(package_bytes, SandboxLimits::default())?; + let mut world = sandbox.instantiate(seed)?; + world.restore(genesis.as_bytes())?; + let mut frontier = snapshot_string(&mut world)?; + ensure!( + frontier == genesis, + "game genesis does not restore to itself under the pinned package" + ); + + let mut previous: Option<&ArtifactHash> = None; + for (position, turn_hash) in lineage.iter().enumerate() { + let turn_object = graph.get(turn_hash).context("lineage turn is missing")?; + let BoardObject::GameTurn(turn) = &turn_object.object else { + anyhow::bail!("lineage reference is not a game turn"); + }; + ensure!(turn.game == *game, "lineage turn belongs to another game"); + ensure!( + turn.package == post.package, + "lineage turn package does not match the game post pin" + ); + ensure!( + turn.prev_turn.as_ref() == previous, + "lineage turn does not build on the previous lineage turn" + ); + ensure!( + turn.index == u64::try_from(position + 1).unwrap_or(u64::MAX), + "lineage turn index is out of sequence" + ); + ensure!( + turn.prev_frontier == frontier, + "game turn names frontier {}, replay is at {frontier}", + turn.prev_frontier + ); + let participant = participant_number(post, turn, &turn_object.artifact.author)?; + world.update(participant, turn.action.as_bytes())?; + frontier = snapshot_string(&mut world)?; + previous = Some(turn_hash); + } + + let records = world + .records()? + .map(|bytes| String::from_utf8(bytes).context("package records are not UTF-8")) + .transpose()?; + Ok(GameReplay { + frontier, + records, + turns_applied: lineage.len(), + }) +} + +/// The 1-based sandbox participant number of a turn's signer: the position +/// of the (author, role) assignment in the game post's participant list. +fn participant_number( + post: &crate::boards::GamePost, + turn: &GameTurn, + author: &str, +) -> Result { + let position = post + .participants + .iter() + .position(|participant| participant.author == author && participant.role == turn.role) + .context("game turn signer is not assigned the turn role")?; + u64::try_from(position + 1).map_err(Into::into) +} + +fn snapshot_string(world: &mut crate::sandbox::WorldInstance) -> Result { + let bytes = world + .snapshot()? + .context("pinned package exposes no state snapshot")?; + String::from_utf8(bytes).context("package snapshot is not UTF-8") +} + +#[cfg(test)] +mod tests { + use ed25519_dalek::SigningKey; + use sha2::{Digest, Sha256}; + + use super::*; + use crate::boards::{ + Board, BoardObject, GameAcceptance, GameMode, GamePackageRef, GameParticipant, GamePost, + SignedBoardObject, + }; + use crate::world::hex_encode; + + const PACKAGE_WASM: &[u8] = include_bytes!("../apps/tic-tac-toe/program/tic-tac-toe.wasm"); + + fn key(seed: u8) -> SigningKey { + SigningKey::from_bytes(&[seed; 32]) + } + + fn author_of(key: &SigningKey) -> String { + hex_encode(&key.verifying_key().to_bytes()) + } + + struct Fixture { + graph: BoardGraph, + game: ArtifactHash, + package: GamePackageRef, + x_key: SigningKey, + o_key: SigningKey, + } + + fn fixture() -> Fixture { + let x_key = key(7); + let o_key = key(9); + let mut graph = BoardGraph::default(); + let board = SignedBoardObject::sign( + &x_key, + 1, + "", + BoardObject::Board(Board { + board_id: "retro-games".to_owned(), + forked_from: None, + theme_ref: None, + }), + ) + .unwrap(); + let board_hash = graph.insert(board).unwrap(); + let package = GamePackageRef { + hash: ArtifactHash::new(hex_encode(&Sha256::digest(PACKAGE_WASM))).unwrap(), + version: "0.1.0".to_owned(), + }; + let post = SignedBoardObject::sign( + &x_key, + 1, + "", + BoardObject::GamePost(GamePost { + board: board_hash.clone(), + package: package.clone(), + mode: GameMode::AsyncTurns, + configuration: serde_json::json!({"board_size": 3}), + participants: vec![ + GameParticipant { + author: author_of(&x_key), + role: "x".to_owned(), + }, + GameParticipant { + author: author_of(&o_key), + role: "o".to_owned(), + }, + ], + genesis: serde_json::json!("---------"), + }), + ) + .unwrap(); + let game = graph.insert(post).unwrap(); + for (signer, role) in [(&x_key, "x"), (&o_key, "o")] { + let acceptance = SignedBoardObject::sign( + signer, + 1, + "", + BoardObject::GameAcceptance(GameAcceptance { + board: board_hash.clone(), + game: game.clone(), + role: role.to_owned(), + }), + ) + .unwrap(); + graph.insert(acceptance).unwrap(); + } + Fixture { + graph, + game, + package, + x_key, + o_key, + } + } + + fn turn( + fixture: &Fixture, + signer: &SigningKey, + role: &str, + index: u64, + prev_turn: Option, + prev_frontier: &str, + action: &str, + ) -> SignedBoardObject { + SignedBoardObject::sign( + signer, + 1, + "", + BoardObject::GameTurn(GameTurn { + board: fixture + .graph + .get(&fixture.game) + .map(|object| match &object.object { + BoardObject::GamePost(post) => post.board.clone(), + _ => unreachable!(), + }) + .unwrap(), + game: fixture.game.clone(), + package: fixture.package.clone(), + role: role.to_owned(), + index, + prev_turn, + prev_frontier: prev_frontier.to_owned(), + action: action.to_owned(), + }), + ) + .unwrap() + } + + /// Play the standard five-move line: X takes the top row. + fn standard_lineage(fixture: &mut Fixture) -> Vec { + let moves = [ + (&fixture.x_key, "x", "---------", "0"), + (&fixture.o_key, "o", "X--------", "3"), + (&fixture.x_key, "x", "X--O-----", "1"), + (&fixture.o_key, "o", "XX-OO----", "4"), + ]; + // The fourth move's frontier is computed from the third move's + // result; keep the table honest by deriving each frontier via + // replay of the prefix instead of trusting the literals past + // move two. + let mut lineage: Vec = Vec::new(); + for (index, (signer, role, frontier, action)) in moves.iter().enumerate() { + let frontier = if index < 2 { + frontier.to_string() + } else { + replay_game_lineage(&fixture.graph, &fixture.game, &lineage, PACKAGE_WASM, 7) + .unwrap() + .frontier + }; + let signed = turn( + fixture, + signer, + role, + u64::try_from(index + 1).unwrap(), + lineage.last().cloned(), + &frontier, + action, + ); + lineage.push(fixture.graph.insert(signed).unwrap()); + } + let frontier = + replay_game_lineage(&fixture.graph, &fixture.game, &lineage, PACKAGE_WASM, 7) + .unwrap() + .frontier; + let signed = turn( + fixture, + &fixture.x_key, + "x", + 5, + lineage.last().cloned(), + &frontier, + "2", + ); + lineage.push(fixture.graph.insert(signed).unwrap()); + lineage + } + + #[test] + fn signed_lineage_replays_deterministically_to_the_same_state() { + // Oracle: the checked-in tic-tac-toe package itself — X playing + // 0,1,2 against O playing 3,4 wins the top row, and replaying + // the signed lineage twice reaches byte-identical state. + let mut fixture = fixture(); + let lineage = standard_lineage(&mut fixture); + let first = + replay_game_lineage(&fixture.graph, &fixture.game, &lineage, PACKAGE_WASM, 7).unwrap(); + assert_eq!(first.turns_applied, 5); + assert_eq!(first.frontier, "XXXOO----"); + assert_eq!( + first.records.as_deref(), + Some(r#"{"board":"XXXOO----","plays":5,"winner":"X"}"#) + ); + let second = + replay_game_lineage(&fixture.graph, &fixture.game, &lineage, PACKAGE_WASM, 7).unwrap(); + assert_eq!(first, second, "same inputs must replay to the same state"); + } + + #[test] + fn replay_rejects_wrong_package_stale_frontier_and_broken_chain() { + let mut fixture = fixture(); + let lineage = standard_lineage(&mut fixture); + + // Package bytes that do not match the post's pin are refused. + let error = + replay_game_lineage(&fixture.graph, &fixture.game, &lineage, b"wasm?", 7).unwrap_err(); + assert!(error.to_string().contains("do not match"), "{error}"); + + // A turn naming a frontier replay has already passed is stale: + // the graph keeps the signed object (it is well-formed), replay + // is where the frontier is judged. + let stale = turn( + &fixture, + &fixture.o_key, + "o", + 2, + Some(lineage[0].clone()), + "---------", + "4", + ); + let stale_hash = fixture.graph.insert(stale).unwrap(); + let error = replay_game_lineage( + &fixture.graph, + &fixture.game, + &[lineage[0].clone(), stale_hash], + PACKAGE_WASM, + 7, + ) + .unwrap_err(); + assert!(error.to_string().contains("frontier"), "{error}"); + + // Skipping a turn breaks the predecessor chain. + let error = replay_game_lineage( + &fixture.graph, + &fixture.game, + &[lineage[1].clone()], + PACKAGE_WASM, + 7, + ) + .unwrap_err(); + assert!(error.to_string().contains("previous"), "{error}"); + } + + #[test] + fn competing_turns_stay_visible_as_forks_and_replay_independently() { + // Oracle: two signed replies to the same frontier are different + // boards under the package's own rules (O at 3 vs O at 4), and + // both remain in the graph as children of the shared turn. + let mut fixture = fixture(); + let opening = turn(&fixture, &fixture.x_key, "x", 1, None, "---------", "0"); + let opening_hash = fixture.graph.insert(opening).unwrap(); + let mut children = Vec::new(); + for action in ["3", "4"] { + let reply = turn( + &fixture, + &fixture.o_key, + "o", + 2, + Some(opening_hash.clone()), + "X--------", + action, + ); + children.push(fixture.graph.insert(reply).unwrap()); + } + let visible = game_turn_children(&fixture.graph, &fixture.game, Some(&opening_hash)); + assert_eq!(visible.len(), 2, "both competing turns stay visible"); + let left = replay_game_lineage( + &fixture.graph, + &fixture.game, + &[opening_hash.clone(), children[0].clone()], + PACKAGE_WASM, + 7, + ) + .unwrap(); + let right = replay_game_lineage( + &fixture.graph, + &fixture.game, + &[opening_hash, children[1].clone()], + PACKAGE_WASM, + 7, + ) + .unwrap(); + assert_eq!(left.frontier, "X--O-----"); + assert_eq!(right.frontier, "X---O----"); + } +} diff --git a/pkgs/id/src/lib.rs b/pkgs/id/src/lib.rs index f9368ba5ef..04b5d515a9 100644 --- a/pkgs/id/src/lib.rs +++ b/pkgs/id/src/lib.rs @@ -197,6 +197,7 @@ pub mod event_sync; pub mod fileops; pub mod foreign_libsql; pub mod frames; +pub mod game_replay; pub mod groups; pub mod helpers; pub mod hosted_binding;