### Configure and Start Servlet Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Initialize workers and build the servlet configuration before starting the servlet. ```rust // Create workers (use ::new, not .start - servlet auto-starts them) let ping_pong_worker = PingPongWorker::new(()); let lucky_number_worker = LuckyNumberDeterminer::new(LuckyNumberDeterminerConf { lotto_number: 42, }); // Build servlet configuration let servlet_conf = ServletConf::::builder() .with_config(Arc::new(PingPongServletConf { lotto_number: 42 })) .with_worker(ping_pong_worker) .with_worker(lucky_number_worker) .build(); // Start the servlet (workers are auto-started with servlet's trace) PingPongServletWithWorker::start(trace, Some(servlet_conf)).await? ``` -------------------------------- ### Bare Environment Example in Rust Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Demonstrates pure logic invocation and assertion in a minimal environment. Requires no external services or complex setup. ```rust use tightbeam::testing::* tb_assert_spec! { pub BareSpec, V(1,0,0): { mode: Accept, gate: Accepted, assertions: [ ("Received", exactly!(1)), ("Responded", exactly!(1)) ] }, } tb_process_spec! { pub BareProcess, events { observable { "Received", "Responded" } } states { Idle => { "Received" => Processing } Processing => { "Responded" => Idle } } terminal { Idle } } tb_scenario! { name: test_bare_environment, config: ScenarioConf::builder() .with_spec(BareSpec::latest()) .with_csp(BareProcess) .build(), environment Bare { exec: |trace| { trace.event("Received")?; trace.event("Responded")?; Ok(()) } } } ``` -------------------------------- ### Start the development server Source: https://github.com/wahidgroup/tightbeam/blob/master/CONTRIBUTING.md Launch the development server from the project root directory. ```bash make dev ``` -------------------------------- ### Set up the development environment Source: https://github.com/wahidgroup/tightbeam/blob/master/CONTRIBUTING.md Run the setup command to prepare your local development environment. This should be done after cloning the repository. ```bash make setup ``` -------------------------------- ### Start and Manage Hive Lifecycle Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Demonstrates the basic lifecycle of a Hive, including starting, establishing, registering with a cluster, and stopping. Ensure necessary imports and configurations are in place before execution. ```rust let mut hive = MyHive::start(trace, Some(HiveConf::default())).await?; hive.establish_hive().await?; let response = hive.register_with_cluster(cluster_addr).await?; hive.stop(); ``` -------------------------------- ### Run tests to verify setup Source: https://github.com/wahidgroup/tightbeam/blob/master/CONTRIBUTING.md Execute the test command to ensure your development environment is correctly configured and all tests pass. ```bash make test ``` -------------------------------- ### Complete Pipeline Example with Mixed Operations Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md An example combining PipelineBuilder for tracing, job execution, standard Result operations, and parallel execution. ```rust use tightbeam::utils::task::{Pipeline, PipelineBuilder, join}; // Mix everything: jobs, Results, parallel execution, fallbacks, trace let session_id = PipelineBuilder::new(trace) .start(client_id) // Job with auto-trace .and_then(|id| CreateHandshakeRequest::run(id, nonce)) // Standard Result operation ``` -------------------------------- ### Conventional commit format examples Source: https://github.com/wahidgroup/tightbeam/blob/master/CONTRIBUTING.md Examples illustrating the conventional commit format for commit messages, including type, scope, and description. ```git type(scope): description feat: add new compression algorithm fix: resolve race condition in transport layer docs: update ASN.1 specification examples test: add integration tests for V2 features ``` -------------------------------- ### Compose and Build Client with Custom Policies Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Compose multiple policies and configure a client builder. This example sets an emitter gate, a collector gate, and a restart strategy before building and connecting the client. ```rust // Client-side with policies let builder = ClientBuilder::::builder() .with_emitter_gate(IdPatternGate) .with_collector_gate(PriorityGate) .with_restart(RestartLinearBackoff::new(3, 1000, 1, None)) .build(); let mut client = builder.connect(addr).await?; ``` -------------------------------- ### ScenarioConf Builder Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Example of building a scenario configuration for refinement checking. ```APIDOC ## ScenarioConf Builder Example ### Description Demonstrates how to construct a `ScenarioConf` object, including specifying refinement checking configurations. ### Method N/A (Code Example) ### Endpoint N/A ### Request Example ```rust tb_scenario! { name: test_simple_refinement, config: ScenarioConf::builder() .with_spec(SimpleSpec::latest()) .with_fdr(FdrConfig { seeds: 4, max_depth: 10, max_internal_run: 8, timeout_ms: 500, specs: vec![SimpleProcess::process()], fail_fast: true, expect_failure: false, }) .build(), environment Bare { exec: |trace| { trace.event("start")?; trace.event("finish")?; Ok(()) } } } ``` ### Response N/A (Code Example) ``` -------------------------------- ### Install cargo-afl Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Install the `cargo-afl` tool, which is a prerequisite for building and running AFL fuzz targets with Rust. ```bash cargo install cargo-afl ``` -------------------------------- ### Prepare Seed Inputs for AFL Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Create a directory for seed inputs (e.g., `fuzz_in`) and place initial seed files within it. AFL uses these seeds to start the mutation process. ```bash # Create seed input directory mkdir -p fuzz_in echo "seed" > fuzz_in/seed.txt ``` -------------------------------- ### Full Example: Client-Server with ServiceClient Environment in Rust Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Illustrates progressive verification across L1 (assertions), L2 (state machine), and L3 (trace refinement) using a ServiceClient environment. Requires specific features like 'testing-fdr', 'tcp', and 'tokio'. ```rust #![cfg(all(feature = "testing-fdr", feature = "tcp", feature = "tokio"))] use tightbeam::testing::* use tightbeam::trace::TraceCollector use tightbeam::transport::tcp::r#async::TokioListener use tightbeam::transport::Protocol // Layer 1: Assert spec - defines expected assertions and cardinalities tb_assert_spec! { pub ClientServerSpec, V(1,0,0): { mode: Accept, gate: Accepted, assertions: [ ("connect", exactly!(1)), ("request", exactly!(1)), ("response", exactly!(2)), ("disconnect", exactly!(1)), ("message_content", exactly!(1), equals!("test")) ] }, } // Layer 2: CSP process spec - models state machine with internal events tb_process_spec! { pub ClientServerProcess, events { observable { "connect", "request", "response", "disconnect" } hidden { "serialize", "encrypt", "decrypt", "deserialize" } } states { Idle => { "connect" => Connected } Connected => { "request" => Processing, "serialize" => Serializing } Serializing => { "encrypt" => Encrypting } Encrypting => { "request" => Processing } Processing => { "decrypt" => Decrypting, "response" => Responded } Decrypting => { "deserialize" => Processing } Responded => { "disconnect" => Idle } } terminal { Idle } choice { Connected, Processing } annotations { description: "Client-server with crypto and nondeterminism" } } tb_scenario! { name: test_client_server_all_layers, config: ScenarioConf::builder() .with_spec(ClientServerSpec::latest()) .with_csp(ClientServerProcess) .with_fdr(FdrConfig { seeds: 64, max_depth: 128, max_internal_run: 32, timeout_ms: 5000, specs: vec![ClientServerProcess::process()], fail_fast: true, expect_failure: false, }) .with_hooks(TestHooks { on_pass: Some(Arc::new(|_trace, _result| { // Optional: custom logic on test pass Ok(()) })), on_fail: Some(Arc::new(|_trace, _result, _violation| { // Optional: custom logic on test fail Err("Test failed".into()) })), }) .build(), environment ServiceClient { worker_threads: 2, server: |trace| async move { let bind_addr = "127.0.0.1:0".parse().unwrap(); let (listener, addr) = ::bind(bind_addr).await?; let handle = server! { protocol TokioListener: listener, assertions: trace.share(), handle: |frame, trace| async move { trace.event("connect")?; trace.event("request")?; trace.event("response")?; Some(frame) } }; Ok((handle, addr)) }, client: |trace, mut client| async move { trace.event("response")?; let frame = compose! { V0: id: "test", order: 1u64, message: TestMessage { content: "test".to_string() } } ?; let response = client.emit(frame, None).await?; // Decode response and emit value assertion if let Some(resp_frame) = response { let decoded: TestMessage = crate::decode(&resp_frame.message)?; trace.event_with("message_content", &[], decoded.content)?; } trace.event("disconnect")?; Ok(()) } } } ``` -------------------------------- ### Define and Manage Servlet Configuration Source: https://context7.com/wahidgroup/tightbeam/llms.txt Configure a servlet with transport, message types, background workers, and collector gates. Servlets can be started, their addresses retrieved, stopped gracefully, and joined for completion. ```rust use tightbeam::colony::servlet::{Servlet, ServletConf, ServletConfBuilder}; use tightbeam::transport::tcp::r#async::TokioListener; use tightbeam::transport::Protocol; use tightbeam::testing::TestMessage; use tightbeam::trace::TraceCollector; use std::sync::Arc; // Define servlet configuration type MyServletConf = ServletConf; let config: MyServletConf = ServletConfBuilder::default() .with_config(Arc::new(MyAppConfig { /* ... */ })) .with_worker(my_background_worker) .with_collector_gate(priority_gate) .build(); // Servlet lifecycle: start, get address, stop, join let trace = Arc::new(TraceCollector::new()); let servlet = MyServlet::start(trace, Some(config)).await?; let addr = servlet.addr(); // Get bound address // Process messages... servlet.stop(); // Graceful shutdown servlet.join().await?; ``` -------------------------------- ### Configure Log Filtering Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Example of initializing a log filter with a default level and component-specific overrides. ```rust let filter = LogFilter::new(LogLevel::Warning) .with_component("security", LogLevel::Debug); ``` -------------------------------- ### TightBeam CSP-Based IJON Integration Example Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Demonstrates how TightBeam automatically handles IJON annotations based on CSP process specifications, eliminating the need for manual `IJON_MAX` calls. The `tb_process_spec!` macro defines states and observable events, and IJON reports state transitions automatically. ```rust tb_process_spec! { pub ParserProcess, events { observable { "magic_detected", "parse_continue" } } states { Init => { "magic_detected" => SpecialState, "parse_continue" => Parsing } SpecialState => { /* ... */ } } // IJON automatically reports when SpecialState is reached } ``` -------------------------------- ### Basic AssertSpec Implementation Example Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md A simple AssertSpec definition with two versions, demonstrating basic assertion configurations for 'A' and 'R' labels. ```rust tb_assert_spec! { pub DemoSpec, V(1,0,0): { mode: Accept, gate: Accepted, tag_filter: ["v1"], assertions: [ ("A", exactly!(1)), ("R", exactly!(1)) ] }, V(1,1,0): { mode: Accept, gate: Accepted, tag_filter: ["v1.1"], assertions: [ ("A", exactly!(1)), ("R", exactly!(2)) ] }, } ``` -------------------------------- ### Start Standalone Worker Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Explicitly start a worker for testing purposes outside of a servlet context. ```rust let worker = MyWorker::new(config); let trace = Arc::new(TraceCollector::new()); let started_worker = worker.start(trace).await?; ``` -------------------------------- ### FMEA Configuration Example Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Illustrates how to configure FMEA generation within the FDR configuration. This includes specifying the fault model with custom fault injection parameters and setting FMEA-specific configurations like severity scale and RPN thresholds. ```rust fdr: FdrConfig { fault_model: Some(FaultModel::default() .with_fault( State::Active, Event::Send, || TightBeamError::Unavailable, BasisPoints::new(2500) // 25% occurrence ) ), fmea_config: Some(FmeaConfig { severity_scale: SeverityScale::MilStd1629, rpn_critical_threshold: 100, auto_generate: true, }), // ... other FDR config } ``` -------------------------------- ### Integrate Logging with TraceCollector Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Setup of a logger configuration and integration into the TraceCollector. ```rust use tightbeam::trace::{TraceConfig, logging::*}; let backend = Box::new(StdoutBackend); let filter = LogFilter::new(LogLevel::Warning); let config = LoggerConfig::new(backend, filter) .with_default_level(LogLevel::Info); let trace: TraceCollector = TraceConfig::builder() .with_logger(config) .build(); trace.event("msg")?.with_log_level(LogLevel::Error).emit(); ``` -------------------------------- ### Configure Linear Backoff Restart Strategy Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Configure a linear backoff strategy for retries. This example sets up a strategy with a maximum of 3 retries, an initial delay of 1000ms, and an increment of 1000ms per retry. ```rust use tightbeam::transport::policy::{RestartLinearBackoff, RestartExponentialBackoff}; // Linear backoff: 1s, 2s, 3s delays let restart = RestartLinearBackoff::new(3, 1000, 1, None); ``` -------------------------------- ### AssertSpec Value Assertion Examples Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Demonstrates using the `equals!` helper macro for verifying assertion payload values against various types. ```rust assertions: [ ("priority", exactly!(1), equals!(MessagePriority::High)), ("lifetime", exactly!(1), equals!(3_600)), ("version", exactly!(1), equals!(Version::V2)), ("confidentiality", exactly!(1), equals!(IsSome)), ("optional_field", exactly!(1), equals!(IsNone)) ] ``` -------------------------------- ### Configure Exponential Backoff Restart Strategy Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Configure an exponential backoff strategy for retries. This example sets up a strategy with a maximum of 4 retries, an initial delay of 1000ms, and a multiplier of 2. ```rust use tightbeam::transport::policy::{RestartLinearBackoff, RestartExponentialBackoff}; // Exponential backoff: 1s, 2s, 4s, 8s delays let restart = RestartExponentialBackoff::new(4, 1000, None); ``` -------------------------------- ### AssertSpec Cardinality Constraint Examples Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Illustrates the use of cardinality helper macros within AssertSpec assertions to define occurrence counts. ```rust assertions: [ ("Received", exactly!(1)), ("Responded", exactly!(1), equals!("ok")) ] ``` ```rust assertions: [ ("A", exactly!(1)), ("R", exactly!(1)) ] ``` ```rust assertions: [ ("A", exactly!(1)), ("R", exactly!(2)) ] ``` -------------------------------- ### Chess Fuzz Seed Byte Layout Example Source: https://github.com/wahidgroup/tightbeam/blob/master/tightbeam/fuzz/chess/seeds/README.md Illustrates the binary format of a chess fuzz test seed, showing the total number of moves followed by move quadruples. Each coordinate is a single byte. ```plaintext [0x01, 0x06, 0x04, 0x04, 0x04] │ └────┬────┘ │ └─ move 1: (6,4) → (4,4) └─ total moves: 1 ``` -------------------------------- ### Perform Acceptance and Refusal Queries in Rust Hooks Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Utilize `FdrTraceExt` within hooks to query process behavior at specific states. This example checks the acceptance set at the 'Connected' state and verifies that the process can refuse certain events after that state. ```rust use tightbeam::testing::fdr::FdrTraceExt; hooks { on_pass: |context| { // Acceptance queries: Check what events are accepted at specific states if let Some(acceptance) = context.trace.acceptance_at("Connected") { // At Connected state, process accepts "serialize" assert!(acceptance.iter().any(|e| e.0 == "serialize")); } // Refusal queries: Verify process can refuse events not in acceptance set // At Connected, process must do "serialize" before "request" assert!(context.trace.can_refuse_after("Connected", "request")); assert!(context.trace.can_refuse_after("Connected", "disconnect")); Ok(()) } } ``` -------------------------------- ### Implement Frame-Level Filtering with GatePolicy Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Use GatePolicy to filter messages at the frame level based on metadata. This example accepts messages with IDs starting with 'api-'. ```rust use tightbeam::policy::{GatePolicy, TransitStatus}; // Accept only messages with specific ID patterns #[derive(Default)] struct IdPatternGate; impl GatePolicy for IdPatternGate { fn evaluate(&self, frame: &Frame) -> TransitStatus { if frame.metadata.id.starts_with(b"api-") { TransitStatus::Accepted } else { TransitStatus::Forbidden } } } ``` -------------------------------- ### Create an Async TCP Server with `server!` Macro Source: https://context7.com/wahidgroup/tightbeam/llms.txt Illustrates setting up an asynchronous TCP server using the `server!` macro. The server can handle incoming messages and optionally return responses. Policies can be applied for advanced control. ```rust use tightbeam::{server, Frame}; use tightbeam::transport::tcp::r#async::TokioListener; use std::sync::Arc; // Bind to dynamic port and start async server let listener = TokioListener::bind("127.0.0.1:0").await?; let addr = listener.local_addr()?; let server_handle = server! { protocol TokioListener: listener, handle: move |message: Frame| { async move { // Process incoming message println!("Received: {:?}", message.metadata.id); // Return optional response frame Ok(None) // or Ok(Some(response_frame)) } } }; // Server with policies let listener2 = TokioListener::bind("127.0.0.1:0").await?; let server_with_policies = server! { protocol TokioListener: listener2, policies: { with_gate: [priority_gate, size_gate] }, handle: move |message: Frame| { async move { Ok(None) } } }; // Cleanup server_handle.abort(); ``` -------------------------------- ### Create a TCP Client with `client!` Macro Source: https://context7.com/wahidgroup/tightbeam/llms.txt Demonstrates creating TCP clients using the `client!` macro, including basic connections and clients with restart policies. Messages can be emitted or sent as requests expecting a response. ```rust use tightbeam::{client, Frame}; use tightbeam::transport::tcp::r#async::TokioListener; use tightbeam::transport::tcp::TightBeamSocketAddr; use tightbeam::transport::policy::RestartLinearBackoff; use tightbeam::transport::Transport; use tightbeam::testing::create_v0_tightbeam; // Server address (from server setup) let addr = TightBeamSocketAddr("127.0.0.1:8080".parse()?); // Basic client connection let mut client = client! { connect TokioListener: addr }; // Client with restart policy let mut client_with_policy = client! { connect TokioListener: addr, policies: { restart_policy: RestartLinearBackoff::default(), } }; // Send message let message = create_v0_tightbeam(Some("Hello"), Some("msg-001")); client.emit(message, None).await?; // Send and receive response let request = create_v0_tightbeam(Some("Request"), Some("req-001")); let response: Option = client.request(request, None).await?; ``` -------------------------------- ### Utilize Tightbeam Testing Macros and Utilities Source: https://context7.com/wahidgroup/tightbeam/llms.txt Use macros like `test_builder` and `test_servlet` for comprehensive testing. Helper functions are available for creating test messages, frames, and cryptographic keys. ```rust use tightbeam::{test_builder, test_servlet, compose}; use tightbeam::builder::{FrameBuilder, TypeBuilder}; use tightbeam::testing::{create_test_message, TestMessage}; use tightbeam::{Frame, Version}; // Builder test macro test_builder! { name: test_v0_frame_creation, builder_type: FrameBuilder, version: Version::V0, message: create_test_message(Some("test")), setup: |builder, msg| { builder .with_message(msg) .with_id("test-id") .with_order(1696521600) .build() }, assertions: |_msg, result| { let frame = result?; assert_eq!(frame.version, Version::V0); assert_eq!(frame.metadata.id, b"test-id"); Ok(()) } } // Test utilities let test_msg = create_test_message(Some("Hello")); let test_frame = tightbeam::testing::create_v0_tightbeam( Some("content"), Some("unique-id") ); // Test signing key let signing_key = tightbeam::testing::create_test_signing_key(); let (key, cipher) = tightbeam::testing::create_test_cipher_key(); ``` -------------------------------- ### Clone the tightbeam repository Source: https://github.com/wahidgroup/tightbeam/blob/master/CONTRIBUTING.md Clone your forked repository and navigate into the project directory to begin development. ```bash git clone https://github.com/yourusername/tightbeam.git cd tightbeam ``` -------------------------------- ### Common development commands Source: https://github.com/wahidgroup/tightbeam/blob/master/CONTRIBUTING.md A collection of make commands for common development tasks such as building, cleaning, testing, and linting the project. ```bash make help make build make clean make test make lint make doc ``` -------------------------------- ### Implement Message-Level Filtering with ReceptorPolicy Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Use ReceptorPolicy to filter messages at the message level based on their content or priority. This example accepts messages with a priority of 5 or higher. ```rust use tightbeam::policy::ReceptorPolicy; #[derive(Beamable, Sequence)] struct RequestMessage { content: String, priority: u8, } // Only accept high-priority messages #[derive(Default)] struct PriorityGate; impl ReceptorPolicy for PriorityGate { fn evaluate(&self, message: &RequestMessage) -> TransitStatus { if message.priority >= 5 { TransitStatus::Accepted } else { TransitStatus::Forbidden } } } ``` -------------------------------- ### Define a Servlet with Gate Policies Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Define a servlet using the `servlet!` macro, specifying its name, protocol, and gate policies. The `handle` function is executed only if all gates pass, providing access to context like trace and configuration. ```rust servlet! { pub SecureServlet, protocol: TokioListener, policies: { with_collector_gate: [RateLimitGate::new(100), AuthGate::new(key)] }, handle: |frame, ctx| async move { // Only reached if all gates pass // Access trace, config, workers via ctx let _trace = ctx.trace(); // ... } } ``` -------------------------------- ### Compose! Macro for Frame Construction (V0) Source: https://context7.com/wahidgroup/tightbeam/llms.txt Constructs a basic V0 frame with ID, order, and message. Ensure all necessary types are imported. ```rust use tightbeam::{compose, Frame, Version, MessagePriority}; use tightbeam::crypto::aead::{Aes256Gcm, Aes256GcmOid}; use tightbeam::crypto::sign::ecdsa::Secp256k1Signature; use tightbeam::crypto::hash::Sha3_256; use tightbeam::der::Sequence; use tightbeam::Beamable; #[derive(Beamable, Clone, Debug, PartialEq, Sequence)] struct MyMessage { value: u64, } // V0: Basic message (id, order, message only) let frame_v0: Frame = compose! { V0: id: "msg-001", order: 1696521600, message: MyMessage { value: 42 } }?; assert_eq!(frame_v0.version, Version::V0); assert!(frame_v0.metadata.confidentiality.is_none()); ``` -------------------------------- ### Build with specific features Source: https://github.com/wahidgroup/tightbeam/blob/master/CONTRIBUTING.md Compile the project with a custom set of features enabled. This is useful for testing specific functionalities. ```bash make build features="std,tcp,tokio" make build features="aes-gcm,sha3,secp256k1" make build features="zstd,compress" make build features="x509,signature" ``` -------------------------------- ### Build ClientKeyExchange Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Constructs the ClientKeyExchange message by extending the transcript, signing the hash, and packaging the enveloped data with client credentials. ```text Client Side - Building ClientKeyExchange: ┌─────────────────────────────────────────────────────────────────────┐ │ 1. Extend Transcript │ │ transcript = ClientHello || ServerHandshake || ClientKeyExchange │ ├─────────────────────────────────────────────────────────────────────┤ │ 2. Sign Extended Transcript │ │ final_hash = SHA3-256(transcript) │ │ client_signed_data = Sign(final_hash, client_priv_key) │ ├─────────────────────────────────────────────────────────────────────┤ │ 3. Build ClientKeyExchange │ │ ┌──────────────────────────────────────────────────────────┐ │ │ │ ClientKeyExchange { │ │ │ │ enveloped_data: EnvelopedData, // Encrypted CEK │ │ │ │ client_certificate: Some(cert), // Client cert │ │ │ │ client_signature: Some(sig), // Transcript sig │ │ │ │ } │ │ │ └──────────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────────┘ ``` -------------------------------- ### Implement Custom Security Profile in Rust Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Example of implementing a custom application-specific security profile by defining associated types for cryptographic algorithms. This allows tailoring the protocol's security features to application needs. ```rust // Example: Custom application profile pub struct MyAppProfile; impl SecurityProfile for MyAppProfile { type DigestOid = Sha3_256; type AeadOid = Aes256GcmOid; type SignatureAlg = Secp256k1Signature; type CurveOid = Secp256k1Oid; type KemOid = Kyber1024Oid; const KEY_WRAP_OID: Option = Some(AES_256_WRAP); } ``` -------------------------------- ### Client Work Request and Response Handling Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Demonstrates the structure of a `ClusterWorkRequest` sent by a client, including the servlet type and payload. Also shows how to decode and handle the `ClusterWorkResponse`, checking its status. ```rust // Client sends: let request = ClusterWorkRequest { servlet_type: b"calculator".to_vec(), payload: encode(&CalcRequest { value: 42 })?, }; // Client receives: let response: ClusterWorkResponse = decode(&frame.message)?; match response.status { TransitStatus::Accepted => { /* process response.payload */ } TransitStatus::Forbidden => { /* no hive available */ } _ => { /* handle other statuses */ } } ``` -------------------------------- ### Configure AFL Fuzzing with tb_scenario! Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Use the `fuzz: afl` parameter within `tb_scenario!` to enable AFL fuzzing mode. This configuration leverages a CSP oracle for guided state navigation based on AFL's random inputs. ```rust tb_scenario! { fuzz: afl, config: ScenarioConf::builder() .with_spec(MySpec::latest()) .with_csp(MyProcess) // ← oracle for valid state navigation .build(), environment Bare { exec: |trace| { // AFL provides random bytes, oracle navigates state machine match trace.oracle().fuzz_from_bytes() { Ok(()) => { for event in trace.oracle().trace() { trace.event(event.0)?; } Ok(()) } Err(_) => Err(TestingError::FuzzInputExhausted.into()) } } } } ``` -------------------------------- ### Compose! Macro for Frame Construction (V1) Source: https://context7.com/wahidgroup/tightbeam/llms.txt Constructs a V1 frame including encryption and signature. Requires cryptographic primitives and signing keys. ```rust let cipher = Aes256Gcm::new_from_slice(&[0x33u8; 32])?; let signing_key = k256::ecdsa::SigningKey::from_bytes(&[1u8; 32].into())?; let frame_v1: Frame = compose! { V1: id: "msg-002", order: 1696521600, message: MyMessage { value: 100 }, confidentiality: cipher, nonrepudiation: signing_key }?; assert!(frame_v1.metadata.confidentiality.is_some()); assert!(frame_v1.nonrepudiation.is_some()); ``` -------------------------------- ### Implement Trace Refinement Checks in Rust Hooks Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Extend `ConsumedTrace` with `FdrTraceExt` to perform CSP-specific analysis within hooks. This example checks trace refinement, failures refinement, divergence freedom, and determinism based on FDR verification results. ```rust use tightbeam::testing::fdr::FdrTraceExt; hooks { on_pass: |trace, result| { // Refinement properties if let Some(ref fdr_verdict) = result.fdr_verdict { assert!(fdr_verdict.trace_refines); assert!(fdr_verdict.failures_refines); assert!(fdr_verdict.divergence_free); assert!(fdr_verdict.is_deterministic); } Ok(()) } } ``` -------------------------------- ### Servlet Integration Testing Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Demonstrates testing a servlet component with client-side assertions and process specifications. ```rust use tightbeam::testing::*; // Define assertion spec for servlet behavior tb_assert_spec! { pub PingPongSpec, V(1,0,0): { mode: Accept, gate: Accepted, assertions: [ ("request_received", exactly!(1)), ("pong_sent", exactly!(1)), ("response_result", exactly!(1), equals!("PONG")), ("is_winner", exactly!(1), equals!(true)) ] }, } // Define process spec for servlet state machine tb_process_spec! { pub PingPongProcess, events { observable { "request_received", "pong_sent" } hidden { "validate_lucky_number", "format_response" } } states { Idle => { "request_received" => Processing } Processing => { "validate_lucky_number" => Validating } Validating => { "format_response" => Responding } Responding => { "pong_sent" => Idle } } terminal { Idle } choice { Processing } } tb_scenario! { name: test_servlet_with_workers, config: ScenarioConf::builder() .with_spec(PingPongSpec::latest()) .with_csp(PingPongProcess) .build(), environment Servlet { servlet: PingPongServletWithWorker, setup: |addr| async move { Ok(client! { connect TokioListener: addr }) }, client: |trace, mut client| async move { fn generate_message( lucky_number: u32, content: Option ) -> Result { let message = RequestMessage { content: content.unwrap_or_else(|| "PING".to_string()), lucky_number, }; compose! { V0: id: b"test-ping", message: message } } // Client-side assertion before sending trace.event("request_received")?; // Test winning case let ping_message = generate_message(42, None)?; let response = client.emit(ping_message, None).await?; let response_message: ResponseMessage = decode(&response.unwrap().message)?; // Emit value assertions for spec verification trace.event_with("response_result", &[], response_message.result)?; trace.event_with("is_winner", &[], response_message.is_winner)?; // Client-side assertion after receiving trace.event("pong_sent")?; Ok(()) } } } ``` -------------------------------- ### Certificate Trust Stores Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Demonstrates how to build and configure certificate trust stores for verifying peer certificates and validating certificate chains. ```APIDOC ## Certificate Trust Stores The `CertificateTrust` trait provides certificate chain verification and trust anchor management. Trust stores are used for: - Verifying peer certificates during connection establishment - Validating certificate chains (root -> intermediate -> leaf) - Looking up signer certificates for frame signature verification ### Building a Trust Store: ```rust let cert = Certificate::try_from(CERT_PEM)?; let trust_store = CertificateTrustBuilder::::from(Secp256k1Policy) .with_certificate(cert)? .build(); ``` ### Adding Certificate Chains: ```rust let trust_store = CertificateTrustBuilder::::from(Secp256k1Policy) .with_chain(vec![root_cert, intermediate_cert, leaf_cert])? .build(); ``` ``` -------------------------------- ### Check tightbeam Frame Version Capabilities Source: https://context7.com/wahidgroup/tightbeam/llms.txt Demonstrates how to check the capabilities of different `Version` variants in tightbeam, such as whether they allow integrity, confidentiality, or priority. ```rust use tightbeam::{Frame, Metadata, Version, MessagePriority}; use tightbeam::der::{Decode, Encode}; // Frame ASN.1 structure // Frame ::= // SEQUENCE { // version Version, // metadata Metadata, // message OCTET STRING, // integrity [0] DigestInfo OPTIONAL, // nonrepudiation [1] SignerInfo OPTIONAL // } // Version capabilities let v0 = Version::V0; assert!(!v0.allows_integrity()); // V0: no security features assert!(!v0.allows_confidentiality()); let v1 = Version::V1; assert!(v1.allows_integrity()); // V1+: integrity & confidentiality assert!(v1.allows_confidentiality()); assert!(!v1.allows_priority()); // V1: no priority/TTL let v2 = Version::V2; assert!(v2.allows_priority()); // V2+: priority, TTL, frame chaining assert!(v2.allows_lifetime()); assert!(v2.allows_previous_frame()); assert!(!v2.allows_matrix()); // V2: no matrix control let v3 = Version::V3; assert!(v3.allows_matrix()); // V3+: matrix control ``` -------------------------------- ### Test Scenario with Refinement Checking Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Set up a test scenario using a defined specification and FdrConfig. The environment defines the execution logic for the test. ```rust // Test with refinement checking tb_scenario! { name: test_simple_refinement, config: ScenarioConf::builder() .with_spec(SimpleSpec::latest()) .with_fdr(FdrConfig { seeds: 4, max_depth: 10, max_internal_run: 8, timeout_ms: 500, specs: vec![SimpleProcess::process()], fail_fast: true, expect_failure: false, }) .build(), environment Bare { exec: |trace| { trace.event("start")?; trace.event("finish")?; Ok(()) } } } ``` -------------------------------- ### Implement TCP Transport Server Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Sets up a TCP listener and uses the server macro to handle incoming frames. ```rust use std::net::TcpListener; use tightbeam::{server, compose, Frame}; let listener = TcpListener::bind("127.0.0.1:8080")?; server! { protocol std::net::TcpListener: listener, handle: |message: Frame| async move { // Echo the frame back Ok(Some(message)) } } ``` -------------------------------- ### Define Servlet Configuration Struct Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Define a configuration struct for the servlet outside of the macro definition. ```rust #[derive(Clone)] pub struct PingPongServletConf { pub lotto_number: u32, } ``` -------------------------------- ### Import Tightbeam Job Utilities Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Import the necessary macros and traits for creating and using jobs within pipelines. ```rust use tightbeam::job; // Macro for creating jobs use tightbeam::utils::task::{Pipeline, join}; ``` -------------------------------- ### Integrate with FDR Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Configures the FDR settings for formal verification during CSP exploration. ```rust fdr: FdrConfig { seeds: 64, fault_model: Some(fault_model), specs: vec![MyProcess::process()], ..Default::default() } ``` -------------------------------- ### Record Trace Events Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Use trace.event for simple labels and trace.event_with for labels with tags and optional values. ```rust trace.event("relay_start")?; trace.event_with("response_ok", &["tag_a"], true)?; ``` -------------------------------- ### tb_process_spec! Macro Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Defines a labeled transition system (LTS) for formal process modeling using CSP theory. ```APIDOC ## tb_process_spec! Macro ### Description Defines a process specification including observable/hidden alphabets, state transitions, terminal states, and optional timing/schedulability constraints. ### Configuration Blocks - **events**: Defines observable (Σ) and hidden (τ) alphabets. - **states**: Defines state transitions, guards, and clock resets. - **terminal**: Specifies valid end states. - **choice**: Specifies nondeterministic states. - **timing**: Defines WCET, jitter, deadlines, and slack constraints. - **schedulability**: Configures scheduler type and task periods. ### Example ```rust tb_process_spec! { pub ProcessName, events { observable { "event1" } hidden { "internal1" } } states { S0 => { "event1" => S1 } } terminal { S1 } } ``` ``` -------------------------------- ### Add Certificate Chains to Trust Store Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Initializes a trust store by providing a vector of certificates representing a chain. ```rust let trust_store = CertificateTrustBuilder::::from(Secp256k1Policy) .with_chain(vec![root_cert, intermediate_cert, leaf_cert])? .build(); ``` -------------------------------- ### Compose! Macro for Frame Construction (V2) Source: https://context7.com/wahidgroup/tightbeam/llms.txt Constructs a V2 frame with full features including priority, TTL, and integrity checks. Ensure all required cryptographic and hashing types are imported. ```rust let frame_v2: Frame = compose! { V2: id: "msg-003", order: 1696521600, message: MyMessage { value: 200 }, confidentiality: cipher, nonrepudiation: signing_key, message_integrity: type Sha3_256, frame_integrity: type Sha3_256, priority: MessagePriority::High, lifetime: 3600 // TTL in seconds }?; assert_eq!(frame_v2.metadata.priority, Some(MessagePriority::High)); assert_eq!(frame_v2.metadata.lifetime, Some(3600)); assert!(frame_v2.metadata.integrity.is_some()); // Message integrity assert!(frame_v2.integrity.is_some()); // Frame integrity ``` -------------------------------- ### Build a Certificate Trust Store Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Constructs a trust store using a specific hash algorithm and security policy. ```rust let cert = Certificate::try_from(CERT_PEM)?; let trust_store = CertificateTrustBuilder::::from(Secp256k1Policy) .with_certificate(cert)? .build(); ``` -------------------------------- ### Build a Custom Application URN Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Use `UrnBuilder` to construct and validate custom URNs. Ensure the URN is valid before building. ```rust use tightbeam::utils::urn::{UrnBuilder, UrnValidationError}; fn build_customer_urn() -> Result<(), UrnValidationError> { let urn = UrnBuilder::default() .with_nid("example") .with_nss("customer:1234") .build()?; assert_eq!(urn.to_string(), "urn:example:customer:1234"); Ok(()) } ``` -------------------------------- ### Set Diagonal Flags in a 3x3 Matrix (Rust) Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Demonstrates how to set diagonal flags in a 3x3 Matrix using the `tightbeam` crate and embed it within a frame. This approach supports up to 255 flags and is extensible. ```rust use tightbeam::Matrix; // Full 3x3 matrix let mut matrix = Matrix::<3>::default(); matrix.set(0, 0, 1); // Feature A: enabled matrix.set(1, 1, 1); // Feature B: enabled matrix.set(2, 2, 0); // Feature C: disabled // Embed in a frame let frame = compose! { V1: id: "config-001", order: 1000, message: my_message, matrix: Some(matrix) }? ``` -------------------------------- ### Define a Simple CSP Process Specification Source: https://github.com/wahidgroup/tightbeam/blob/master/README.md Uses the tb_process_spec! macro to define process events, states, and transitions. Requires the tightbeam::testing module. ```rust use tightbeam::testing::*; tb_process_spec! { pub SimpleProcess, events { observable { "Received", "Responded" } hidden { "internal_processing" } } states { Idle => { "Received" => Processing } Processing => { "internal_processing" => Processing, "Responded" => Idle } } terminal { Idle } choice { Processing } annotations { description: "Simple request-response with internal processing" } } ```