CodeSampleX

Ejemplo

yasna 0.5.2

Muestra verificada para cargo yasna 0.5.2. El contrato se ejecutó en rust 1 · linux alpine/x64 · docker y pasó: yasna::construct_der encodes a DER SEQUENCE…

sha256:642bf55afbb48fb609a6420a0393d5597664cee289ba3dd6f5b0942f4be1f059

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 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-11-27

Caso

HOW
Objetivo
verify pkg:cargo/yasna@0.5.2
Paquetes
Creado
2026-11-27T01:49:02Z

Contrato

  1. yasna::construct_der encodes a DER SEQUENCE containing i64, bool, UTF8String (write_utf8_string), OCTET STRING, ObjectIdentifier, context-specific tagged u32/u64, and NULL starting with tag 0x30
  2. yasna::parse_der decodes the constructed DER SEQUENCE back to identical primitive, UTF8String (read_utf8string), OID, and tagged values
  3. yasna::parse_ber accepts non-canonical BER booleans (0x01, 0x05) as true while yasna::parse_der rejects them with ASN1ErrorKind::Invalid
  4. yasna::parse_der rejects truncated DER input with ASN1ErrorKind::Eof and trailing extra bytes with ASN1ErrorKind::Extra

Archivos

  • Cargo.lock
  • Cargo.toml
  • PROMPT.md
  • csx.json
  • spec.json
  • src/main.rs
  • tests/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 = "sample-yasna"
version = "0.1.0"
dependencies = [
 "yasna",
]

[[package]]
name = "yasna"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e17bb3549cc1321ae1296b9cdc2698e2b6cb1992adfa19a8c72e5b7a738f44cd"
Cargo.toml
[package]
name = "sample-yasna"
version = "0.1.0"
edition = "2021"

[dependencies]
yasna = "=0.5.2"
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 pkg:cargo/yasna@0.5.2
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:cargo/yasna@0.5.2
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:596ae356fb3b8c9d755bdb8f331c815ddb389a177448eed216a2fa24757d604c","contract":["yasna::construct_der encodes a DER SEQUENCE containing i64, bool, UTF8String (write_utf8_string), OCTET STRING, ObjectIdentifier, context-specific tagged u32/u64, and NULL starting with tag 0x30","yasna::parse_der decodes the constructed DER SEQUENCE back to identical primitive, UTF8String (read_utf8string), OID, and tagged values","yasna::parse_ber accepts non-canonical BER booleans (0x01, 0x05) as true while yasna::parse_der rejects them with ASN1ErrorKind::Invalid","yasna::parse_der rejects truncated DER input with ASN1ErrorKind::Eof and trailing extra bytes with ASN1ErrorKind::Extra"],"goal":"verify pkg:cargo/yasna@0.5.2","kind":"HOW","packages":["pkg:cargo/yasna@0.5.2"],"schemaVersion":1},"contractCommand":["cargo","test","--offline"],"environment":{"arch":"x64","ecosystem":"cargo","os":"linux","packageManager":"cargo","schemaVersion":1},"license":"MIT-0","packages":["pkg:cargo/yasna@0.5.2"],"schemaVersion":1,"subject":"pkg:cargo/yasna@0.5.2","verifierAdapter":"cargo@1"}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:cargo/yasna@0.5.2",
  "kind": "HOW",
  "packages": [
    "pkg:cargo/yasna@0.5.2"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/main.rs
use yasna::models::ObjectIdentifier;
use yasna::{ASN1ErrorKind, Tag};

fn encode_record(
    id: i64,
    active: bool,
    label: &str,
    payload: &[u8],
    oid: &ObjectIdentifier,
    revision: u32,
) -> Vec<u8> {
    yasna::construct_der(|writer| {
        writer.write_sequence(|writer| {
            writer.next().write_i64(id);
            writer.next().write_bool(active);
            writer.next().write_utf8_string(label);
            writer.next().write_bytes(payload);
            writer.next().write_oid(oid);
            writer
                .next()
                .write_tagged(Tag::context(0), |writer| writer.write_u32(revision));
            writer.next().write_null();
        });
    })
}

fn decode_record(
    der: &[u8],
) -> yasna::ASN1Result<(i64, bool, String, Vec<u8>, ObjectIdentifier, u32)> {
    yasna::parse_der(der, |reader| {
        reader.read_sequence(|reader| {
            let id = reader.next().read_i64()?;
            let active = reader.next().read_bool()?;
            let label = reader.next().read_utf8string()?;
            let payload = reader.next().read_bytes()?;
            let oid = reader.next().read_oid()?;
            let revision = reader
                .next()
                .read_tagged(Tag::context(0), |reader| reader.read_u32())?;
            reader.next().read_null()?;
            Ok((id, active, label, payload, oid, revision))
        })
    })
}

fn main() {
    let oid = ObjectIdentifier::from_slice(&[1, 2, 840, 113549, 1, 1, 11]);
    let der = encode_record(-42, true, "sample-item", b"\x01\x02\x03", &oid, 7);

    // DER sequence starts with universal SEQUENCE tag 0x30
    assert_eq!(der[0], 0x30);

    let (id, active, label, payload, parsed_oid, revision) =
        decode_record(&der).expect("valid DER record");
    assert_eq!(id, -42);
    assert!(active);
    assert_eq!(label, "sample-item");
    assert_eq!(payload, b"\x01\x02\x03");
    assert_eq!(parsed_oid.components().as_slice(), &[1, 2, 840, 113549, 1, 1, 11]);
    assert_eq!(revision, 7);

    // Non-canonical BER boolean (0x01 instead of 0xff for true):
    // accepted by parse_ber, rejected by parse_der.
    let non_canonical_bool = [0x01u8, 0x01, 0x01];
    assert_eq!(
        yasna::parse_ber(&non_canonical_bool, |r| r.read_bool()).expect("valid BER bool"),
        true
    );
    let der_err = yasna::parse_der(&non_canonical_bool, |r| r.read_bool())
        .expect_err("non-canonical DER bool must fail");
    assert_eq!(der_err.kind(), ASN1ErrorKind::Invalid);

    // Trailing bytes are rejected with ASN1ErrorKind::Extra
    let mut trailing = der.clone();
    trailing.push(0x00);
    let extra_err = decode_record(&trailing).expect_err("trailing bytes must fail");
    assert_eq!(extra_err.kind(), ASN1ErrorKind::Extra);

    println!("CONTRACT_OK");
}
tests/contract.rs
use yasna::models::ObjectIdentifier;
use yasna::{ASN1ErrorKind, Tag};

#[test]
fn der_sequence_round_trip() {
    let oid = ObjectIdentifier::from_slice(&[2, 5, 4, 3]);
    let der = yasna::construct_der(|writer| {
        writer.write_sequence(|writer| {
            writer.next().write_i64(123456);
            writer.next().write_bool(false);
            writer.next().write_utf8_string("example");
            writer.next().write_bytes(&[0xde, 0xad, 0xbe, 0xef]);
            writer.next().write_oid(&oid);
            writer
                .next()
                .write_tagged(Tag::context(2), |w| w.write_u64(99));
            writer.next().write_null();
        });
    });

    let decoded = yasna::parse_der(&der, |reader| {
        reader.read_sequence(|reader| {
            let n = reader.next().read_i64()?;
            let b = reader.next().read_bool()?;
            let s = reader.next().read_utf8string()?;
            let raw = reader.next().read_bytes()?;
            let parsed_oid = reader.next().read_oid()?;
            let tagged = reader
                .next()
                .read_tagged(Tag::context(2), |r| r.read_u64())?;
            reader.next().read_null()?;
            Ok((n, b, s, raw, parsed_oid, tagged))
        })
    })
    .expect("DER sequence should decode");

    assert_eq!(decoded.0, 123456);
    assert!(!decoded.1);
    assert_eq!(decoded.2, "example");
    assert_eq!(decoded.3, vec![0xde, 0xad, 0xbe, 0xef]);
    assert_eq!(decoded.4.components().as_slice(), &[2, 5, 4, 3]);
    assert_eq!(decoded.5, 99);
}

#[test]
fn der_strictness_and_error_kinds() {
    // Non-canonical boolean: valid BER, invalid DER
    let ber_true = [0x01u8, 0x01, 0x05];
    assert_eq!(
        yasna::parse_ber(&ber_true, |r| r.read_bool()).expect("BER bool"),
        true
    );
    let err = yasna::parse_der(&ber_true, |r| r.read_bool()).expect_err("DER rejects 0x05 bool");
    assert_eq!(err.kind(), ASN1ErrorKind::Invalid);

    // Truncated input returns Eof
    let truncated = [0x30u8, 0x05, 0x02, 0x01];
    let eof_err = yasna::parse_der(&truncated, |r| r.read_sequence(|r| r.next().read_i64()))
        .expect_err("truncated DER fails");
    assert_eq!(eof_err.kind(), ASN1ErrorKind::Eof);

    // Trailing data returns Extra
    let with_extra = [0x05u8, 0x00, 0xff];
    let extra_err = yasna::parse_der(&with_extra, |r| r.read_null())
        .expect_err("trailing byte must fail");
    assert_eq!(extra_err.kind(), ASN1ErrorKind::Extra);
}

Seeder de origen

anónimo