CodeSampleX

Пример

@noble/hashes 2.3.0: sha256

Проверенный пример — npm @noble/hashes 2.3.0: sha256. Контракт выполнен на node 22 · linux debian/x64 · docker и пройден: sha256 is exported as a callable…

sha256:11c0cc0500f6f78891901bbee004fefa0c2d2001074b30e4feb0abbcd19a7ff4

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

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

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

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

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

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

Кейс

HOW
Цель
verify @noble/hashes.sha256 in pkg:npm/%40noble/hashes@2.3.0
Пакеты
Символы
  • @noble/hashes.sha256
Окружение
node 22.23.2
Создан
2026-09-06T16:13:11Z

Контракт

  1. sha256 is exported as a callable function from @noble/hashes/sha2.js
  2. sha256 strictly requires Uint8Array inputs and throws TypeError on string inputs
  3. sha256 produces exact 32-byte digest matching standard NIST test vectors for empty, ASCII, and multi-block byte inputs
  4. sha256 exposes outputLen as 32 bytes and blockLen as 64 bytes
  5. sha256.create supports incremental streaming hash updates via update and digest with Uint8Array inputs
  6. sha256 incremental hash instance supports clone to independently branch hash computation
  7. sha256 incremental hash instance supports digestInto to write digest into pre-allocated Uint8Array
  8. sha256 incremental hash instance supports destroy which cleans state and prevents further updates
  9. module wrapper helpers hashSha256, hashSha256Hex, and hashChunksHex accept string and Uint8Array inputs to compute correct digests

Файлы

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

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

Исходный код

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

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

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:f2b1c392030a086e76f7579bcddf5b3a1fed3f5d400c4ce3c8454646141eadc2","contract":["sha256 is exported as a callable function from @noble/hashes/sha2.js","sha256 strictly requires Uint8Array inputs and throws TypeError on string inputs","sha256 produces exact 32-byte digest matching standard NIST test vectors for empty, ASCII, and multi-block byte inputs","sha256 exposes outputLen as 32 bytes and blockLen as 64 bytes","sha256.create supports incremental streaming hash updates via update and digest with Uint8Array inputs","sha256 incremental hash instance supports clone to independently branch hash computation","sha256 incremental hash instance supports digestInto to write digest into pre-allocated Uint8Array","sha256 incremental hash instance supports destroy which cleans state and prevents further updates","module wrapper helpers hashSha256, hashSha256Hex, and hashChunksHex accept string and Uint8Array inputs to compute correct digests"],"goal":"verify @noble/hashes.sha256 in pkg:npm/%40noble/hashes@2.3.0","kind":"HOW","packages":["pkg:npm/%40noble/hashes@2.3.0"],"schemaVersion":1,"symbols":["@noble/hashes.sha256"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"esm","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@2.3.0"],"schemaVersion":1,"subject":"pkg:npm/%40noble/hashes@2.3.0","symbols":["@noble/hashes.sha256"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-noble-hashes-sha256",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-noble-hashes-sha256",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "@noble/hashes": "2.3.0"
      }
    },
    "node_modules/@noble/hashes": {
      "version": "2.3.0",
      "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.3.0.tgz",
      "integrity": "sha512-oN+QwyX7VSHotibwubG3kpzbwKrfnyR6OOO+3Nk/53ADL7FmgHHz4TgrbaYKvvOw09u6QTx0oiH1cNCIOuN0CQ==",
      "license": "MIT",
      "engines": {
        "node": ">= 20.19.0"
      },
      "funding": {
        "url": "https://paulmillr.com/funding/"
      }
    }
  }
}
package.json
{
  "name": "sample-noble-hashes-sha256",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "description": "Clean-room code sample for @noble/hashes sha256",
  "main": "src/index.js",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "@noble/hashes": "2.3.0"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify @noble/hashes.sha256 in pkg:npm/%40noble/hashes@2.3.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40noble/hashes@2.3.0"
  ],
  "symbols": [
    "@noble/hashes.sha256"
  ]
}
src/index.js
import { sha256 } from '@noble/hashes/sha2.js';
import { bytesToHex, utf8ToBytes } from '@noble/hashes/utils.js';

/**
 * Normalizes input to Uint8Array, encoding strings as UTF-8.
 * In @noble/hashes v2, functions strictly require Uint8Array inputs.
 * @param {string | Uint8Array} input
 * @returns {Uint8Array}
 */
export function toBytes(input) {
  if (typeof input === 'string') {
    return utf8ToBytes(input);
  }
  return input;
}

/**
 * Computes the SHA-256 hash of a string or Uint8Array and returns the raw 32-byte Uint8Array digest.
 * @param {string | Uint8Array} input
 * @returns {Uint8Array}
 */
export function hashSha256(input) {
  return sha256(toBytes(input));
}

/**
 * Computes the SHA-256 hash of a string or Uint8Array and returns a lowercase hex string.
 * @param {string | Uint8Array} input
 * @returns {string}
 */
export function hashSha256Hex(input) {
  return bytesToHex(sha256(toBytes(input)));
}

/**
 * Creates an incremental SHA-256 hasher.
 * @returns {ReturnType<typeof sha256.create>}
 */
export function createSha256Hasher() {
  return sha256.create();
}

/**
 * Computes SHA-256 hash over an array of sequential chunks.
 * @param {Array<string | Uint8Array>} chunks
 * @returns {string}
 */
export function hashChunksHex(chunks) {
  const hasher = sha256.create();
  for (const chunk of chunks) {
    hasher.update(toBytes(chunk));
  }
  return bytesToHex(hasher.digest());
}

export { sha256, bytesToHex, utf8ToBytes };
test/contract.mjs
import assert from 'node:assert/strict';
import { sha256 as directSha256 } from '@noble/hashes/sha2.js';
import { bytesToHex, utf8ToBytes } from '@noble/hashes/utils.js';
import {
  sha256,
  toBytes,
  hashSha256,
  hashSha256Hex,
  createSha256Hasher,
  hashChunksHex,
} from '../src/index.js';

// 1. sha256 is exported as a callable function from @noble/hashes/sha2.js
assert.equal(typeof directSha256, 'function', 'sha256 must be a function');
assert.equal(typeof sha256, 'function', 're-exported sha256 must be a function');

// 2. sha256 strictly requires Uint8Array inputs and throws TypeError on string inputs
{
  assert.throws(
    () => directSha256('string-input'),
    {
      name: 'TypeError',
      message: /expected Uint8Array/,
    },
    'sha256 must throw TypeError when given a string'
  );
  assert.throws(
    () => {
      const hasher = directSha256.create();
      hasher.update('string-input');
    },
    {
      name: 'TypeError',
      message: /expected Uint8Array/,
    },
    'hasher.update must throw TypeError when given a string'
  );
}

// 3. sha256 produces exact 32-byte digest matching standard NIST test vectors for empty, ASCII, and multi-block byte inputs
{
  const emptyBytes = new Uint8Array(0);
  const emptyDigest = directSha256(emptyBytes);
  assert.equal(emptyDigest.length, 32, 'Empty input digest length must be 32 bytes');
  assert.equal(
    bytesToHex(emptyDigest),
    'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855',
    'Empty input digest must match NIST vector'
  );

  const abcBytes = utf8ToBytes('abc');
  const abcDigest = directSha256(abcBytes);
  assert.equal(abcDigest.length, 32, 'abc digest length must be 32 bytes');
  assert.equal(
    bytesToHex(abcDigest),
    'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad',
    'abc digest must match NIST vector'
  );

  const multiBlockMsg = 'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq';
  const multiBlockDigest = directSha256(utf8ToBytes(multiBlockMsg));
  assert.equal(multiBlockDigest.length, 32, 'multi-block digest length must be 32 bytes');
  assert.equal(
    bytesToHex(multiBlockDigest),
    '248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1',
    'multi-block digest must match NIST vector'
  );
}

// 4. sha256 exposes outputLen as 32 bytes and blockLen as 64 bytes
assert.equal(directSha256.outputLen, 32, 'sha256.outputLen must be 32 bytes');
assert.equal(directSha256.blockLen, 64, 'sha256.blockLen must be 64 bytes');

// 5. sha256.create supports incremental streaming hash updates via update and digest with Uint8Array inputs
{
  const hasher = directSha256.create();
  hasher.update(utf8ToBytes('abc'));
  hasher.update(utf8ToBytes('dbcd'));
  hasher.update(utf8ToBytes('ecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'));
  const digestHex = bytesToHex(hasher.digest());
  assert.equal(
    digestHex,
    '248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1',
    'Incremental sha256 stream must match expected multi-block digest'
  );
}

// 6. sha256 incremental hash instance supports clone to independently branch hash computation
{
  const base = directSha256.create();
  base.update(utf8ToBytes('common prefix: '));
  const branchA = base.clone();
  const branchB = base.clone();
  branchA.update(utf8ToBytes('action_alpha'));
  branchB.update(utf8ToBytes('action_beta'));

  assert.equal(
    bytesToHex(branchA.digest()),
    bytesToHex(directSha256(utf8ToBytes('common prefix: action_alpha'))),
    'Cloned branch A must compute independent digest'
  );
  assert.equal(
    bytesToHex(branchB.digest()),
    bytesToHex(directSha256(utf8ToBytes('common prefix: action_beta'))),
    'Cloned branch B must compute independent digest'
  );
}

// 7. sha256 incremental hash instance supports digestInto to write digest into pre-allocated Uint8Array
{
  const outBuf = new Uint8Array(32);
  const hasher = directSha256.create();
  hasher.update(utf8ToBytes('abc'));
  hasher.digestInto(outBuf);
  assert.equal(
    bytesToHex(outBuf),
    'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad',
    'digestInto must write digest into target Uint8Array buffer'
  );
}

// 8. sha256 incremental hash instance supports destroy which cleans state and prevents further updates
{
  const hasher = directSha256.create();
  hasher.update(utf8ToBytes('sensitive data'));
  hasher.destroy();
  assert.throws(
    () => hasher.update(utf8ToBytes('more data')),
    /destroyed/,
    'Calling update after destroy must throw'
  );
}

// 9. module wrapper helpers hashSha256, hashSha256Hex, and hashChunksHex accept string and Uint8Array inputs to compute correct digests
{
  const rawFromStr = hashSha256('abc');
  const rawFromBytes = hashSha256(utf8ToBytes('abc'));
  assert(rawFromStr instanceof Uint8Array, 'hashSha256 must return Uint8Array');
  assert.equal(rawFromStr.length, 32, 'hashSha256 length must be 32');
  assert.equal(bytesToHex(rawFromStr), bytesToHex(rawFromBytes), 'String and byte input must produce identical hash');

  assert.equal(
    hashSha256Hex('abc'),
    'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad',
    'hashSha256Hex must return correct lowercase hex string'
  );

  const chunksHex = hashChunksHex(['abc', 'dbcd', utf8ToBytes('ecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq')]);
  assert.equal(
    chunksHex,
    '248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1',
    'hashChunksHex must match expected multi-block digest'
  );
}

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

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

аноним