CodeSampleX

Пример

crypto-common 0.2.2: crypto_common::Block

Проверенный пример — cargo crypto-common 0.2.2: crypto_common::Block. Контракт выполнен на rust 1 · linux alpine/x64 · docker и пройден.

sha256:4c972db6178588dc52548f68d9e447fa585cf39cefbc15afd0a51135b488bdc2

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда linux x64 cargo

Среды запусков проверки

Окружение Контракт Этапы Запуск
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-11-11

Кейс

HOW
Цель
verify crypto_common::Block in pkg:cargo/crypto-common@0.2.2
Пакеты
Символы
  • crypto_common::Block
Создан
2026-11-11T11:45:29Z

Контракт

  1. Block<B> resolves to Array<u8, B::BlockSize> with zeroed default length matching B::block_size()
  2. Block<B> converts losslessly to and from [u8; N] and validates exact byte lengths via TryFrom on shared and mutable slices
  3. Blanket BlockSizeUser implementations for &B and &mut B share the identical Block<B> representation
  4. In-place mutation of Block<B> and ParBlocks<B> transforms fixed-size blocks and round-trips deterministically

Файлы

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

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

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

[[package]]
name = "crypto-common"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
dependencies = [
 "hybrid-array",
]

[[package]]
name = "hybrid-array"
version = "0.4.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"
dependencies = [
 "typenum",
]

[[package]]
name = "sample-crypto-common-block"
version = "0.1.0"
dependencies = [
 "crypto-common",
]

[[package]]
name = "typenum"
version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
Cargo.toml
[package]
name = "sample-crypto-common-block"
version = "0.1.0"
edition = "2021"
publish = false

[dependencies]
crypto-common = "=0.2.2"

[[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 crypto_common::Block in pkg:cargo/crypto-common@0.2.2
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:cargo/crypto-common@0.2.2
Demonstrate these symbols/APIs:
  - crypto_common::Block

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:a883b2204fbdfef5af60586f3125ce4f5a398df90640df753a951beef4f7028c","contract":["Block\u003cB\u003e resolves to Array\u003cu8, B::BlockSize\u003e with zeroed default length matching B::block_size()","Block\u003cB\u003e converts losslessly to and from [u8; N] and validates exact byte lengths via TryFrom on shared and mutable slices","Blanket BlockSizeUser implementations for \u0026B and \u0026mut B share the identical Block\u003cB\u003e representation","In-place mutation of Block\u003cB\u003e and ParBlocks\u003cB\u003e transforms fixed-size blocks and round-trips deterministically"],"goal":"verify crypto_common::Block in pkg:cargo/crypto-common@0.2.2","kind":"HOW","packages":["pkg:cargo/crypto-common@0.2.2"],"schemaVersion":1,"symbols":["crypto_common::Block"]},"contractCommand":["cargo","run","--offline"],"environment":{"arch":"x64","ecosystem":"cargo","os":"linux","packageManager":"cargo","schemaVersion":1},"license":"MIT-0","packages":["pkg:cargo/crypto-common@0.2.2"],"schemaVersion":1,"subject":"pkg:cargo/crypto-common@0.2.2","symbols":["crypto_common::Block"],"verifierAdapter":"cargo@1"}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify crypto_common::Block in pkg:cargo/crypto-common@0.2.2",
  "kind": "HOW",
  "packages": [
    "pkg:cargo/crypto-common@0.2.2"
  ],
  "symbols": [
    "crypto_common::Block"
  ]
}
src/lib.rs
//! Clean-room verification sample for `crypto_common::Block`.

pub use crypto_common::Block;
use crypto_common::{
    BlockSizeUser, ParBlocks, ParBlocksSizeUser,
    typenum::{U4, U8, U16},
};

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct NarrowBlockUnit;

impl BlockSizeUser for NarrowBlockUnit {
    type BlockSize = U8;
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct XorBlockProcessor {
    mask: [u8; 16],
}

impl XorBlockProcessor {
    pub const fn new(mask: [u8; 16]) -> Self {
        Self { mask }
    }

    pub fn apply_in_place(&self, block: &mut Block<Self>) {
        for (byte, &m) in block.iter_mut().zip(self.mask.iter()) {
            *byte ^= m;
        }
    }

    pub fn apply_par_blocks(&self, blocks: &mut ParBlocks<Self>) {
        for block in blocks.iter_mut() {
            self.apply_in_place(block);
        }
    }
}

impl BlockSizeUser for XorBlockProcessor {
    type BlockSize = U16;
}

impl ParBlocksSizeUser for XorBlockProcessor {
    type ParBlocksSize = U4;
}
test/contract.rs
use crypto_common::{Block, BlockSizeUser, ParBlocks};
use sample_crypto_common_block::{NarrowBlockUnit, XorBlockProcessor};

fn read_ref_block<B: BlockSizeUser>( _b: B, block: &Block<B>) -> usize {
    block.len()
}

fn main() {
    // 1. Block<B> resolves to Array<u8, B::BlockSize> with zeroed default matching B::block_size()
    let narrow_default = Block::<NarrowBlockUnit>::default();
    assert_eq!(NarrowBlockUnit::block_size(), 8);
    assert_eq!(narrow_default.len(), 8);
    assert_eq!(narrow_default.as_slice(), &[0u8; 8]);

    let wide_default = Block::<XorBlockProcessor>::default();
    assert_eq!(XorBlockProcessor::block_size(), 16);
    assert_eq!(wide_default.len(), 16);
    assert_eq!(wide_default.as_slice(), &[0u8; 16]);

    // 2. Block<B> converts losslessly with [u8; N] and validates slice lengths via TryFrom
    let raw8: [u8; 8] = [0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80];
    let block8 = Block::<NarrowBlockUnit>::from(raw8);
    let roundtrip8: [u8; 8] = block8.into();
    assert_eq!(roundtrip8, raw8);

    let exact_slice: &[u8] = &[1, 2, 3, 4, 5, 6, 7, 8];
    let borrowed_block = <&Block<NarrowBlockUnit>>::try_from(exact_slice).expect("exact 8-byte slice");
    assert_eq!(borrowed_block.as_slice(), exact_slice);

    let owned_from_slice = Block::<NarrowBlockUnit>::try_from(exact_slice).expect("owned 8-byte block");
    assert_eq!(owned_from_slice.as_slice(), exact_slice);

    assert!(<&Block<NarrowBlockUnit>>::try_from(&[0u8; 7][..]).is_err());
    assert!(<&Block<NarrowBlockUnit>>::try_from(&[0u8; 9][..]).is_err());
    assert!(Block::<NarrowBlockUnit>::try_from(&[0u8; 4][..]).is_err());

    let mut backing = [9u8; 8];
    {
        let mut_block = <&mut Block<NarrowBlockUnit>>::try_from(&mut backing[..]).expect("mutable 8-byte slice");
        mut_block[0] = 0xAA;
        mut_block[7] = 0x55;
    }
    assert_eq!(backing[0], 0xAA);
    assert_eq!(backing[7], 0x55);

    // 3. Blanket BlockSizeUser impls for &B and &mut B share the identical Block<B> representation
    let mut unit = NarrowBlockUnit;
    let shared_block: Block<&NarrowBlockUnit> = block8;
    assert_eq!(read_ref_block(&unit, &shared_block), 8);
    let mut_ref_block: Block<&mut NarrowBlockUnit> = shared_block;
    assert_eq!(read_ref_block(&mut unit, &mut_ref_block), 8);
    assert_eq!(mut_ref_block, block8);

    // 4. In-place mutation of Block<B> and ParBlocks<B> transforms blocks and round-trips
    let mask = [
        0xAA, 0x55, 0xFF, 0x00, 0x12, 0x34, 0x56, 0x78,
        0x9A, 0xBC, 0xDE, 0xF0, 0x0F, 0x1E, 0x2D, 0x3C,
    ];
    let processor = XorBlockProcessor::new(mask);
    let plaintext: [u8; 16] = [
        0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
        0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10,
    ];
    let mut block16 = Block::<XorBlockProcessor>::from(plaintext);
    processor.apply_in_place(&mut block16);
    assert_ne!(block16.as_slice(), &plaintext);
    for i in 0..16 {
        assert_eq!(block16[i], plaintext[i] ^ mask[i]);
    }
    processor.apply_in_place(&mut block16);
    assert_eq!(block16.as_slice(), &plaintext);

    let mut par = ParBlocks::<XorBlockProcessor>::default();
    assert_eq!(par.len(), 4);
    for (idx, blk) in par.iter_mut().enumerate() {
        *blk = Block::<XorBlockProcessor>::from([idx as u8; 16]);
    }
    processor.apply_par_blocks(&mut par);
    for (idx, blk) in par.iter().enumerate() {
        for pos in 0..16 {
            assert_eq!(blk[pos], (idx as u8) ^ mask[pos]);
        }
    }
    processor.apply_par_blocks(&mut par);
    for (idx, blk) in par.iter().enumerate() {
        assert_eq!(blk.as_slice(), &[idx as u8; 16]);
    }
}

Исходный сидер

аноним