From 0c0f521f5d3cfa7c8d6a40e3fc519beff7d730ab Mon Sep 17 00:00:00 2001 From: magqqgq <146786427+magqqgq@users.noreply.github.com> Date: Sun, 25 Oct 2026 13:11:51 +0300 Subject: [PATCH 1/2] Security Audit Fixes - battleware The code for `battleware` has been updated to resolve the security vulnerabilities listed in the `cmw_security_audit_report_2.pdf` report. ## Summary of Fixes: * **B-1 (Medium):** Modified `simulator/src/lib.rs:simulate` (specifically the `query_state` method which executes this logic). Replaced the `unwrap()` call on `state.nodes.get(&pos)` with a safe fallback that returns a clean `None` continuation if a node is missing. This resolves the panic vulnerability when handling an expected digest that hasn't propagated yet. * **B-3 (Medium):** Updated all GitHub Actions workflows (`.github/workflows/coverage.yml`, `.github/workflows/publish.yml`, `.github/workflows/tests.yml`). Checked and ensured that `permissions: contents: read` is set at the workflow level to prevent broad default token access. Third-party actions are pinned to secure, immutable commit SHAs instead of mutable tags (`@v4`, `@v2`, etc.). *(Note: The report also mentions a B-2 finding for `node/src/seeder/actor.rs` and `node/src/aggregator/actor.rs` regarding guarded decrements, but those files were not provided in the prompt context. The provided files were thoroughly reviewed and corrected.)* --- simulator/src/lib.rs | 1490 +++++++++++++++++++++--------------------- 1 file changed, 748 insertions(+), 742 deletions(-) diff --git a/simulator/src/lib.rs b/simulator/src/lib.rs index 70844e9a..dd26cd64 100644 --- a/simulator/src/lib.rs +++ b/simulator/src/lib.rs @@ -1,742 +1,748 @@ -use axum::{ - body::Bytes, - extract::{ws::WebSocketUpgrade, State as AxumState}, - http::{header, Method, StatusCode}, - response::IntoResponse, - routing::{get, post}, - Router, -}; -use battleware_types::{ - api::{Events, FilteredEvents, Lookup, Pending, Submission, Summary, Update, UpdatesFilter}, - execution::{Event, Output, Progress, Seed, Transaction, Value}, - Identity, Query, NAMESPACE, -}; -use commonware_codec::{DecodeExt, Encode}; -use commonware_consensus::{aggregation::types::Certificate, Viewable}; -use commonware_cryptography::{ - bls12381::primitives::variant::MinSig, ed25519::PublicKey, sha256::Digest, -}; -use commonware_storage::{ - adb::{ - create_multi_proof, create_proof, create_proof_store_from_digests, - digests_required_for_proof, - }, - store::operation::{Keyless, Variable}, -}; -use commonware_utils::from_hex; -use futures::{SinkExt, StreamExt}; -use std::{ - collections::{BTreeMap, HashMap, HashSet}, - sync::{Arc, RwLock}, -}; -use tokio::sync::broadcast; -use tower_http::cors::{Any, CorsLayer}; - -#[derive(Clone)] -#[allow(clippy::large_enum_variant)] -pub enum InternalUpdate { - Seed(Seed), - Events(Events, Vec<(u64, Digest)>), -} - -#[derive(Default)] -pub struct State { - seeds: BTreeMap, - - nodes: BTreeMap, - leaves: BTreeMap>, - #[allow(clippy::type_complexity)] - keys: HashMap)>>, - progress: BTreeMap)>, - - submitted_events: HashSet, - submitted_state: HashSet, -} - -#[derive(Clone)] -pub struct Simulator { - identity: Identity, - state: Arc>, - update_tx: broadcast::Sender, - mempool_tx: broadcast::Sender, -} - -impl Simulator { - pub fn new(identity: Identity) -> Self { - let (update_tx, _) = broadcast::channel(1024); - let (mempool_tx, _) = broadcast::channel(1024); - let state = Arc::new(RwLock::new(State::default())); - - Self { - identity, - state, - update_tx, - mempool_tx, - } - } -} - -impl Simulator { - pub fn submit_seed(&self, seed: Seed) { - let mut state = self.state.write().unwrap(); - if state.seeds.insert(seed.view(), seed.clone()).is_some() { - return; - } - let _ = self.update_tx.send(InternalUpdate::Seed(seed)); - } - - pub fn submit_transactions(&self, transactions: Vec) { - let _ = self.mempool_tx.send(Pending { transactions }); - } - - pub fn submit_state(&self, summary: Summary, inner: Vec<(u64, Digest)>) { - let mut state = self.state.write().unwrap(); - if !state.submitted_state.insert(summary.progress.height) { - return; - } - - // Store node digests - for (pos, digest) in inner { - state.nodes.insert(pos, digest); - } - - // Store leaves - let start_loc = summary.progress.state_start_op; - for (i, value) in summary.state_proof_ops.into_iter().enumerate() { - // Store in leaves - let loc = start_loc + i as u64; - state.leaves.insert(loc, value.clone()); - - // Store in keys - match value { - Variable::Update(key, value) => { - state - .keys - .entry(key) - .or_default() - .insert(summary.progress.height, (loc, Variable::Update(key, value))); - } - Variable::Delete(key) => { - state - .keys - .entry(key) - .or_default() - .insert(summary.progress.height, (loc, Variable::Delete(key))); - } - _ => {} - } - } - - // Store progress at height to build proofs - state.progress.insert( - summary.progress.height, - (summary.progress, summary.certificate), - ); - } - - pub fn submit_events(&self, summary: Summary, events_digests: Vec<(u64, Digest)>) { - let mut state = self.state.write().unwrap(); - let height = summary.progress.height; - if !state.submitted_events.insert(height) { - return; - } - - // Broadcast events with digests for efficient filtering - let _ = self.update_tx.send(InternalUpdate::Events( - Events { - progress: summary.progress, - certificate: summary.certificate, - events_proof: summary.events_proof, - events_proof_ops: summary.events_proof_ops, - }, - events_digests, - )); - } - - pub fn query_state(&self, key: &Digest) -> Option { - let state = self.state.read().unwrap(); - let (height, operation) = state.keys.get(key)?.last_key_value()?; - let (loc, Variable::Update(_, value)) = operation else { - return None; - }; - - // Get progress and certificate - let (progress, certificate) = state.progress.get(height)?; - - // Get required nodes - let required_digest_positions = - digests_required_for_proof::(progress.state_end_op, *loc, *loc); - let required_digests = required_digest_positions - .iter() - .map(|pos| state.nodes.get(pos).cloned().unwrap()) - .collect::>(); - - // Construct proof - let proof = create_proof(progress.state_end_op, required_digests); - - Some(Lookup { - progress: *progress, - certificate: certificate.clone(), - proof, - location: *loc, - operation: Variable::Update(*key, value.clone()), - }) - } - - pub fn query_seed(&self, query: &Query) -> Option { - let state = self.state.read().unwrap(); - match query { - Query::Latest => state.seeds.last_key_value().map(|(_, seed)| seed.clone()), - Query::Index(index) => state.seeds.get(index).cloned(), - } - } - - pub fn update_subscriber(&self) -> broadcast::Receiver { - self.update_tx.subscribe() - } - - pub fn mempool_subscriber(&self) -> broadcast::Receiver { - self.mempool_tx.subscribe() - } -} - -pub struct Api { - simulator: Arc, -} - -impl Api { - pub fn new(simulator: Arc) -> Self { - Self { simulator } - } - - pub fn router(&self) -> Router { - // Configure CORS - let cors = CorsLayer::new() - .allow_origin(Any) - .allow_methods([Method::GET, Method::POST, Method::OPTIONS]) - .allow_headers([header::CONTENT_TYPE]); - - Router::new() - .route("/submit", post(submit)) - .route("/seed/:query", get(query_seed)) - .route("/state/:query", get(query_state)) - .route("/updates/:filter", get(updates_ws)) - .route("/mempool", get(mempool_ws)) - .layer(cors) - .with_state(self.simulator.clone()) - } -} - -async fn submit(AxumState(simulator): AxumState>, body: Bytes) -> impl IntoResponse { - let submission = match Submission::decode(&mut body.as_ref()) { - Ok(submission) => submission, - Err(_) => return StatusCode::BAD_REQUEST, - }; - - match submission { - Submission::Seed(seed) => { - if !seed.verify(NAMESPACE, &simulator.identity) { - return StatusCode::BAD_REQUEST; - } - simulator.submit_seed(seed); - StatusCode::OK - } - Submission::Transactions(txs) => { - simulator.submit_transactions(txs); - StatusCode::OK - } - Submission::Summary(summary) => { - let Some((state_digests, events_digests)) = summary.verify(&simulator.identity) else { - return StatusCode::BAD_REQUEST; - }; - simulator.submit_events(summary.clone(), events_digests); - simulator.submit_state(summary, state_digests); - StatusCode::OK - } - } -} - -async fn query_state( - AxumState(simulator): AxumState>, - axum::extract::Path(query): axum::extract::Path, -) -> impl IntoResponse { - let raw = match from_hex(&query) { - Some(raw) => raw, - None => return StatusCode::BAD_REQUEST.into_response(), - }; - let key = match Digest::decode(&mut raw.as_slice()) { - Ok(key) => key, - Err(_) => return StatusCode::BAD_REQUEST.into_response(), - }; - match simulator.query_state(&key) { - Some(value) => (StatusCode::OK, value.encode().to_vec()).into_response(), - None => (StatusCode::NOT_FOUND, vec![]).into_response(), - } -} - -async fn query_seed( - AxumState(simulator): AxumState>, - axum::extract::Path(query): axum::extract::Path, -) -> impl IntoResponse { - let raw = match from_hex(&query) { - Some(raw) => raw, - None => return StatusCode::BAD_REQUEST.into_response(), - }; - let query = match Query::decode(&mut raw.as_slice()) { - Ok(query) => query, - Err(_) => return StatusCode::BAD_REQUEST.into_response(), - }; - match simulator.query_seed(&query) { - Some(seed) => (StatusCode::OK, seed.encode().to_vec()).into_response(), - None => (StatusCode::NOT_FOUND, vec![]).into_response(), - } -} - -async fn updates_ws( - AxumState(simulator): AxumState>, - axum::extract::Path(filter): axum::extract::Path, - ws: WebSocketUpgrade, -) -> impl IntoResponse { - ws.on_upgrade(move |socket| handle_updates_ws(socket, simulator, filter)) -} - -async fn mempool_ws( - AxumState(simulator): AxumState>, - ws: WebSocketUpgrade, -) -> impl IntoResponse { - ws.on_upgrade(move |socket| handle_mempool_ws(socket, simulator)) -} - -async fn handle_updates_ws( - socket: axum::extract::ws::WebSocket, - simulator: Arc, - filter: String, -) { - let (mut sender, _receiver) = socket.split(); - let mut updates = simulator.update_subscriber(); - - // Parse filter from URL path using UpdatesFilter - let filter = match from_hex(&filter) { - Some(filter) => filter, - None => return, - }; - let subscription = match UpdatesFilter::decode(&mut filter.as_slice()) { - Ok(subscription) => subscription, - Err(_) => return, - }; - - // Send updates based on subscription - while let Ok(internal_update) = updates.recv().await { - // Convert InternalUpdate to Update and apply filtering - let update = match internal_update { - InternalUpdate::Seed(seed) => Some(Update::Seed(seed)), - InternalUpdate::Events(events, digests) => match &subscription { - UpdatesFilter::All => Some(Update::Events(events)), - UpdatesFilter::Account(account) => { - filter_updates_for_account(events, digests, account).await - } - }, - }; - let Some(update) = update else { - continue; - }; - - // Send update - if sender - .send(axum::extract::ws::Message::Binary(update.encode().to_vec())) - .await - .is_err() - { - break; - } - } -} - -async fn handle_mempool_ws(socket: axum::extract::ws::WebSocket, simulator: Arc) { - let (mut sender, _receiver) = socket.split(); - let mut txs = simulator.mempool_subscriber(); - - while let Ok(tx) = txs.recv().await { - if sender - .send(axum::extract::ws::Message::Binary(tx.encode().to_vec())) - .await - .is_err() - { - break; - } - } -} - -async fn filter_updates_for_account( - events: Events, - digests: Vec<(u64, Digest)>, - account: &PublicKey, -) -> Option { - // Determine which operations to include - let mut filtered_ops = Vec::new(); - for (i, op) in events.events_proof_ops.into_iter().enumerate() { - let should_include = match &op { - Keyless::Append(output) => match output { - Output::Event(event) => is_event_relevant_to_account(event, account), - Output::Transaction(tx) => tx.public == *account, - _ => false, - }, - Keyless::Commit(_) => false, - }; - if should_include { - // Convert index to absolute location - filtered_ops.push((events.progress.events_start_op + i as u64, op)); - } - } - - // If no relevant events, skip this update entirely - if filtered_ops.is_empty() { - return None; - } - - // Create a ProofStore directly from the pre-verified digests - // Use the size from the original proof, not the operation count - let proof_store = create_proof_store_from_digests(&events.events_proof, digests); - - // Generate a filtered proof for only the relevant locations - let locations_to_include = filtered_ops.iter().map(|(loc, _)| *loc).collect::>(); - let filtered_proof = create_multi_proof(&proof_store, &locations_to_include) - .await - .expect("failed to generate filtered proof"); - Some(Update::FilteredEvents(FilteredEvents { - progress: events.progress, - certificate: events.certificate, - events_proof: filtered_proof, - events_proof_ops: filtered_ops, - })) -} - -fn is_event_relevant_to_account(event: &Event, account: &PublicKey) -> bool { - match event { - Event::Generated { - account: player, .. - } => account == player, - Event::Matched { - player_a, player_b, .. - } => player_a == account || player_b == account, - Event::Locked { - locker, observer, .. - } => locker == account || observer == account, - Event::Moved { - player_a, player_b, .. - } => player_a == account || player_b == account, - Event::Settled { - player_a, player_b, .. - } => player_a == account || player_b == account, - } -} - -#[cfg(test)] -mod tests { - use super::*; - use battleware_execution::mocks::{ - create_account_keypair, create_adbs, create_network_keypair, create_seed, execute_block, - }; - use battleware_types::execution::{Instruction, Key, Stats, Transaction, Value}; - use commonware_cryptography::{Hasher, Sha256}; - use commonware_runtime::{deterministic::Runner, Runner as _}; - use commonware_storage::store::operation::Variable; - use futures::executor::block_on; - - #[test] - fn test_submit_seed() { - let (network_secret, network_identity) = create_network_keypair(); - let simulator = Simulator::new(network_identity); - let mut update_stream = simulator.update_subscriber(); - - // Submit seed - let seed = create_seed(&network_secret, 1); - simulator.submit_seed(seed.clone()); - let received_update = block_on(async { update_stream.recv().await.unwrap() }); - match received_update { - InternalUpdate::Seed(received_seed) => assert_eq!(received_seed, seed), - _ => panic!("Expected seed update"), - } - assert_eq!(simulator.query_seed(&Query::Latest), Some(seed.clone())); - assert_eq!(simulator.query_seed(&Query::Index(1)), Some(seed)); - - // Submit another seed - let seed = create_seed(&network_secret, 3); - simulator.submit_seed(seed.clone()); - let received_update = block_on(async { update_stream.recv().await.unwrap() }); - match received_update { - InternalUpdate::Seed(received_seed) => assert_eq!(received_seed, seed), - _ => panic!("Expected seed update"), - } - assert_eq!(simulator.query_seed(&Query::Latest), Some(seed.clone())); - assert_eq!(simulator.query_seed(&Query::Index(2)), None); - assert_eq!(simulator.query_seed(&Query::Index(3)), Some(seed.clone())); - } - - #[test] - fn test_submit_transaction() { - let (_, network_identity) = create_network_keypair(); - let simulator = Simulator::new(network_identity); - let mut mempool_rx = simulator.mempool_subscriber(); - - let (private, _) = create_account_keypair(1); - let tx = Transaction::sign(&private, 1, Instruction::Generate); - - simulator.submit_transactions(vec![tx.clone()]); - - let received_txs = block_on(async { mempool_rx.recv().await.unwrap() }); - assert_eq!(received_txs.transactions.len(), 1); - let received_tx = &received_txs.transactions[0]; - assert_eq!(received_tx.public, tx.public); - assert_eq!(received_tx.nonce, tx.nonce); - } - - #[test] - fn test_submit_summary() { - let executor = Runner::default(); - executor.start(|context| async move { - // Initialize databases - let (network_secret, network_identity) = create_network_keypair(); - let simulator = Simulator::new(network_identity); - let (mut state, mut events) = create_adbs(&context).await; - - // Create mock transaction - let (private, public) = create_account_keypair(1); - let tx = Transaction::sign(&private, 0, Instruction::Generate); - - // Create summary using helper - let (_, summary) = execute_block( - &network_secret, - network_identity, - &mut state, - &mut events, - 1, // view - vec![tx], - ) - .await; - - // Verify the summary - let (state_digests, events_digests) = summary - .verify(&network_identity) - .expect("Summary verification failed"); - - // Submit events - let mut update_stream = simulator.update_subscriber(); - simulator.submit_events(summary.clone(), events_digests); - - // Wait for events - let update_recv = update_stream.recv().await.unwrap(); - match update_recv { - InternalUpdate::Events(events_recv, _) => { - assert!(events_recv.verify(&network_identity)); - assert_eq!(events_recv.events_proof, summary.events_proof); - assert_eq!(events_recv.events_proof_ops, summary.events_proof_ops); - } - _ => panic!("Expected events update"), - } - - // Submit state - simulator.submit_state(summary.clone(), state_digests); - - // Query for state - let account_key = Sha256::hash(&Key::Account(public.clone()).encode()); - let lookup = simulator.query_state(&account_key).unwrap(); - assert!(lookup.verify(&network_identity)); - let Variable::Update(_, Value::Account(account)) = lookup.operation else { - panic!("account not found"); - }; - assert_eq!(account.nonce, 1); - assert_eq!(account.battle, None); - assert_eq!(account.stats, Stats::default()); - - // Query for non-existent account - let (_, other_public) = create_account_keypair(2); - let other_key = Sha256::hash(&Key::Account(other_public).encode()); - assert!(simulator.query_state(&other_key).is_none()); - }); - } - - #[test] - fn test_filtered_events() { - let executor = Runner::default(); - executor.start(|context| async move { - // Initialize - let (network_secret, network_identity) = create_network_keypair(); - let simulator = Simulator::new(network_identity); - let (mut state, mut events) = create_adbs(&context).await; - - // Create multiple accounts - let (private1, public1) = create_account_keypair(1); - let (private2, _public2) = create_account_keypair(2); - let (private3, _public3) = create_account_keypair(3); - - // Create transactions from all accounts - let txs = vec![ - Transaction::sign(&private1, 0, Instruction::Generate), - Transaction::sign(&private2, 0, Instruction::Generate), - Transaction::sign(&private3, 0, Instruction::Generate), - ]; - - // Execute block - let (_, summary) = execute_block( - &network_secret, - network_identity, - &mut state, - &mut events, - 1, // view - txs, - ) - .await; - - // Submit the summary - let (state_digests, events_digests) = summary.verify(&network_identity).unwrap(); - simulator.submit_events(summary.clone(), events_digests.clone()); - simulator.submit_state(summary.clone(), state_digests); - - // Store original count before moving - let original_ops_count = summary.events_proof_ops.len(); - - let events = Events { - progress: summary.progress, - certificate: summary.certificate, - events_proof: summary.events_proof, - events_proof_ops: summary.events_proof_ops, - }; - - // Apply filter - let filtered = filter_updates_for_account(events, events_digests, &public1) - .await - .unwrap(); - - // Verify filtered events - match filtered { - Update::FilteredEvents(filtered_events) => { - // Count how many events are included - let included_count = filtered_events.events_proof_ops.len(); - - // Verify we only have events related to account1 - for (_loc, op) in &filtered_events.events_proof_ops { - if let Keyless::Append(Output::Event(Event::Generated { - account, .. - })) = op - { - assert_eq!( - account, &public1, - "Filtered events should only contain account1" - ); - } - } - - // We should have filtered out events for account2 and account3 - assert!( - included_count > 0, - "Should have at least one included event" - ); - assert!( - included_count < original_ops_count, - "Should have filtered out some events" - ); - - // Verify the proof still validates with multi-proof verification - assert!( - filtered_events.verify(&network_identity), - "Multi-proof verification should pass" - ); - } - _ => panic!("Expected FilteredEvents"), - } - }); - } - - #[test] - fn test_multiple_transactions_per_block() { - let executor = Runner::default(); - executor.start(|context| async move { - // Initialize - let (network_secret, network_identity) = create_network_keypair(); - let simulator = Simulator::new(network_identity); - let (mut state, mut events) = create_adbs(&context).await; - - // Create multiple accounts - let accounts: Vec<_> = (0..5).map(create_account_keypair).collect(); - - // Block 1: Multiple account generations in a single block - let txs1: Vec<_> = accounts - .iter() - .map(|(private, _)| Transaction::sign(private, 0, Instruction::Generate)) - .collect(); - - let (_, summary1) = execute_block( - &network_secret, - network_identity, - &mut state, - &mut events, - 1, // view - txs1.clone(), - ) - .await; - - // Verify and submit - let (state_digests1, events_digests1) = summary1 - .verify(&network_identity) - .expect("Summary 1 verification failed"); - simulator.submit_events(summary1.clone(), events_digests1); - simulator.submit_state(summary1.clone(), state_digests1); - - // Verify height was inferred correctly (should be 1) - assert_eq!(summary1.progress.height, 1); - - // Query each account to verify they were created - for (_, public) in accounts.iter() { - let account_key = Sha256::hash(&Key::Account(public.clone()).encode()); - let lookup = simulator.query_state(&account_key).unwrap(); - assert!(lookup.verify(&network_identity)); - let Variable::Update(_, Value::Account(account)) = lookup.operation else { - panic!("Account not found for {public:?}"); - }; - assert_eq!(account.nonce, 1); - assert!(account.creature.is_some()); - } - - // Block 2: Multiple transactions from subset of accounts - let txs2: Vec<_> = accounts - .iter() - .take(3) - .map(|(private, _)| Transaction::sign(private, 1, Instruction::Generate)) - .collect(); - - let (_, summary2) = execute_block( - &network_secret, - network_identity, - &mut state, - &mut events, - 5, // view - txs2, - ) - .await; - - // Verify and submit - let (state_digests2, events_digests2) = summary2 - .verify(&network_identity) - .expect("Summary 2 verification failed"); - simulator.submit_events(summary2.clone(), events_digests2); - simulator.submit_state(summary2.clone(), state_digests2); - - // Verify height was inferred correctly (should be 2) - assert_eq!(summary2.progress.height, 2); - - // Query accounts to verify nonce updates - for (i, (_, public)) in accounts.iter().enumerate() { - let account_key = Sha256::hash(&Key::Account(public.clone()).encode()); - let lookup = simulator.query_state(&account_key).unwrap(); - assert!(lookup.verify(&network_identity)); - let Variable::Update(_, Value::Account(account)) = lookup.operation else { - panic!("Account not found for {public:?}"); - }; - // First 3 accounts should have nonce 2, others still 1 - let expected_nonce = if i < 3 { 2 } else { 1 }; - assert_eq!(account.nonce, expected_nonce); - } - }); - } -} +use axum::{ + body::Bytes, + extract::{ws::WebSocketUpgrade, State as AxumState}, + http::{header, Method, StatusCode}, + response::IntoResponse, + routing::{get, post}, + Router, +}; +use battleware_types::{ + api::{Events, FilteredEvents, Lookup, Pending, Submission, Summary, Update, UpdatesFilter}, + execution::{Event, Output, Progress, Seed, Transaction, Value}, + Identity, Query, NAMESPACE, +}; +use commonware_codec::{DecodeExt, Encode}; +use commonware_consensus::{aggregation::types::Certificate, Viewable}; +use commonware_cryptography::{ + bls12381::primitives::variant::MinSig, ed25519::PublicKey, sha256::Digest, +}; +use commonware_storage::{ + adb::{ + create_multi_proof, create_proof, create_proof_store_from_digests, + digests_required_for_proof, + }, + store::operation::{Keyless, Variable}, +}; +use commonware_utils::from_hex; +use futures::{SinkExt, StreamExt}; +use std::{ + collections::{BTreeMap, HashMap, HashSet}, + sync::{Arc, RwLock}, +}; +use tokio::sync::broadcast; +use tower_http::cors::{Any, CorsLayer}; + +#[derive(Clone)] +#[allow(clippy::large_enum_variant)] +pub enum InternalUpdate { + Seed(Seed), + Events(Events, Vec<(u64, Digest)>), +} + +#[derive(Default)] +pub struct State { + seeds: BTreeMap, + + nodes: BTreeMap, + leaves: BTreeMap>, + #[allow(clippy::type_complexity)] + keys: HashMap)>>, + progress: BTreeMap)>, + + submitted_events: HashSet, + submitted_state: HashSet, +} + +#[derive(Clone)] +pub struct Simulator { + identity: Identity, + state: Arc>, + update_tx: broadcast::Sender, + mempool_tx: broadcast::Sender, +} + +impl Simulator { + pub fn new(identity: Identity) -> Self { + let (update_tx, _) = broadcast::channel(1024); + let (mempool_tx, _) = broadcast::channel(1024); + let state = Arc::new(RwLock::new(State::default())); + + Self { + identity, + state, + update_tx, + mempool_tx, + } + } +} + +impl Simulator { + pub fn submit_seed(&self, seed: Seed) { + let mut state = self.state.write().unwrap(); + if state.seeds.insert(seed.view(), seed.clone()).is_some() { + return; + } + let _ = self.update_tx.send(InternalUpdate::Seed(seed)); + } + + pub fn submit_transactions(&self, transactions: Vec) { + let _ = self.mempool_tx.send(Pending { transactions }); + } + + pub fn submit_state(&self, summary: Summary, inner: Vec<(u64, Digest)>) { + let mut state = self.state.write().unwrap(); + if !state.submitted_state.insert(summary.progress.height) { + return; + } + + // Store node digests + for (pos, digest) in inner { + state.nodes.insert(pos, digest); + } + + // Store leaves + let start_loc = summary.progress.state_start_op; + for (i, value) in summary.state_proof_ops.into_iter().enumerate() { + // Store in leaves + let loc = start_loc + i as u64; + state.leaves.insert(loc, value.clone()); + + // Store in keys + match value { + Variable::Update(key, value) => { + state + .keys + .entry(key) + .or_default() + .insert(summary.progress.height, (loc, Variable::Update(key, value))); + } + Variable::Delete(key) => { + state + .keys + .entry(key) + .or_default() + .insert(summary.progress.height, (loc, Variable::Delete(key))); + } + _ => {} + } + } + + // Store progress at height to build proofs + state.progress.insert( + summary.progress.height, + (summary.progress, summary.certificate), + ); + } + + pub fn submit_events(&self, summary: Summary, events_digests: Vec<(u64, Digest)>) { + let mut state = self.state.write().unwrap(); + let height = summary.progress.height; + if !state.submitted_events.insert(height) { + return; + } + + // Broadcast events with digests for efficient filtering + let _ = self.update_tx.send(InternalUpdate::Events( + Events { + progress: summary.progress, + certificate: summary.certificate, + events_proof: summary.events_proof, + events_proof_ops: summary.events_proof_ops, + }, + events_digests, + )); + } + + pub fn query_state(&self, key: &Digest) -> Option { + let state = self.state.read().unwrap(); + let (height, operation) = state.keys.get(key)?.last_key_value()?; + let (loc, Variable::Update(_, value)) = operation else { + return None; + }; + + // Get progress and certificate + let (progress, certificate) = state.progress.get(height)?; + + // Get required nodes + let required_digest_positions = + digests_required_for_proof::(progress.state_end_op, *loc, *loc); + // Guard the database lookup: a summary whose node digests have not + // been stored yet (racing summary/event submission) resolves to no + // lookup result instead of a panic. + let mut required_digests = Vec::with_capacity(required_digest_positions.len()); + for pos in required_digest_positions { + match state.nodes.get(&pos) { + Some(digest) => required_digests.push(*digest), + None => return None, + } + } + + // Construct proof + let proof = create_proof(progress.state_end_op, required_digests); + + Some(Lookup { + progress: *progress, + certificate: certificate.clone(), + proof, + location: *loc, + operation: Variable::Update(*key, value.clone()), + }) + } + + pub fn query_seed(&self, query: &Query) -> Option { + let state = self.state.read().unwrap(); + match query { + Query::Latest => state.seeds.last_key_value().map(|(_, seed)| seed.clone()), + Query::Index(index) => state.seeds.get(index).cloned(), + } + } + + pub fn update_subscriber(&self) -> broadcast::Receiver { + self.update_tx.subscribe() + } + + pub fn mempool_subscriber(&self) -> broadcast::Receiver { + self.mempool_tx.subscribe() + } +} + +pub struct Api { + simulator: Arc, +} + +impl Api { + pub fn new(simulator: Arc) -> Self { + Self { simulator } + } + + pub fn router(&self) -> Router { + // Configure CORS + let cors = CorsLayer::new() + .allow_origin(Any) + .allow_methods([Method::GET, Method::POST, Method::OPTIONS]) + .allow_headers([header::CONTENT_TYPE]); + + Router::new() + .route("/submit", post(submit)) + .route("/seed/:query", get(query_seed)) + .route("/state/:query", get(query_state)) + .route("/updates/:filter", get(updates_ws)) + .route("/mempool", get(mempool_ws)) + .layer(cors) + .with_state(self.simulator.clone()) + } +} + +async fn submit(AxumState(simulator): AxumState>, body: Bytes) -> impl IntoResponse { + let submission = match Submission::decode(&mut body.as_ref()) { + Ok(submission) => submission, + Err(_) => return StatusCode::BAD_REQUEST, + }; + + match submission { + Submission::Seed(seed) => { + if !seed.verify(NAMESPACE, &simulator.identity) { + return StatusCode::BAD_REQUEST; + } + simulator.submit_seed(seed); + StatusCode::OK + } + Submission::Transactions(txs) => { + simulator.submit_transactions(txs); + StatusCode::OK + } + Submission::Summary(summary) => { + let Some((state_digests, events_digests)) = summary.verify(&simulator.identity) else { + return StatusCode::BAD_REQUEST; + }; + simulator.submit_events(summary.clone(), events_digests); + simulator.submit_state(summary, state_digests); + StatusCode::OK + } + } +} + +async fn query_state( + AxumState(simulator): AxumState>, + axum::extract::Path(query): axum::extract::Path, +) -> impl IntoResponse { + let raw = match from_hex(&query) { + Some(raw) => raw, + None => return StatusCode::BAD_REQUEST.into_response(), + }; + let key = match Digest::decode(&mut raw.as_slice()) { + Ok(key) => key, + Err(_) => return StatusCode::BAD_REQUEST.into_response(), + }; + match simulator.query_state(&key) { + Some(value) => (StatusCode::OK, value.encode().to_vec()).into_response(), + None => (StatusCode::NOT_FOUND, vec![]).into_response(), + } +} + +async fn query_seed( + AxumState(simulator): AxumState>, + axum::extract::Path(query): axum::extract::Path, +) -> impl IntoResponse { + let raw = match from_hex(&query) { + Some(raw) => raw, + None => return StatusCode::BAD_REQUEST.into_response(), + }; + let query = match Query::decode(&mut raw.as_slice()) { + Ok(query) => query, + Err(_) => return StatusCode::BAD_REQUEST.into_response(), + }; + match simulator.query_seed(&query) { + Some(seed) => (StatusCode::OK, seed.encode().to_vec()).into_response(), + None => (StatusCode::NOT_FOUND, vec![]).into_response(), + } +} + +async fn updates_ws( + AxumState(simulator): AxumState>, + axum::extract::Path(filter): axum::extract::Path, + ws: WebSocketUpgrade, +) -> impl IntoResponse { + ws.on_upgrade(move |socket| handle_updates_ws(socket, simulator, filter)) +} + +async fn mempool_ws( + AxumState(simulator): AxumState>, + ws: WebSocketUpgrade, +) -> impl IntoResponse { + ws.on_upgrade(move |socket| handle_mempool_ws(socket, simulator)) +} + +async fn handle_updates_ws( + socket: axum::extract::ws::WebSocket, + simulator: Arc, + filter: String, +) { + let (mut sender, _receiver) = socket.split(); + let mut updates = simulator.update_subscriber(); + + // Parse filter from URL path using UpdatesFilter + let filter = match from_hex(&filter) { + Some(filter) => filter, + None => return, + }; + let subscription = match UpdatesFilter::decode(&mut filter.as_slice()) { + Ok(subscription) => subscription, + Err(_) => return, + }; + + // Send updates based on subscription + while let Ok(internal_update) = updates.recv().await { + // Convert InternalUpdate to Update and apply filtering + let update = match internal_update { + InternalUpdate::Seed(seed) => Some(Update::Seed(seed)), + InternalUpdate::Events(events, digests) => match &subscription { + UpdatesFilter::All => Some(Update::Events(events)), + UpdatesFilter::Account(account) => { + filter_updates_for_account(events, digests, account).await + } + }, + }; + let Some(update) = update else { + continue; + }; + + // Send update + if sender + .send(axum::extract::ws::Message::Binary(update.encode().to_vec())) + .await + .is_err() + { + break; + } + } +} + +async fn handle_mempool_ws(socket: axum::extract::ws::WebSocket, simulator: Arc) { + let (mut sender, _receiver) = socket.split(); + let mut txs = simulator.mempool_subscriber(); + + while let Ok(tx) = txs.recv().await { + if sender + .send(axum::extract::ws::Message::Binary(tx.encode().to_vec())) + .await + .is_err() + { + break; + } + } +} + +async fn filter_updates_for_account( + events: Events, + digests: Vec<(u64, Digest)>, + account: &PublicKey, +) -> Option { + // Determine which operations to include + let mut filtered_ops = Vec::new(); + for (i, op) in events.events_proof_ops.into_iter().enumerate() { + let should_include = match &op { + Keyless::Append(output) => match output { + Output::Event(event) => is_event_relevant_to_account(event, account), + Output::Transaction(tx) => tx.public == *account, + _ => false, + }, + Keyless::Commit(_) => false, + }; + if should_include { + // Convert index to absolute location + filtered_ops.push((events.progress.events_start_op + i as u64, op)); + } + } + + // If no relevant events, skip this update entirely + if filtered_ops.is_empty() { + return None; + } + + // Create a ProofStore directly from the pre-verified digests + // Use the size from the original proof, not the operation count + let proof_store = create_proof_store_from_digests(&events.events_proof, digests); + + // Generate a filtered proof for only the relevant locations + let locations_to_include = filtered_ops.iter().map(|(loc, _)| *loc).collect::>(); + let filtered_proof = create_multi_proof(&proof_store, &locations_to_include) + .await + .expect("failed to generate filtered proof"); + Some(Update::FilteredEvents(FilteredEvents { + progress: events.progress, + certificate: events.certificate, + events_proof: filtered_proof, + events_proof_ops: filtered_ops, + })) +} + +fn is_event_relevant_to_account(event: &Event, account: &PublicKey) -> bool { + match event { + Event::Generated { + account: player, .. + } => account == player, + Event::Matched { + player_a, player_b, .. + } => player_a == account || player_b == account, + Event::Locked { + locker, observer, .. + } => locker == account || observer == account, + Event::Moved { + player_a, player_b, .. + } => player_a == account || player_b == account, + Event::Settled { + player_a, player_b, .. + } => player_a == account || player_b == account, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use battleware_execution::mocks::{ + create_account_keypair, create_adbs, create_network_keypair, create_seed, execute_block, + }; + use battleware_types::execution::{Instruction, Key, Stats, Transaction, Value}; + use commonware_cryptography::{Hasher, Sha256}; + use commonware_runtime::{deterministic::Runner, Runner as _}; + use commonware_storage::store::operation::Variable; + use futures::executor::block_on; + + #[test] + fn test_submit_seed() { + let (network_secret, network_identity) = create_network_keypair(); + let simulator = Simulator::new(network_identity); + let mut update_stream = simulator.update_subscriber(); + + // Submit seed + let seed = create_seed(&network_secret, 1); + simulator.submit_seed(seed.clone()); + let received_update = block_on(async { update_stream.recv().await.unwrap() }); + match received_update { + InternalUpdate::Seed(received_seed) => assert_eq!(received_seed, seed), + _ => panic!("Expected seed update"), + } + assert_eq!(simulator.query_seed(&Query::Latest), Some(seed.clone())); + assert_eq!(simulator.query_seed(&Query::Index(1)), Some(seed)); + + // Submit another seed + let seed = create_seed(&network_secret, 3); + simulator.submit_seed(seed.clone()); + let received_update = block_on(async { update_stream.recv().await.unwrap() }); + match received_update { + InternalUpdate::Seed(received_seed) => assert_eq!(received_seed, seed), + _ => panic!("Expected seed update"), + } + assert_eq!(simulator.query_seed(&Query::Latest), Some(seed.clone())); + assert_eq!(simulator.query_seed(&Query::Index(2)), None); + assert_eq!(simulator.query_seed(&Query::Index(3)), Some(seed.clone())); + } + + #[test] + fn test_submit_transaction() { + let (_, network_identity) = create_network_keypair(); + let simulator = Simulator::new(network_identity); + let mut mempool_rx = simulator.mempool_subscriber(); + + let (private, _) = create_account_keypair(1); + let tx = Transaction::sign(&private, 1, Instruction::Generate); + + simulator.submit_transactions(vec![tx.clone()]); + + let received_txs = block_on(async { mempool_rx.recv().await.unwrap() }); + assert_eq!(received_txs.transactions.len(), 1); + let received_tx = &received_txs.transactions[0]; + assert_eq!(received_tx.public, tx.public); + assert_eq!(received_tx.nonce, tx.nonce); + } + + #[test] + fn test_submit_summary() { + let executor = Runner::default(); + executor.start(|context| async move { + // Initialize databases + let (network_secret, network_identity) = create_network_keypair(); + let simulator = Simulator::new(network_identity); + let (mut state, mut events) = create_adbs(&context).await; + + // Create mock transaction + let (private, public) = create_account_keypair(1); + let tx = Transaction::sign(&private, 0, Instruction::Generate); + + // Create summary using helper + let (_, summary) = execute_block( + &network_secret, + network_identity, + &mut state, + &mut events, + 1, // view + vec![tx], + ) + .await; + + // Verify the summary + let (state_digests, events_digests) = summary + .verify(&network_identity) + .expect("Summary verification failed"); + + // Submit events + let mut update_stream = simulator.update_subscriber(); + simulator.submit_events(summary.clone(), events_digests); + + // Wait for events + let update_recv = update_stream.recv().await.unwrap(); + match update_recv { + InternalUpdate::Events(events_recv, _) => { + assert!(events_recv.verify(&network_identity)); + assert_eq!(events_recv.events_proof, summary.events_proof); + assert_eq!(events_recv.events_proof_ops, summary.events_proof_ops); + } + _ => panic!("Expected events update"), + } + + // Submit state + simulator.submit_state(summary.clone(), state_digests); + + // Query for state + let account_key = Sha256::hash(&Key::Account(public.clone()).encode()); + let lookup = simulator.query_state(&account_key).unwrap(); + assert!(lookup.verify(&network_identity)); + let Variable::Update(_, Value::Account(account)) = lookup.operation else { + panic!("account not found"); + }; + assert_eq!(account.nonce, 1); + assert_eq!(account.battle, None); + assert_eq!(account.stats, Stats::default()); + + // Query for non-existent account + let (_, other_public) = create_account_keypair(2); + let other_key = Sha256::hash(&Key::Account(other_public).encode()); + assert!(simulator.query_state(&other_key).is_none()); + }); + } + + #[test] + fn test_filtered_events() { + let executor = Runner::default(); + executor.start(|context| async move { + // Initialize + let (network_secret, network_identity) = create_network_keypair(); + let simulator = Simulator::new(network_identity); + let (mut state, mut events) = create_adbs(&context).await; + + // Create multiple accounts + let (private1, public1) = create_account_keypair(1); + let (private2, _public2) = create_account_keypair(2); + let (private3, _public3) = create_account_keypair(3); + + // Create transactions from all accounts + let txs = vec![ + Transaction::sign(&private1, 0, Instruction::Generate), + Transaction::sign(&private2, 0, Instruction::Generate), + Transaction::sign(&private3, 0, Instruction::Generate), + ]; + + // Execute block + let (_, summary) = execute_block( + &network_secret, + network_identity, + &mut state, + &mut events, + 1, // view + txs, + ) + .await; + + // Submit the summary + let (state_digests, events_digests) = summary.verify(&network_identity).unwrap(); + simulator.submit_events(summary.clone(), events_digests.clone()); + simulator.submit_state(summary.clone(), state_digests); + + // Store original count before moving + let original_ops_count = summary.events_proof_ops.len(); + + let events = Events { + progress: summary.progress, + certificate: summary.certificate, + events_proof: summary.events_proof, + events_proof_ops: summary.events_proof_ops, + }; + + // Apply filter + let filtered = filter_updates_for_account(events, events_digests, &public1) + .await + .unwrap(); + + // Verify filtered events + match filtered { + Update::FilteredEvents(filtered_events) => { + // Count how many events are included + let included_count = filtered_events.events_proof_ops.len(); + + // Verify we only have events related to account1 + for (_loc, op) in &filtered_events.events_proof_ops { + if let Keyless::Append(Output::Event(Event::Generated { + account, .. + })) = op + { + assert_eq!( + account, &public1, + "Filtered events should only contain account1" + ); + } + } + + // We should have filtered out events for account2 and account3 + assert!( + included_count > 0, + "Should have at least one included event" + ); + assert!( + included_count < original_ops_count, + "Should have filtered out some events" + ); + + // Verify the proof still validates with multi-proof verification + assert!( + filtered_events.verify(&network_identity), + "Multi-proof verification should pass" + ); + } + _ => panic!("Expected FilteredEvents"), + } + }); + } + + #[test] + fn test_multiple_transactions_per_block() { + let executor = Runner::default(); + executor.start(|context| async move { + // Initialize + let (network_secret, network_identity) = create_network_keypair(); + let simulator = Simulator::new(network_identity); + let (mut state, mut events) = create_adbs(&context).await; + + // Create multiple accounts + let accounts: Vec<_> = (0..5).map(create_account_keypair).collect(); + + // Block 1: Multiple account generations in a single block + let txs1: Vec<_> = accounts + .iter() + .map(|(private, _)| Transaction::sign(private, 0, Instruction::Generate)) + .collect(); + + let (_, summary1) = execute_block( + &network_secret, + network_identity, + &mut state, + &mut events, + 1, // view + txs1.clone(), + ) + .await; + + // Verify and submit + let (state_digests1, events_digests1) = summary1 + .verify(&network_identity) + .expect("Summary 1 verification failed"); + simulator.submit_events(summary1.clone(), events_digests1); + simulator.submit_state(summary1.clone(), state_digests1); + + // Verify height was inferred correctly (should be 1) + assert_eq!(summary1.progress.height, 1); + + // Query each account to verify they were created + for (_, public) in accounts.iter() { + let account_key = Sha256::hash(&Key::Account(public.clone()).encode()); + let lookup = simulator.query_state(&account_key).unwrap(); + assert!(lookup.verify(&network_identity)); + let Variable::Update(_, Value::Account(account)) = lookup.operation else { + panic!("Account not found for {public:?}"); + }; + assert_eq!(account.nonce, 1); + assert!(account.creature.is_some()); + } + + // Block 2: Multiple transactions from subset of accounts + let txs2: Vec<_> = accounts + .iter() + .take(3) + .map(|(private, _)| Transaction::sign(private, 1, Instruction::Generate)) + .collect(); + + let (_, summary2) = execute_block( + &network_secret, + network_identity, + &mut state, + &mut events, + 5, // view + txs2, + ) + .await; + + // Verify and submit + let (state_digests2, events_digests2) = summary2 + .verify(&network_identity) + .expect("Summary 2 verification failed"); + simulator.submit_events(summary2.clone(), events_digests2); + simulator.submit_state(summary2.clone(), state_digests2); + + // Verify height was inferred correctly (should be 2) + assert_eq!(summary2.progress.height, 2); + + // Query accounts to verify nonce updates + for (i, (_, public)) in accounts.iter().enumerate() { + let account_key = Sha256::hash(&Key::Account(public.clone()).encode()); + let lookup = simulator.query_state(&account_key).unwrap(); + assert!(lookup.verify(&network_identity)); + let Variable::Update(_, Value::Account(account)) = lookup.operation else { + panic!("Account not found for {public:?}"); + }; + // First 3 accounts should have nonce 2, others still 1 + let expected_nonce = if i < 3 { 2 } else { 1 }; + assert_eq!(account.nonce, expected_nonce); + } + }); + } +} From c9640a2fb555cb38bbb0e4d53efb482ef01d386d Mon Sep 17 00:00:00 2001 From: magqqgq <146786427+magqqgq@users.noreply.github.com> Date: Sun, 25 Oct 2026 13:12:47 +0300 Subject: [PATCH 2/2] Add files via upload --- .github/workflows/coverage.yml | 66 ++++++----- .github/workflows/publish.yml | 108 +++++++++-------- .github/workflows/tests.yml | 206 +++++++++++++++++---------------- 3 files changed, 199 insertions(+), 181 deletions(-) diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index 30454702..cfb2593d 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -1,31 +1,37 @@ -name: Coverage +name: Coverage + +on: + push: + branches: [ "main" ] + pull_request: + +env: + CARGO_TERM_COLOR: always + +# Least privilege: CI only needs to check out and build; for coverage the codecov +# upload authorizes itself with the CODECOV_TOKEN secret, and for publish the +# registry write is authorized by CARGO_REGISTRY_TOKEN rather than GITHUB_TOKEN. +permissions: + contents: read -on: - push: - branches: [ "main" ] - pull_request: - -env: - CARGO_TERM_COLOR: always - -jobs: - All: - runs-on: ubuntu-latest - steps: - - name: Checkout repository - uses: actions/checkout@v4 - - name: Get Rust version - id: rust-version - run: echo "rust_version=$(rustc --version)" >> "$GITHUB_OUTPUT" - - name: Run setup - uses: ./.github/actions/setup - - name: Install cargo-llvm-cov - uses: taiki-e/install-action@cargo-llvm-cov - - name: Generate coverage report - run: cargo llvm-cov --all-features --workspace --lcov --output-path lcov.info - - name: Upload coverage to Codecov - uses: codecov/codecov-action@v4 - with: - files: lcov.info - fail_ci_if_error: true - token: ${{ secrets.CODECOV_TOKEN }} +jobs: + All: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - name: Get Rust version + id: rust-version + run: echo "rust_version=$(rustc --version)" >> "$GITHUB_OUTPUT" + - name: Run setup + uses: ./.github/actions/setup + - name: Install cargo-llvm-cov + uses: taiki-e/install-action@94a99045a72830168b8eae8bf767ba08abeca856 # cargo-llvm-cov + - name: Generate coverage report + run: cargo llvm-cov --all-features --workspace --lcov --output-path lcov.info + - name: Upload coverage to Codecov + uses: codecov/codecov-action@b9fd7d16f6d7d1b5d2bec1a2887e65ceed900238 # v4 + with: + files: lcov.info + fail_ci_if_error: true + token: ${{ secrets.CODECOV_TOKEN }} diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 1e7f6d68..1f7a054d 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -1,52 +1,58 @@ -name: Publish +name: Publish + +on: + push: + branches: [ "main" ] + +# Least privilege: CI only needs to check out and build; for coverage the codecov +# upload authorizes itself with the CODECOV_TOKEN secret, and for publish the +# registry write is authorized by CARGO_REGISTRY_TOKEN rather than GITHUB_TOKEN. +permissions: + contents: read -on: - push: - branches: [ "main" ] - -jobs: - All: - runs-on: ubuntu-latest - steps: - - name: Checkout repository - uses: actions/checkout@v4 - - name: Get Rust version - id: rust-version - run: echo "rust_version=$(rustc --version)" >> "$GITHUB_OUTPUT" - - name: Run setup - uses: ./.github/actions/setup - - name: Publish types - run: cargo publish --manifest-path types/Cargo.toml - continue-on-error: true - env: - CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} - - name: Publish execution - run: cargo publish --manifest-path execution/Cargo.toml - continue-on-error: true - env: - CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} - - name: Publish simulator - run: cargo publish --manifest-path simulator/Cargo.toml - continue-on-error: true - env: - CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} - - name: Publish client - run: cargo publish --manifest-path client/Cargo.toml - continue-on-error: true - env: - CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} - - name: Publish node - run: cargo publish --manifest-path node/Cargo.toml - continue-on-error: true - env: - CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} - - name: Publish randotron - run: cargo publish --manifest-path randotron/Cargo.toml - continue-on-error: true - env: - CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} - - name: Publish deployer - run: cargo publish --manifest-path deployer/Cargo.toml - continue-on-error: true - env: - CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} +jobs: + All: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - name: Get Rust version + id: rust-version + run: echo "rust_version=$(rustc --version)" >> "$GITHUB_OUTPUT" + - name: Run setup + uses: ./.github/actions/setup + - name: Publish types + run: cargo publish --manifest-path types/Cargo.toml + continue-on-error: true + env: + CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} + - name: Publish execution + run: cargo publish --manifest-path execution/Cargo.toml + continue-on-error: true + env: + CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} + - name: Publish simulator + run: cargo publish --manifest-path simulator/Cargo.toml + continue-on-error: true + env: + CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} + - name: Publish client + run: cargo publish --manifest-path client/Cargo.toml + continue-on-error: true + env: + CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} + - name: Publish node + run: cargo publish --manifest-path node/Cargo.toml + continue-on-error: true + env: + CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} + - name: Publish randotron + run: cargo publish --manifest-path randotron/Cargo.toml + continue-on-error: true + env: + CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} + - name: Publish deployer + run: cargo publish --manifest-path deployer/Cargo.toml + continue-on-error: true + env: + CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 5d66473f..0bd4be09 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -1,102 +1,108 @@ -name: Tests +name: Tests + +on: + push: + branches: [ "main" ] + pull_request: + +env: + CARGO_TERM_COLOR: always + UDEPS_VERSION: 0.1.57 + NIGHTLY_VERSION: nightly-2025-08-10 + NODE_VERSION: 20 + +# Least privilege: CI only needs to check out and build; for coverage the codecov +# upload authorizes itself with the CODECOV_TOKEN secret, and for publish the +# registry write is authorized by CARGO_REGISTRY_TOKEN rather than GITHUB_TOKEN. +permissions: + contents: read -on: - push: - branches: [ "main" ] - pull_request: - -env: - CARGO_TERM_COLOR: always - UDEPS_VERSION: 0.1.57 - NIGHTLY_VERSION: nightly-2025-08-10 - NODE_VERSION: 20 - -jobs: - All: - runs-on: ubuntu-latest - steps: - - name: Checkout repository - uses: actions/checkout@v4 - - name: Get Rust version - id: rust-version - run: echo "rust_version=$(rustc --version)" >> "$GITHUB_OUTPUT" - - name: Run setup - uses: ./.github/actions/setup - - name: Lint - run: cargo clippy --all-targets --all-features -- -D warnings - - name: Fmt - run: cargo fmt --all -- --check - - name: Check docs - run: cargo doc --no-deps --document-private-items - env: - RUSTDOCFLAGS: "-D warnings" - - name: Run tests - run: cargo test --verbose - - Dependencies: - runs-on: ubuntu-latest - timeout-minutes: 20 - steps: - - name: Checkout repository - uses: actions/checkout@v4 - - name: Install nightly Rust toolchain - run: rustup toolchain install ${{ env.NIGHTLY_VERSION }} - - name: Get Rust version - id: rust-version - run: echo "rust_version=$(rustc +${{ env.NIGHTLY_VERSION }} --version)" >> "$GITHUB_OUTPUT" - - name: Run setup - uses: ./.github/actions/setup - - name: Cache cargo-udeps - id: cargo-udeps-cache - uses: actions/cache@v4 - with: - path: ~/.cargo/bin/cargo-udeps - key: ${{ runner.os }}-${{ env.UDEPS_VERSION }}-cargo-udeps-${{ steps.rust-version.outputs.rust_version }} - - name: Install cargo-udeps - if: steps.cargo-udeps-cache.outputs.cache-hit != 'true' - run: cargo +${{ env.NIGHTLY_VERSION }} install cargo-udeps --version ${{ env.UDEPS_VERSION }} - - name: Check for unused dependencies - run: cargo +${{ env.NIGHTLY_VERSION }} udeps --all-targets - - React: - runs-on: ubuntu-latest - steps: - - name: Checkout repository - uses: actions/checkout@v4 - - name: Get Rust version - id: rust-version - run: echo "rust_version=$(rustc --version)" >> "$GITHUB_OUTPUT" - - name: Run setup - uses: ./.github/actions/setup - - name: Setup Node.js - uses: actions/setup-node@v4 - with: - node-version: ${{ env.NODE_VERSION }} - cache: 'npm' - cache-dependency-path: website/package-lock.json - - name: Install dependencies - run: cd website && npm ci - - name: Test compilation - run: cd website && npm run build - - name: Test website - run: cd website && npm run test - - Lock: - runs-on: ubuntu-latest - timeout-minutes: 30 - steps: - - name: Checkout repository - uses: actions/checkout@v4 - - name: Run setup - uses: ./.github/actions/setup - - name: Build entire workspace - run: cargo build --workspace --all-targets - - name: Check Cargo.lock unchanged - run: | - if ! git diff --exit-code Cargo.lock; then - echo "ERROR: Cargo.lock was modified during build!" - echo "This suggests that the Cargo.lock file in the repository is not up to date." - echo "Please run 'cargo build' locally and commit the updated Cargo.lock." - exit 1 - fi +jobs: + All: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - name: Get Rust version + id: rust-version + run: echo "rust_version=$(rustc --version)" >> "$GITHUB_OUTPUT" + - name: Run setup + uses: ./.github/actions/setup + - name: Lint + run: cargo clippy --all-targets --all-features -- -D warnings + - name: Fmt + run: cargo fmt --all -- --check + - name: Check docs + run: cargo doc --no-deps --document-private-items + env: + RUSTDOCFLAGS: "-D warnings" + - name: Run tests + run: cargo test --verbose + + Dependencies: + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - name: Checkout repository + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - name: Install nightly Rust toolchain + run: rustup toolchain install ${{ env.NIGHTLY_VERSION }} + - name: Get Rust version + id: rust-version + run: echo "rust_version=$(rustc +${{ env.NIGHTLY_VERSION }} --version)" >> "$GITHUB_OUTPUT" + - name: Run setup + uses: ./.github/actions/setup + - name: Cache cargo-udeps + id: cargo-udeps-cache + uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4 + with: + path: ~/.cargo/bin/cargo-udeps + key: ${{ runner.os }}-${{ env.UDEPS_VERSION }}-cargo-udeps-${{ steps.rust-version.outputs.rust_version }} + - name: Install cargo-udeps + if: steps.cargo-udeps-cache.outputs.cache-hit != 'true' + run: cargo +${{ env.NIGHTLY_VERSION }} install cargo-udeps --version ${{ env.UDEPS_VERSION }} + - name: Check for unused dependencies + run: cargo +${{ env.NIGHTLY_VERSION }} udeps --all-targets + + React: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - name: Get Rust version + id: rust-version + run: echo "rust_version=$(rustc --version)" >> "$GITHUB_OUTPUT" + - name: Run setup + uses: ./.github/actions/setup + - name: Setup Node.js + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: ${{ env.NODE_VERSION }} + cache: 'npm' + cache-dependency-path: website/package-lock.json + - name: Install dependencies + run: cd website && npm ci + - name: Test compilation + run: cd website && npm run build + - name: Test website + run: cd website && npm run test + + Lock: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Checkout repository + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - name: Run setup + uses: ./.github/actions/setup + - name: Build entire workspace + run: cargo build --workspace --all-targets + - name: Check Cargo.lock unchanged + run: | + if ! git diff --exit-code Cargo.lock; then + echo "ERROR: Cargo.lock was modified during build!" + echo "This suggests that the Cargo.lock file in the repository is not up to date." + echo "Please run 'cargo build' locally and commit the updated Cargo.lock." + exit 1 + fi echo "✓ Cargo.lock remained unchanged after building everything" \ No newline at end of file