diff --git a/pkgs/id/src/boards.rs b/pkgs/id/src/boards.rs index 0a5c974d86..baabdfea8e 100644 --- a/pkgs/id/src/boards.rs +++ b/pkgs/id/src/boards.rs @@ -16,14 +16,15 @@ //! or claims global erasure. It also adds signed, portable themes a board applies by reference //! ([`Board::theme_ref`]), and [`BoardGraph::compose_view`] projects the //! three-layer view (personal filter / board view / host view) under the -//! transparency rule: hidden is never erased. It does not render markup, -//! serve content, or fetch attachment/game payloads. +//! transparency rule: hidden is never erased. It does not render markup, serve +//! content, execute game packages, replay turns, or fetch attachment/game payloads. //! Duplicate `Rules` objects for the same board and revision are legal signed //! history. [`BoardGraph::resolve_rules`] selects the greater content hash //! within a revision; current rules are the highest revision, using that same //! tie-break, so every peer projects the same signed set identically. use std::collections::{BTreeMap, BTreeSet}; +use std::io::{self, Write}; use anyhow::{Context, Result, bail, ensure}; use ed25519_dalek::{SigningKey, VerifyingKey}; @@ -41,6 +42,10 @@ pub const MAX_BOARD_REFERENCES: usize = 128; pub const MAX_THEME_TOKENS: usize = 64; /// Largest design-token value accepted in a theme. pub const MAX_THEME_TOKEN_VALUE_BYTES: usize = 512; +/// Largest number of assigned participants in one game post. +pub const MAX_GAME_PARTICIPANTS: usize = 32; +/// Largest serialized configuration or genesis state accepted by a game post. +pub const MAX_GAME_DATA_BYTES: usize = 16 * 1024; /// A canonical lower-case SHA-256 artifact/content hash. #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)] @@ -78,15 +83,63 @@ impl<'de> Deserialize<'de> for ArtifactHash { } /// Typed reference to a signed game-post object; game execution is out of scope. -/// In v1, the target must be a same-board `BoardObject::Post`. If a dedicated -/// game-post object kind is added, update the graph's kind check with it. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct GamePostRef { - /// Hash of the immutable signed object represented in the board graph. + /// Hash of the immutable `BoardObject::GamePost` in the board graph. pub object: ArtifactHash, } +/// Immutable package identity pinned by a game post. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct GamePackageRef { + /// SHA-256 hash of the package bytes. A new package build has a new hash. + pub hash: ArtifactHash, + /// Human-facing package version associated with the pinned bytes. + pub version: String, +} + +/// Play mode supported by playable posts in v1. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum GameMode { + /// Players submit signed turns asynchronously against a pinned frontier. + AsyncTurns, +} + +/// One author assigned to a package-defined game role. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct GameParticipant { + /// Canonical Ed25519 public key of the assigned author. + pub author: String, + /// Canonical role identifier understood by the pinned game package. + pub role: String, +} + +/// Signed metadata for a package-pinned playable post. +/// +/// This object records the immutable package reference, package-specific +/// configuration and initial state, and the authors assigned to package-defined +/// roles. It is data, not executable code; accepting it does not run the package. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct GamePost { + /// Board root hash. + pub board: ArtifactHash, + /// Immutable package bytes and their human-facing version. + pub package: GamePackageRef, + /// The v1 play mode. + pub mode: GameMode, + /// Package-defined configuration, carried as data. + pub configuration: serde_json::Value, + /// Authors assigned to package-defined roles. + pub participants: Vec, + /// Package-specific initial state, carried as data. + pub genesis: serde_json::Value, +} + /// Stable identity root for one public board. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] @@ -366,6 +419,8 @@ pub enum BoardObject { Tombstone(Tombstone), /// Signed portable theme. Theme(Theme), + /// Package-pinned playable game post metadata. + GamePost(GamePost), /// Signed opt-in host listing / withdrawal. BoardListing(BoardListing), } @@ -386,6 +441,7 @@ impl BoardObject { Self::Supersede(_) => "supersede", Self::Tombstone(_) => "tombstone", Self::Theme(_) => "theme", + Self::GamePost(_) => "game_post", Self::BoardListing(_) => "board_listing", } } @@ -404,6 +460,7 @@ impl BoardObject { Self::Supersede(value) => Some(&value.board), Self::Tombstone(value) => Some(&value.board), Self::BoardListing(value) => Some(&value.board), + Self::GamePost(value) => Some(&value.board), } } @@ -491,6 +548,33 @@ impl BoardObject { "duplicate theme asset reference" ); } + Self::GamePost(value) => { + validate_text("game package version", &value.package.version, false)?; + ensure!( + value.package.version.len() <= 128, + "game package version is at most 128 bytes" + ); + ensure!( + !value.participants.is_empty() + && value.participants.len() <= MAX_GAME_PARTICIPANTS, + "a game post assigns 1 to {MAX_GAME_PARTICIPANTS} participants" + ); + let mut participant_roles = BTreeSet::new(); + for participant in &value.participants { + ensure!( + is_public_key(&participant.author), + "game participant is not a canonical Ed25519 key" + ); + validate_game_role(&participant.role)?; + ensure!( + participant_roles + .insert((participant.author.as_str(), participant.role.as_str())), + "duplicate game participant (author, role) assignment" + ); + } + validate_game_data("game configuration", &value.configuration)?; + validate_game_data("game genesis state", &value.genesis)?; + } Self::BoardListing(value) => { ensure!( is_public_key(&value.host), @@ -684,9 +768,12 @@ impl BoardGraph { self.require_scoped(attachment, &value.board, "attachment")?; } if let Some(embed_ref) = &value.embed_ref { - self.require_scoped(&embed_ref.object, &value.board, "post")?; + self.require_scoped(&embed_ref.object, &value.board, "game_post")?; } } + BoardObject::GamePost(value) => { + self.require_board(&value.board)?; + } BoardObject::Attachment(value) => { self.require_board(&value.board)?; } @@ -1032,6 +1119,7 @@ impl BoardGraph { BoardObject::BoardListing(body) => std::iter::once(body.board.clone()) .chain(body.supersedes.iter().cloned()) .collect(), + BoardObject::GamePost(body) => vec![body.board.clone()], }; for dependency in dependencies { if self.objects.contains_key(&dependency) && set.insert(dependency.clone()) { @@ -1672,13 +1760,53 @@ fn validate_text(name: &str, value: &str, allow_empty: bool) -> Result<()> { Ok(()) } +struct SerializedSizeLimit { + limit: usize, + written: usize, +} + +impl Write for SerializedSizeLimit { + fn write(&mut self, buffer: &[u8]) -> io::Result { + let remaining = self.limit.saturating_sub(self.written); + let written = buffer.len().min(remaining); + self.written += written; + Ok(written) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +fn validate_game_data(name: &str, value: &serde_json::Value) -> Result<()> { + let mut writer = SerializedSizeLimit { + limit: MAX_GAME_DATA_BYTES, + written: 0, + }; + match serde_json::to_writer(&mut writer, value) { + Ok(()) => Ok(()), + Err(_) if writer.written == MAX_GAME_DATA_BYTES => { + bail!("{name} is at most {MAX_GAME_DATA_BYTES} serialized bytes") + } + Err(error) => Err(error.into()), + } +} + fn validate_token_name(value: &str) -> Result<()> { + validate_ascii_identifier("theme token name", value, 64) +} + +fn validate_game_role(value: &str) -> Result<()> { + validate_ascii_identifier("game role identifier", value, 64) +} + +fn validate_ascii_identifier(name: &str, value: &str, max_bytes: usize) -> Result<()> { ensure!( - (1..=64).contains(&value.len()) + (1..=max_bytes).contains(&value.len()) && value.bytes().all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || b"-_.".contains(&byte)), - "theme token name must be 1-64 lower-case ASCII letters, digits, '-', '_' or '.'" + "{name} must be 1-{max_bytes} lower-case ASCII letters, digits, '-', '_' or '.'" ); Ok(()) } @@ -1774,6 +1902,75 @@ mod tests { .unwrap() } + fn game_post_body( + board: ArtifactHash, + version: String, + configuration: serde_json::Value, + participants: Vec, + genesis: serde_json::Value, + ) -> GamePost { + GamePost { + board, + package: GamePackageRef { + hash: ArtifactHash::new("e".repeat(64)).unwrap(), + version, + }, + mode: GameMode::AsyncTurns, + configuration, + participants, + genesis, + } + } + + fn game_post_object( + author: &SigningKey, + opponent: &SigningKey, + board: ArtifactHash, + ) -> SignedBoardObject { + let participants = vec![ + GameParticipant { + author: hex_encode(&author.verifying_key().to_bytes()), + role: "x".to_owned(), + }, + GameParticipant { + author: hex_encode(&opponent.verifying_key().to_bytes()), + role: "o".to_owned(), + }, + ]; + SignedBoardObject::sign( + author, + 1, + "", + BoardObject::GamePost(game_post_body( + board, + "0.1.0".to_owned(), + serde_json::json!({"board_size": 3}), + participants, + serde_json::json!("---------"), + )), + ) + .unwrap() + } + + fn participant(index: usize) -> GameParticipant { + let author = key(u8::try_from(index).unwrap()); + GameParticipant { + author: hex_encode(&author.verifying_key().to_bytes()), + role: format!("role-{index}"), + } + } + + fn invalid_game_post_is_rejected_by_builder_and_receipt( + author: &SigningKey, + game: GamePost, + ) -> bool { + let typed = BoardObject::GamePost(game.clone()); + let raw = serde_json::to_value(&typed).unwrap(); + let artifact = SignedArtifact::sign(author, 1, "", BOARD_OBJECT_KIND, raw).unwrap(); + SignedBoardObject::sign(author, 1, "", typed).is_err() + && SignedBoardObject::from_artifact(artifact).is_err() + } + fn theme(key: &SigningKey, seq: u64, forked_from: Option) -> SignedBoardObject { let mut tokens = BTreeMap::new(); tokens.insert("accent".to_owned(), "#cc5500".to_owned()); @@ -1900,7 +2097,7 @@ mod tests { } #[test] - fn post_embed_ref_must_name_a_same_board_post() { + fn signed_game_post_is_verified_and_post_embed_ref_is_board_scoped() { let creator = key(6); let other = key(7); let mut graph = BoardGraph::default(); @@ -1909,6 +2106,15 @@ mod tests { .insert(thread(&creator, root_hash.clone(), "main")) .unwrap(); + let signed_game = game_post_object(&creator, &other, root_hash.clone()); + signed_game.verify().unwrap(); + let decoded = SignedBoardObject::from_artifact(signed_game.artifact.clone()).unwrap(); + assert_eq!(decoded, signed_game); + + let mut tampered = signed_game.artifact.clone(); + tampered.body["data"]["package"]["version"] = serde_json::Value::String("9.9.9".to_owned()); + assert!(SignedBoardObject::from_artifact(tampered).is_err()); + let missing = ArtifactHash::new("a".repeat(64)).unwrap(); assert!( graph @@ -1934,12 +2140,29 @@ mod tests { .is_err() ); - let foreign_root = graph.insert(board(&other)).unwrap(); - let foreign_thread = graph - .insert(thread(&other, foreign_root.clone(), "foreign")) + let ordinary_post = graph + .insert(post( + &creator, + root_hash.clone(), + thread_hash.clone(), + "not a game post", + )) .unwrap(); - let foreign_post = graph - .insert(post(&other, foreign_root, foreign_thread, "foreign target")) + assert!( + graph + .insert(post_with_embed_ref( + &creator, + root_hash.clone(), + thread_hash.clone(), + ordinary_post, + "wrong object type", + )) + .is_err() + ); + + let foreign_root = graph.insert(board(&other)).unwrap(); + let foreign_game = graph + .insert(game_post_object(&other, &creator, foreign_root.clone())) .unwrap(); assert!( graph @@ -1947,29 +2170,32 @@ mod tests { &creator, root_hash.clone(), thread_hash.clone(), - foreign_post, + foreign_game, "cross-board embed", )) .is_err() ); - let local_post = graph - .insert(post( - &creator, - root_hash.clone(), - thread_hash.clone(), - "local target", - )) - .unwrap(); - graph + let local_game = graph.insert(signed_game).unwrap(); + let embedded_post = graph .insert(post_with_embed_ref( &creator, - root_hash, + root_hash.clone(), thread_hash, - local_post, + local_game.clone(), "valid embed", )) .unwrap(); + + let mut replica = BoardGraph::default(); + let report = replica.replicate_board_from(&graph, &root_hash).unwrap(); + assert_eq!(report.status.state, ReplicaState::Complete); + assert!(replica.get(&local_game).is_some()); + let view = replica + .compose_view(&root_hash, &ViewLayers::default()) + .unwrap(); + assert!(view.objects.contains(&local_game)); + assert!(view.objects.contains(&embedded_post)); } proptest! { @@ -3510,4 +3736,122 @@ mod tests { assert_eq!(graph.len(), before); assert!(HostServingPolicy::default().serves_board(&root)); } + + proptest! { + /// Oracle: every generated in-bound GamePost must pass the builder, + /// signature verification and strict typed decode with its body intact. + #[test] + fn generated_valid_game_posts_round_trip( + seed in any::(), + participant_count in 1usize..=MAX_GAME_PARTICIPANTS, + version_len in 1usize..=128, + configuration in proptest::collection::vec(any::(), 0..32), + genesis in proptest::collection::vec(any::(), 0..64), + ) { + let game = game_post_body( + ArtifactHash::new("d".repeat(64)).unwrap(), + "v".repeat(version_len), + serde_json::json!(configuration), + (0..participant_count).map(participant).collect(), + serde_json::json!(genesis), + ); + let signed = SignedBoardObject::sign( + &key(seed), + 1, + "", + BoardObject::GamePost(game.clone()), + ).unwrap(); + prop_assert!(signed.verify().is_ok()); + prop_assert_eq!(&signed.object, &BoardObject::GamePost(game)); + prop_assert_eq!( + SignedBoardObject::from_artifact(signed.artifact.clone()).unwrap(), + signed, + ); + } + + /// Oracle: generated invalid metadata variants are refused both by the + /// builder and by typed receipt of a valid SignedArtifact envelope. + #[test] + fn generated_invalid_game_post_variants_are_rejected( + seed in any::(), + invalid_variant in 0u8..8, + ) { + let author = key(seed); + let mut invalid = game_post_body( + ArtifactHash::new("d".repeat(64)).unwrap(), + "0.1.0".to_owned(), + serde_json::json!({"seed": seed}), + vec![participant(1), participant(2)], + serde_json::json!([seed]), + ); + match invalid_variant { + 0 => invalid.participants.clear(), + 1 => invalid.participants = (0..=MAX_GAME_PARTICIPANTS).map(participant).collect(), + 2 => { + let first = invalid.participants[0].clone(); + invalid.participants[1] = first; + } + 3 => invalid.participants[0].author = "not-an-ed25519-key".to_owned(), + 4 => invalid.participants[0].role = "Player One".to_owned(), + 5 => invalid.package.version = "v".repeat(129), + 6 => { + invalid.configuration = serde_json::Value::String( + "c".repeat(MAX_GAME_DATA_BYTES - 1), + ); + } + _ => { + invalid.genesis = serde_json::Value::String( + "g".repeat(MAX_GAME_DATA_BYTES - 1), + ); + } + } + prop_assert!(invalid_game_post_is_rejected_by_builder_and_receipt( + &author, + invalid, + )); + } + } + + #[test] + fn game_post_accepts_exact_limits_and_rejects_empty_version() { + let author = key(60); + let maximum = game_post_body( + ArtifactHash::new("d".repeat(64)).unwrap(), + "v".repeat(128), + serde_json::Value::String("c".repeat(MAX_GAME_DATA_BYTES - 2)), + (0..MAX_GAME_PARTICIPANTS).map(participant).collect(), + serde_json::Value::String("g".repeat(MAX_GAME_DATA_BYTES - 2)), + ); + let signed = + SignedBoardObject::sign(&author, 1, "", BoardObject::GamePost(maximum.clone())) + .unwrap(); + assert_eq!( + SignedBoardObject::from_artifact(signed.artifact.clone()).unwrap(), + signed + ); + + let mut duplicate = maximum.clone(); + duplicate.participants[1] = duplicate.participants[0].clone(); + let duplicate_error = + SignedBoardObject::sign(&author, 2, "", BoardObject::GamePost(duplicate)).unwrap_err(); + assert!( + duplicate_error + .to_string() + .contains("duplicate game participant (author, role) assignment") + ); + + let mut invalid_role = maximum.clone(); + invalid_role.participants[0].role = "Player One".to_owned(); + let role_error = + SignedBoardObject::sign(&author, 3, "", BoardObject::GamePost(invalid_role)) + .unwrap_err(); + assert!(role_error.to_string().contains("game role identifier")); + + let mut empty_version = maximum; + empty_version.package.version.clear(); + assert!(invalid_game_post_is_rejected_by_builder_and_receipt( + &author, + empty_version, + )); + } }