CodeSampleX

Ejemplo

rand_core 0.9.5: rand_core

Muestra verificada para cargo rand_core 0.9.5: rand_core. El contrato se ejecutó en rust 1 · linux alpine/x64 · docker y pasó.

sha256:69938f55d174911737cc255535d169396f5a7ad374a696b1b51765312fbca604

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado linux · alpine · musl x64 cargo

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
rust 1 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · cargo@1rust:1-alpine@sha256:a10e64dd139b…
2026-10-13

Caso

HOW
Objetivo
verify rand_core in pkg:cargo/rand_core@0.9.5
Paquetes
Símbolos
  • rand_core
Creado
2026-10-13T04:30:28Z

Contrato

  1. RngCore generates u32 and u64 integers and fills byte slices uniformly from a custom generator
  2. SeedableRng initializes reproducible state from seed array, from u64 seed, and from another RngCore
  3. TryRngCore blanket implementation provides infallible try_next_u32, try_next_u64, and try_fill_bytes for all RngCore types
  4. UnwrapErr and UnwrapMut wrap TryRngCore implementors into infallible RngCore generators
  5. impls helper functions convert between integer generators and byte fill operations using little-endian encoding
  6. BlockRng and BlockRng64 adapt block-based RNG cores into standard RngCore generators with buffer replenishment

Archivos

  • Cargo.lock
  • Cargo.toml
  • PROMPT.md
  • csx.json
  • spec.json
  • src/lib.rs
  • test/contract.rs

Descargar el artefacto de código fuente (tar.gz)

Código fuente

Cargo.lock
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4

[[package]]
name = "rand_core"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"

[[package]]
name = "sample-rand-core"
version = "1.0.0"
dependencies = [
 "rand_core",
]
Cargo.toml
[package]
name = "sample-rand-core"
version = "1.0.0"
edition = "2021"
publish = false

[dependencies]
rand_core = "=0.9.5"

[[bin]]
name = "contract"
path = "test/contract.rs"
PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify rand_core in pkg:cargo/rand_core@0.9.5
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:cargo/rand_core@0.9.5
Demonstrate these symbols/APIs:
  - rand_core

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:9f8925732bc23e3ba35c10aa4430775d9591a774c435436f7fdfc086cfb092a3","contract":["RngCore generates u32 and u64 integers and fills byte slices uniformly from a custom generator","SeedableRng initializes reproducible state from seed array, from u64 seed, and from another RngCore","TryRngCore blanket implementation provides infallible try_next_u32, try_next_u64, and try_fill_bytes for all RngCore types","UnwrapErr and UnwrapMut wrap TryRngCore implementors into infallible RngCore generators","impls helper functions convert between integer generators and byte fill operations using little-endian encoding","BlockRng and BlockRng64 adapt block-based RNG cores into standard RngCore generators with buffer replenishment"],"goal":"verify rand_core in pkg:cargo/rand_core@0.9.5","kind":"HOW","packages":["pkg:cargo/rand_core@0.9.5"],"schemaVersion":1,"symbols":["rand_core"]},"contractCommand":["cargo","run","--offline"],"environment":{"arch":"x64","distro":"alpine","ecosystem":"cargo","libc":"musl","os":"linux","packageManager":"cargo","schemaVersion":1},"license":"MIT-0","packages":["pkg:cargo/rand_core@0.9.5"],"schemaVersion":1,"subject":"pkg:cargo/rand_core@0.9.5","symbols":["rand_core"],"verifierAdapter":"cargo@1"}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify rand_core in pkg:cargo/rand_core@0.9.5",
  "kind": "HOW",
  "packages": [
    "pkg:cargo/rand_core@0.9.5"
  ],
  "symbols": [
    "rand_core"
  ]
}
src/lib.rs
//! Clean-room verification sample for rand_core.

pub use rand_core::*;
test/contract.rs
use rand_core::block::{BlockRng, BlockRng64, BlockRngCore};
use rand_core::{
    impls, le, CryptoRng, RngCore, SeedableRng, TryCryptoRng, TryRngCore, UnwrapErr, UnwrapMut,
};

/// Deterministic linear congruential style step RNG for testing RngCore and SeedableRng
struct SimpleStepRng {
    state: u64,
    step: u64,
}

impl SimpleStepRng {
    fn new(state: u64, step: u64) -> Self {
        Self { state, step }
    }
}

impl RngCore for SimpleStepRng {
    fn next_u32(&mut self) -> u32 {
        self.next_u64() as u32
    }

    fn next_u64(&mut self) -> u64 {
        let val = self.state;
        self.state = self.state.wrapping_add(self.step);
        val
    }

    fn fill_bytes(&mut self, dst: &mut [u8]) {
        impls::fill_bytes_via_next(self, dst);
    }
}

impl CryptoRng for SimpleStepRng {}

impl SeedableRng for SimpleStepRng {
    type Seed = [u8; 16];

    fn from_seed(seed: Self::Seed) -> Self {
        let mut state_arr = [0u64; 2];
        le::read_u64_into(&seed, &mut state_arr);
        Self {
            state: state_arr[0],
            step: if state_arr[1] == 0 { 1 } else { state_arr[1] },
        }
    }
}

/// Block RNG core generating 32-bit words
struct SimpleBlockCore {
    counter: u32,
}

impl BlockRngCore for SimpleBlockCore {
    type Item = u32;
    type Results = [u32; 4];

    fn generate(&mut self, results: &mut Self::Results) {
        for item in results.iter_mut() {
            *item = self.counter;
            self.counter = self.counter.wrapping_add(1);
        }
    }
}

/// Block RNG core generating 64-bit words
struct SimpleBlockCore64 {
    counter: u64,
}

impl BlockRngCore for SimpleBlockCore64 {
    type Item = u64;
    type Results = [u64; 2];

    fn generate(&mut self, results: &mut Self::Results) {
        for item in results.iter_mut() {
            *item = self.counter;
            self.counter = self.counter.wrapping_add(1);
        }
    }
}

/// Custom error for testing TryRngCore
#[derive(Debug, PartialEq, Eq)]
struct CustomError;

impl core::fmt::Display for CustomError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "CustomError")
    }
}

/// Fallible RNG implementation for testing TryRngCore
struct FallibleRng {
    count: u32,
    fail_after: u32,
}

impl TryRngCore for FallibleRng {
    type Error = CustomError;

    fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
        if self.count >= self.fail_after {
            return Err(CustomError);
        }
        self.count += 1;
        Ok(self.count)
    }

    fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
        let lo = self.try_next_u32()? as u64;
        let hi = self.try_next_u32()? as u64;
        Ok((hi << 32) | lo)
    }

    fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error> {
        for b in dst.iter_mut() {
            *b = (self.try_next_u32()? & 0xFF) as u8;
        }
        Ok(())
    }
}

impl TryCryptoRng for FallibleRng {}

fn main() {
    // 1. RngCore generates u32 and u64 integers and fills byte slices uniformly from a custom generator
    {
        let mut rng = SimpleStepRng::new(10, 5);
        assert_eq!(rng.next_u64(), 10);
        assert_eq!(rng.next_u64(), 15);
        assert_eq!(rng.next_u32(), 20);

        let mut buf = [0u8; 12];
        rng.fill_bytes(&mut buf);
        assert_ne!(buf, [0u8; 12]);

        // Blanket RngCore implementation for &mut R
        let rng_ref = &mut rng;
        assert_eq!(rng_ref.next_u64(), 35);
    }

    // 2. SeedableRng initializes reproducible state from seed array, from u64 seed, and from another RngCore
    {
        let seed = [
            1, 0, 0, 0, 0, 0, 0, 0, // state = 1
            2, 0, 0, 0, 0, 0, 0, 0, // step = 2
        ];
        let mut rng1 = SimpleStepRng::from_seed(seed);
        assert_eq!(rng1.next_u64(), 1);
        assert_eq!(rng1.next_u64(), 3);

        // seed_from_u64 uses PCG32 deterministic seed expansion
        let mut rng_u64_a = SimpleStepRng::seed_from_u64(12345);
        let mut rng_u64_b = SimpleStepRng::seed_from_u64(12345);
        assert_eq!(rng_u64_a.next_u64(), rng_u64_b.next_u64());
        assert_eq!(rng_u64_a.next_u64(), rng_u64_b.next_u64());

        // from_rng initializes from an existing RngCore
        let mut master = SimpleStepRng::new(100, 7);
        let mut child1 = SimpleStepRng::from_rng(&mut master);
        let mut child2 = SimpleStepRng::from_rng(&mut master);
        assert_ne!(child1.next_u64(), child2.next_u64());
    }

    // 3. TryRngCore blanket implementation provides infallible try_next_u32, try_next_u64, and try_fill_bytes for all RngCore types
    {
        let mut rng = SimpleStepRng::new(50, 10);
        let res_u32 = rng.try_next_u32();
        assert_eq!(res_u32, Ok(50));

        let res_u64 = rng.try_next_u64();
        assert_eq!(res_u64, Ok(60));

        let mut buf = [0u8; 8];
        let res_fill = rng.try_fill_bytes(&mut buf);
        assert!(res_fill.is_ok());

        // try_from_rng with infallible RngCore
        let mut seed_src = SimpleStepRng::new(1, 1);
        let seeded = SimpleStepRng::try_from_rng(&mut seed_src);
        assert!(seeded.is_ok());
    }

    // 4. UnwrapErr and UnwrapMut wrap TryRngCore implementors into infallible RngCore generators
    {
        let fallible = FallibleRng {
            count: 0,
            fail_after: 10,
        };
        let mut unwrapped = UnwrapErr(fallible);
        assert_eq!(unwrapped.next_u32(), 1);
        assert_eq!(unwrapped.next_u32(), 2);

        let mut fallible2 = FallibleRng {
            count: 0,
            fail_after: 10,
        };
        let mut unwrap_mut = UnwrapMut(&mut fallible2);
        assert_eq!(unwrap_mut.next_u32(), 1);
        let mut reborrowed = unwrap_mut.re();
        assert_eq!(reborrowed.next_u32(), 2);
    }

    // 5. impls helper functions convert between integer generators and byte fill operations using little-endian encoding
    {
        struct ConstU32Rng(u32);
        impl RngCore for ConstU32Rng {
            fn next_u32(&mut self) -> u32 {
                let v = self.0;
                self.0 = self.0.wrapping_add(1);
                v
            }
            fn next_u64(&mut self) -> u64 {
                impls::next_u64_via_u32(self)
            }
            fn fill_bytes(&mut self, dst: &mut [u8]) {
                impls::fill_bytes_via_next(self, dst);
            }
        }

        let mut rng = ConstU32Rng(0x01020304);
        let combined = rng.next_u64();
        assert_eq!(combined, (0x01020305u64 << 32) | 0x01020304u64);

        struct ByteRng(u8);
        impl RngCore for ByteRng {
            fn next_u32(&mut self) -> u32 {
                impls::next_u32_via_fill(self)
            }
            fn next_u64(&mut self) -> u64 {
                impls::next_u64_via_fill(self)
            }
            fn fill_bytes(&mut self, dst: &mut [u8]) {
                for b in dst.iter_mut() {
                    *b = self.0;
                    self.0 = self.0.wrapping_add(1);
                }
            }
        }

        let mut byte_rng = ByteRng(1);
        let u32_val = byte_rng.next_u32();
        assert_eq!(u32_val, u32::from_le_bytes([1, 2, 3, 4]));

        let u64_val = byte_rng.next_u64();
        assert_eq!(u64_val, u64::from_le_bytes([5, 6, 7, 8, 9, 10, 11, 12]));
    }

    // 6. BlockRng and BlockRng64 adapt block-based RNG cores into standard RngCore generators with buffer replenishment
    {
        let mut block_rng = BlockRng::new(SimpleBlockCore { counter: 100 });
        assert_eq!(block_rng.next_u32(), 100);
        assert_eq!(block_rng.next_u32(), 101);
        assert_eq!(block_rng.next_u32(), 102);
        assert_eq!(block_rng.next_u32(), 103);
        assert_eq!(block_rng.next_u32(), 104);

        let mut block_rng64 = BlockRng64::new(SimpleBlockCore64 { counter: 500 });
        assert_eq!(block_rng64.next_u64(), 500);
        assert_eq!(block_rng64.next_u64(), 501);
        assert_eq!(block_rng64.next_u64(), 502);
    }

    println!("All rand_core 0.9.5 contract assertions passed successfully.");
}

Seeder de origen

anónimo