CodeSampleX

Exemplo

@noble/hashes 1.4.0: hexToBytes

Amostra verificada para npm @noble/hashes 1.4.0: hexToBytes. O contrato rodou em node 22 · linux debian/x64 · docker e passou.

sha256:d62a2dc77bd9521f6ca286115bcae75ebb8d6c6adec9a867d7683c3bbb3fcdd5

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
node 22 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2…
2026-09-04

Caso

HOW
Objetivo
verify @noble/hashes.hexToBytes in pkg:npm/%40noble/hashes@1.4.0
Pacotes
Símbolos
  • @noble/hashes.hexToBytes
Ambiente
node 22.23.2
Criado
2026-09-04T12:18:18Z

Contrato

  1. assert hexToBytes converts valid even-length hex string to Uint8Array byte values
  2. assert hexToBytes supports uppercase and mixed-case hex representations
  3. assert hexToBytes converts empty string to 0-length Uint8Array
  4. assert hexToBytes and bytesToHex form bidirectional round-trip conversions
  5. assert hexToBytes throws on non-string input
  6. assert hexToBytes throws on unpadded odd-length hex string
  7. assert hexToBytes throws on non-hex characters with character and index detail

Arquivos

  • PROMPT.md
  • csx.json
  • index.js
  • package-lock.json
  • package.json
  • spec.json
  • test/contract.mjs

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

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 @noble/hashes.hexToBytes in pkg:npm/%40noble/hashes@1.4.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40noble/hashes@1.4.0
Demonstrate these symbols/APIs:
  - @noble/hashes.hexToBytes

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:d9c5d6077c23040497a9e577015e640f0b095c90623beac693086d116bae114c","contract":["assert hexToBytes converts valid even-length hex string to Uint8Array byte values","assert hexToBytes supports uppercase and mixed-case hex representations","assert hexToBytes converts empty string to 0-length Uint8Array","assert hexToBytes and bytesToHex form bidirectional round-trip conversions","assert hexToBytes throws on non-string input","assert hexToBytes throws on unpadded odd-length hex string","assert hexToBytes throws on non-hex characters with character and index detail"],"goal":"verify @noble/hashes.hexToBytes in pkg:npm/%40noble/hashes@1.4.0","kind":"HOW","packages":["pkg:npm/%40noble/hashes@1.4.0"],"schemaVersion":1,"symbols":["@noble/hashes.hexToBytes"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/%40noble/hashes@1.4.0"],"schemaVersion":1,"subject":"pkg:npm/%40noble/hashes@1.4.0","symbols":["@noble/hashes.hexToBytes"],"verifierAdapter":"node-typescript@1"}
index.js
const { hexToBytes, bytesToHex } = require('@noble/hashes/utils');

/**
 * Converts a hex string to a Uint8Array byte buffer.
 * @param {string} hex - Even-length hexadecimal string
 * @returns {Uint8Array}
 */
function decodeHex(hex) {
  return hexToBytes(hex);
}

/**
 * Converts a Uint8Array byte buffer to a lowercase hex string.
 * @param {Uint8Array} bytes
 * @returns {string}
 */
function encodeHex(bytes) {
  return bytesToHex(bytes);
}

/**
 * Validates whether the given value is a valid hex-encoded string accepted by hexToBytes.
 * @param {unknown} value
 * @returns {boolean}
 */
function isValidHex(value) {
  if (typeof value !== 'string' || value.length % 2 !== 0) {
    return false;
  }
  try {
    hexToBytes(value);
    return true;
  } catch {
    return false;
  }
}

/**
 * Round-trips a hex string through hexToBytes and bytesToHex.
 * Normalizes uppercase or mixed-case hex to lowercase.
 * @param {string} hex
 * @returns {string}
 */
function normalizeHex(hex) {
  return bytesToHex(hexToBytes(hex));
}

module.exports = {
  hexToBytes,
  bytesToHex,
  decodeHex,
  encodeHex,
  isValidHex,
  normalizeHex,
};
package-lock.json
{
  "name": "sample-noble-hashes-hextobytes",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-noble-hashes-hextobytes",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "@noble/hashes": "1.4.0"
      }
    },
    "node_modules/@noble/hashes": {
      "version": "1.4.0",
      "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.4.0.tgz",
      "integrity": "sha512-V1JJ1WTRUqHHrOSh597hURcMqVKVGL/ea3kv0gSnEdsEZ0/+VyPghM1lMNGc00z7CIQorSvbKpuJkxvuHbvdbg==",
      "license": "MIT",
      "engines": {
        "node": ">= 16"
      },
      "funding": {
        "url": "https://paulmillr.com/funding/"
      }
    }
  }
}
package.json
{
  "name": "sample-noble-hashes-hextobytes",
  "version": "1.0.0",
  "private": true,
  "description": "verify @noble/hashes.hexToBytes in pkg:npm/%40noble/hashes@1.4.0",
  "main": "index.js",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "@noble/hashes": "1.4.0"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify @noble/hashes.hexToBytes in pkg:npm/%40noble/hashes@1.4.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40noble/hashes@1.4.0"
  ],
  "symbols": [
    "@noble/hashes.hexToBytes"
  ]
}
test/contract.mjs
import assert from 'node:assert';
import { hexToBytes, bytesToHex } from '@noble/hashes/utils';
import {
  decodeHex,
  encodeHex,
  isValidHex,
  normalizeHex,
} from '../index.js';

// 1. Convert standard lowercase hex string to Uint8Array
const standardBytes = hexToBytes('0123456789abcdef');
assert(standardBytes instanceof Uint8Array, 'hexToBytes must return an instance of Uint8Array');
assert.strictEqual(standardBytes.length, 8, 'Hex string of 16 characters must yield 8 bytes');
assert.deepStrictEqual(
  Array.from(standardBytes),
  [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef],
  'Byte values must match expected decoded hex bytes'
);

// 2. Uppercase and mixed-case hex string decoding
const upperBytes = hexToBytes('DEADBEEF');
assert.deepStrictEqual(
  Array.from(upperBytes),
  [0xde, 0xad, 0xbe, 0xef],
  'Uppercase hex string must decode correctly'
);

const mixedBytes = hexToBytes('0a1B2c3D4e5F');
assert.deepStrictEqual(
  Array.from(mixedBytes),
  [0x0a, 0x1b, 0x2c, 0x3d, 0x4e, 0x5f],
  'Mixed-case hex string must decode correctly'
);

// 3. Empty string produces 0-length Uint8Array
const emptyBytes = hexToBytes('');
assert(emptyBytes instanceof Uint8Array, 'Empty hex string must return Uint8Array');
assert.strictEqual(emptyBytes.length, 0, 'Empty hex string must produce 0-length buffer');

// 4. Bidirectional round-trip between hexToBytes and bytesToHex
const testPayload = new Uint8Array([0x00, 0x10, 0x7f, 0x80, 0xff]);
const hexEncoded = bytesToHex(testPayload);
assert.strictEqual(hexEncoded, '00107f80ff', 'bytesToHex must produce lowercase hex');
assert.deepStrictEqual(
  hexToBytes(hexEncoded),
  testPayload,
  'hexToBytes must invert bytesToHex accurately'
);
assert.strictEqual(
  normalizeHex('00107F80FF'),
  '00107f80ff',
  'Round-trip normalization must convert uppercase hex to canonical lowercase hex'
);

// 5. Throws TypeError / Error on non-string input
assert.throws(
  () => hexToBytes(12345),
  /hex string expected, got number/,
  'hexToBytes must reject number input'
);
assert.throws(
  () => hexToBytes(null),
  /hex string expected, got object/,
  'hexToBytes must reject null input'
);
assert.throws(
  () => hexToBytes(undefined),
  /hex string expected, got undefined/,
  'hexToBytes must reject undefined input'
);

// 6. Throws on unpadded (odd-length) hex string
assert.throws(
  () => hexToBytes('abc'),
  /padded hex string expected, got unpadded hex of length 3/,
  'hexToBytes must reject odd-length hex strings'
);
assert.throws(
  () => hexToBytes('f'),
  /padded hex string expected, got unpadded hex of length 1/,
  'hexToBytes must reject single-char hex string'
);

// 7. Throws on non-hex characters with index and character detail
assert.throws(
  () => hexToBytes('012g'),
  /hex string expected, got non-hex character "2g" at index 2/,
  'hexToBytes must reject invalid hex character "g"'
);
assert.throws(
  () => hexToBytes('zz'),
  /hex string expected, got non-hex character "zz" at index 0/,
  'hexToBytes must reject non-hex character at index 0'
);

// 8. Module wrapper helpers
assert.strictEqual(isValidHex('cafebabe'), true, 'isValidHex returns true for valid hex');
assert.strictEqual(isValidHex('not_hex!'), false, 'isValidHex returns false for invalid hex');
assert.strictEqual(isValidHex('abc'), false, 'isValidHex returns false for odd-length string');
assert.strictEqual(isValidHex(null), false, 'isValidHex returns false for non-string input');

const decoded = decodeHex('feedface');
assert.strictEqual(encodeHex(decoded), 'feedface', 'encodeHex must encode decoded bytes back to feedface');

console.log('All @noble/hashes.hexToBytes contract assertions passed.');

Seeder de origem

anônimo