@leofcoin/chain 1.10.12 → 1.10.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/exports/beacon-envelope.js +2 -2
  2. package/exports/beacon-epoch.js +1 -1
  3. package/exports/beacon-lifecycle.js +2 -2
  4. package/exports/beacon-round.js +1 -1
  5. package/exports/beacon.js +1 -1
  6. package/exports/browser/beacon-envelope.js +79 -3
  7. package/exports/browser/beacon-epoch.js +2 -1
  8. package/exports/browser/beacon-lifecycle.js +3 -2
  9. package/exports/browser/beacon-round.js +2 -1
  10. package/exports/browser/beacon-wire.js +3 -3
  11. package/exports/browser/beacon.js +3 -2
  12. package/exports/browser/{browser-DvU1xNFS-sdlKNCJc.js → browser-DvU1xNFS-4-PGqr4c.js} +4 -4
  13. package/exports/browser/browser-DvU1xNFS-BJCQsckZ.js +151 -0
  14. package/exports/browser/browser-DvU1xNFS-D9eSzJGJ.js +151 -0
  15. package/exports/browser/browser-crypto-BHeOz9rj.js +8893 -0
  16. package/exports/browser/browser-crypto-CTP3Yk4M.js +8893 -0
  17. package/exports/browser/{proposal.proto-BcUgd885.js → browser-crypto-Yk_e6OHw.js} +35 -6
  18. package/exports/browser/chain.js +63 -321
  19. package/exports/browser/{client-B-jyclOB-CsNYfj4Z.js → client-DDC8C510-CUi3_3uT.js} +36 -12
  20. package/exports/browser/client-DDC8C510-DbIdQjhy.js +2225 -0
  21. package/exports/browser/client-DDC8C510-ZN_MLo1Y.js +2225 -0
  22. package/exports/browser/connection-monitor-BjXI0nBP.js +453 -0
  23. package/exports/browser/connection-monitor-Cf0vNDCA.js +453 -0
  24. package/exports/browser/connection-monitor-pdopeM1I.js +453 -0
  25. package/exports/browser/hkdf-B9AXp_7K.js +222 -0
  26. package/exports/browser/hkdf-CnZvwpZ9.js +222 -0
  27. package/exports/browser/{index-Bxr5Iztg-C6xBk0rK.js → index-Bxr5Iztg-AmkW0EHS.js} +4 -4
  28. package/exports/browser/index-Bxr5Iztg-Bdpw_E83.js +40 -0
  29. package/exports/browser/index-Bxr5Iztg-CxXVYm3t.js +40 -0
  30. package/exports/browser/{index-D7FUx7Dd.js → index-CPQ5yvZ2.js} +5 -6
  31. package/exports/browser/index-C_RakUAS.js +4995 -0
  32. package/exports/browser/index-uFaocBqT.js +4995 -0
  33. package/exports/browser/{messages-FMRAS8QX-CvlZBzy5.js → messages-DH0tgNM9-BRp0gcJh.js} +4 -4
  34. package/exports/browser/messages-DH0tgNM9-CZwrcL37.js +208 -0
  35. package/exports/browser/messages-DH0tgNM9-DkNnpePH.js +208 -0
  36. package/exports/browser/{node-browser-xlqSBOaN.js → node-browser-1VSuCeew.js} +6 -6
  37. package/exports/browser/node-browser-CQugE1WZ.js +17880 -0
  38. package/exports/browser/node-browser-wDmRaOEo.js +17880 -0
  39. package/exports/browser/node-browser.js +4 -4
  40. package/exports/browser/sha2-Dkoic3vb.js +602 -0
  41. package/exports/browser/sha2-piimb6xL.js +614 -0
  42. package/exports/browser/weierstrass-HGdA_prK.js +2156 -0
  43. package/exports/browser/{weierstrass-C-jX_jly.js → weierstrass-Q0QND1ZT.js} +1 -1
  44. package/exports/browser/workers/machine-worker.js +419 -147
  45. package/exports/chain.js +56 -313
  46. package/exports/connection-monitor.js +324 -0
  47. package/exports/node.js +2 -0
  48. package/exports/workers/machine-worker.js +419 -147
  49. package/package.json +4 -4
  50. package/exports/browser/browser-CWeoyGUw-BabtHowB.js +0 -57
  51. package/exports/browser/constants-Cv0p224A.js +0 -130
  52. package/exports/browser/hkdf-DhdhLAAv.js +0 -147
@@ -0,0 +1,614 @@
1
+ // Split a JS number into u32 halves without a BigInt allocation. Exact only for integers
2
+ // `0 <= n < 2**53`; callers use it on byte / bit counters, which JS length math caps far below
3
+ // that (an ArrayBuffer cannot exceed 2**53 - 1 bytes).
4
+ const fromNumH = (n) => (n / 2 ** 32) | 0;
5
+ const fromNumL = (n) => n >>> 0;
6
+ // Drop-in replacement for `view.setBigUint64(byteOffset, BigInt(n), isLE)` without the per-call
7
+ // BigInt allocation. Same `n < 2**53` precondition as `fromNumH`/`fromNumL`.
8
+ function setU64FromNum(view, byteOffset, n, isLE) {
9
+ const h = fromNumH(n);
10
+ const l = fromNumL(n);
11
+ view.setUint32(byteOffset, isLE ? l : h, isLE);
12
+ view.setUint32(byteOffset + 4, isLE ? h : l, isLE);
13
+ }
14
+
15
+ /**
16
+ * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.
17
+ * @param a - value to test
18
+ * @returns `true` when the value is a Uint8Array-compatible view.
19
+ * @example
20
+ * Check whether a value is a Uint8Array-compatible view.
21
+ * ```ts
22
+ * isBytes(new Uint8Array([1, 2, 3]));
23
+ * ```
24
+ */
25
+ function isBytes(a) {
26
+ // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.
27
+ // The fallback still requires a real ArrayBuffer view, so plain
28
+ // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and
29
+ // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.
30
+ return (a instanceof Uint8Array ||
31
+ (ArrayBuffer.isView(a) &&
32
+ a.constructor.name === 'Uint8Array' &&
33
+ 'BYTES_PER_ELEMENT' in a &&
34
+ a.BYTES_PER_ELEMENT === 1));
35
+ }
36
+ // Shared error-message prefix builder. Only called on throw paths, so assert
37
+ // success paths never pay for the string concatenation.
38
+ const atitle = (title) => (title ? `"${title}" ` : '');
39
+ /**
40
+ * Asserts something is a non-negative integer.
41
+ * @param n - number to validate
42
+ * @param title - label included in thrown errors
43
+ * @returns The validated number.
44
+ * @throws On wrong argument types. {@link TypeError}
45
+ * @throws On wrong argument ranges or values. {@link RangeError}
46
+ * @example
47
+ * Validate a non-negative integer option.
48
+ * ```ts
49
+ * anumber(32, 'length');
50
+ * ```
51
+ */
52
+ function anumber(n, title = '') {
53
+ if (typeof n !== 'number')
54
+ throw new TypeError(atitle(title) + 'expected number, got ' + typeof n);
55
+ if (!Number.isSafeInteger(n) || n < 0)
56
+ throw new RangeError(atitle(title) + 'expected integer >= 0, got ' + n);
57
+ return n;
58
+ }
59
+ /**
60
+ * Asserts something is Uint8Array.
61
+ * @param value - value to validate
62
+ * @param length - optional exact length constraint
63
+ * @param title - label included in thrown errors
64
+ * @returns The validated byte array.
65
+ * @throws On wrong argument types. {@link TypeError}
66
+ * @throws On wrong argument ranges or values. {@link RangeError}
67
+ * @example
68
+ * Validate that a value is a byte array.
69
+ * ```ts
70
+ * abytes(new Uint8Array([1, 2, 3]));
71
+ * ```
72
+ */
73
+ function abytes(value, length, title = '') {
74
+ // Success path first: this runs at the start of every update() / digestInto(), and the
75
+ // common `abytes(data)` form must not pay for length handling it does not use.
76
+ if (isBytes(value) && (length === undefined))
77
+ return value;
78
+ const bytes = isBytes(value);
79
+ const ofLen = '';
80
+ const got = bytes ? `length=${value.length}` : `type=${typeof value}`;
81
+ const message = atitle(title) + 'expected Uint8Array' + ofLen + ', got ' + got;
82
+ if (!bytes)
83
+ throw new TypeError(message);
84
+ throw new RangeError(message);
85
+ }
86
+ /**
87
+ * Asserts something is a wrapped hash constructor.
88
+ * @param h - hash constructor to validate
89
+ * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}
90
+ * @throws On invalid hash metadata ranges or values. {@link RangeError}
91
+ * @throws If the hash metadata allows empty outputs or block sizes. {@link Error}
92
+ * @example
93
+ * Validate a callable hash wrapper.
94
+ * ```ts
95
+ * import { ahash } from '@noble/hashes/utils.js';
96
+ * import { sha256 } from '@noble/hashes/sha2.js';
97
+ * ahash(sha256);
98
+ * ```
99
+ */
100
+ function ahash(h) {
101
+ if (typeof h !== 'function' || typeof h.create !== 'function')
102
+ throw new TypeError('expected hash wrapped by utils.createHasher');
103
+ anumber(h.outputLen);
104
+ anumber(h.blockLen);
105
+ // HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass
106
+ // validation and can produce empty outputs instead of failing fast.
107
+ if (h.outputLen < 1 || h.blockLen < 1)
108
+ throw new Error('hash blockLen / outputLen must be >= 1');
109
+ }
110
+ const aobject = (value, label) => {
111
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
112
+ throw new TypeError((label === 'object' ? '' : `"${label}" `) + 'expected object, got type=' + typeof value);
113
+ };
114
+ const aopts = (value, label) => {
115
+ aobject(value, label);
116
+ const proto = Object.getPrototypeOf(value);
117
+ if (proto !== Object.prototype && proto !== null)
118
+ throw new TypeError(`"${label}" expected plain object`);
119
+ // Object.assign() treats an own "__proto__" source key as a write to the target's legacy
120
+ // prototype setter. Reject it before merging so inherited option values cannot be injected.
121
+ if (Object.hasOwn(value, '__proto__'))
122
+ throw new TypeError(`"${label}.__proto__" is not allowed`);
123
+ };
124
+ /**
125
+ * Asserts a hash instance has not been destroyed or finished.
126
+ * @param instance - hash instance to validate
127
+ * @param checkFinished - whether to reject finalized instances
128
+ * @throws If the hash instance has already been destroyed or finalized. {@link Error}
129
+ * @example
130
+ * Validate that a hash instance is still usable.
131
+ * ```ts
132
+ * import { aexists } from '@noble/hashes/utils.js';
133
+ * import { sha256 } from '@noble/hashes/sha2.js';
134
+ * const hash = sha256.create();
135
+ * aexists(hash);
136
+ * ```
137
+ */
138
+ function aexists(instance, checkFinished = true) {
139
+ // Runs on every update()/digestInto(); the flags are library-owned booleans, so only their
140
+ // truthiness is checked - re-validating their type per call was pure hot-path overhead.
141
+ if (instance.destroyed)
142
+ throw new Error('hash was destroyed');
143
+ if (checkFinished && instance.finished)
144
+ throw new Error('digest() was already called');
145
+ }
146
+ /**
147
+ * Asserts output is a sufficiently-sized byte array.
148
+ * @param out - destination buffer
149
+ * @param instance - hash instance providing output length
150
+ * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.
151
+ * @throws On wrong argument types. {@link TypeError}
152
+ * @throws On wrong argument ranges or values. {@link RangeError}
153
+ * @example
154
+ * Validate a caller-provided digest buffer.
155
+ * ```ts
156
+ * import { aoutput } from '@noble/hashes/utils.js';
157
+ * import { sha256 } from '@noble/hashes/sha2.js';
158
+ * const hash = sha256.create();
159
+ * aoutput(new Uint8Array(hash.outputLen), hash);
160
+ * ```
161
+ */
162
+ function aoutput(out, instance) {
163
+ abytes(out, undefined, 'output');
164
+ // `outputLen` is a library-owned readonly number; the negated comparison keeps failing fast
165
+ // when it is missing/NaN (comparisons with undefined/NaN are false) without an anumber() call.
166
+ const min = instance.outputLen;
167
+ if (!(out.length >= min)) {
168
+ throw new RangeError('"output" expected length >= ' + min);
169
+ }
170
+ }
171
+ /**
172
+ * Zeroizes typed arrays in place. Warning: JS provides no guarantees.
173
+ * @param arrays - arrays to overwrite with zeros
174
+ * @example
175
+ * Zeroize sensitive buffers in place.
176
+ * ```ts
177
+ * clean(new Uint8Array([1, 2, 3]));
178
+ * ```
179
+ */
180
+ function clean(...arrays) {
181
+ for (let i = 0; i < arrays.length; i++) {
182
+ arrays[i].fill(0);
183
+ }
184
+ }
185
+ /**
186
+ * Creates a DataView for byte-level manipulation.
187
+ * @param arr - source typed array
188
+ * @returns DataView over the same buffer region.
189
+ * @example
190
+ * Create a DataView over an existing buffer.
191
+ * ```ts
192
+ * createView(new Uint8Array(4));
193
+ * ```
194
+ */
195
+ function createView(arr) {
196
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
197
+ }
198
+ /**
199
+ * Rotate-right operation for uint32 values.
200
+ * @param word - source word
201
+ * @param shift - shift amount in bits
202
+ * @returns Rotated word.
203
+ * @example
204
+ * Rotate a 32-bit word to the right.
205
+ * ```ts
206
+ * rotr(0x12345678, 8);
207
+ * ```
208
+ */
209
+ function rotr(word, shift) {
210
+ return (word << (32 - shift)) | (word >>> shift);
211
+ }
212
+ /**
213
+ * Merges default options and passed options.
214
+ * @param defaults - base option object
215
+ * @param opts - user overrides
216
+ * @param title - label included in thrown override errors
217
+ * @returns Fresh merged option object with a null prototype.
218
+ * @throws On wrong argument types. {@link TypeError}
219
+ * @example
220
+ * Merge user overrides onto default options.
221
+ * ```ts
222
+ * checkOpts({ dkLen: 32 }, { asyncTick: 10 });
223
+ * ```
224
+ */
225
+ function checkOpts(defaults, opts, title = 'opts') {
226
+ aopts(defaults, 'defaults');
227
+ if (opts !== undefined)
228
+ aopts(opts, title);
229
+ // Callers read optional fields directly, so omitted values must not fall through to ambient
230
+ // Object.prototype pollution (for example a forged `dkLen` changing SHAKE's default output).
231
+ const merged = Object.assign(Object.create(null), defaults, opts);
232
+ return merged;
233
+ }
234
+ /**
235
+ * Creates a callable hash function from a stateful class constructor.
236
+ * @param hashCons - hash constructor or factory
237
+ * @param info - optional metadata such as DER OID
238
+ * @returns Frozen callable hash wrapper with `.create()`.
239
+ * Wrapper construction eagerly calls `hashCons(undefined)` once to read
240
+ * `outputLen` / `blockLen`, so constructor side effects happen at module
241
+ * init time.
242
+ * @throws On wrong argument types. {@link TypeError}
243
+ * @example
244
+ * Wrap a stateful hash constructor into a callable helper.
245
+ * ```ts
246
+ * import { createHasher } from '@noble/hashes/utils.js';
247
+ * import { sha256 } from '@noble/hashes/sha2.js';
248
+ * const wrapped = createHasher(sha256.create, { oid: sha256.oid });
249
+ * wrapped(new Uint8Array([1]));
250
+ * ```
251
+ */
252
+ function createHasher(hashCons, info = {}) {
253
+ if (typeof hashCons !== 'function')
254
+ throw new TypeError('"hashCons" expected function, got type=' + typeof hashCons);
255
+ info = checkOpts({}, info, 'info');
256
+ const hashC = (msg, opts) => hashCons(opts)
257
+ .update(msg)
258
+ .digest();
259
+ const tmp = hashCons(undefined);
260
+ hashC.outputLen = tmp.outputLen;
261
+ hashC.blockLen = tmp.blockLen;
262
+ hashC.canXOF = tmp.canXOF;
263
+ hashC.create = (opts) => hashCons(opts);
264
+ Object.assign(hashC, info);
265
+ return Object.freeze(hashC);
266
+ }
267
+ /**
268
+ * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.
269
+ * @param suffix - final OID byte for the selected hash.
270
+ * The helper accepts any byte even though only the documented NIST hash
271
+ * suffixes are meaningful downstream.
272
+ * @returns Object containing the DER-encoded OID.
273
+ * @example
274
+ * Build OID metadata for a NIST hash.
275
+ * ```ts
276
+ * oidNist(0x01);
277
+ * ```
278
+ */
279
+ const oidNist = (suffix) => ({
280
+ // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.
281
+ // Larger suffix values would need base-128 OID encoding and a different length byte.
282
+ oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),
283
+ });
284
+
285
+ /**
286
+ * Internal Merkle-Damgard hash utils.
287
+ * @module
288
+ */
289
+ /**
290
+ * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.
291
+ * Returns bits from `b` when `a` is set, otherwise from `c`.
292
+ * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never
293
+ * set the same bit.
294
+ * @param a - selector word
295
+ * @param b - word chosen when selector bit is set
296
+ * @param c - word chosen when selector bit is clear
297
+ * @returns Mixed 32-bit word.
298
+ * @example
299
+ * Combine three words with the shared 32-bit choice primitive.
300
+ * ```ts
301
+ * Chi(0xffffffff, 0x12345678, 0x87654321);
302
+ * ```
303
+ */
304
+ function Chi(a, b, c) {
305
+ return (a & b) ^ (~a & c);
306
+ }
307
+ /**
308
+ * Shared 32-bit majority primitive reused by SHA-256 and SHA-1.
309
+ * Returns bits shared by at least two inputs.
310
+ * @param a - first input word
311
+ * @param b - second input word
312
+ * @param c - third input word
313
+ * @returns Mixed 32-bit word.
314
+ * @example
315
+ * Combine three words with the shared 32-bit majority primitive.
316
+ * ```ts
317
+ * Maj(0xffffffff, 0x12345678, 0x87654321);
318
+ * ```
319
+ */
320
+ function Maj(a, b, c) {
321
+ return (a & b) ^ (a & c) ^ (b & c);
322
+ }
323
+ /**
324
+ * Merkle-Damgard hash construction base class.
325
+ * Could be used to create MD5, RIPEMD, SHA1, SHA2.
326
+ * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit
327
+ * strings with partial-byte tails.
328
+ * @param blockLen - internal block size in bytes
329
+ * @param outputLen - digest size in bytes
330
+ * @param padOffset - trailing length field size in bytes
331
+ * @param isLE - whether length and state words are encoded in little-endian
332
+ * @example
333
+ * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.
334
+ * ```ts
335
+ * import { _SHA1 } from '@noble/hashes/legacy.js';
336
+ * const hash = new _SHA1();
337
+ * hash.update(new Uint8Array([97, 98, 99]));
338
+ * hash.digest();
339
+ * ```
340
+ */
341
+ class HashMD {
342
+ blockLen;
343
+ outputLen;
344
+ canXOF = false;
345
+ padOffset;
346
+ isLE;
347
+ // For partial updates less than block size
348
+ buffer;
349
+ view;
350
+ finished = false;
351
+ length = 0;
352
+ pos = 0;
353
+ destroyed = false;
354
+ constructor(blockLen, outputLen, padOffset, isLE) {
355
+ this.blockLen = blockLen;
356
+ this.outputLen = outputLen;
357
+ this.padOffset = padOffset;
358
+ this.isLE = isLE;
359
+ this.buffer = new Uint8Array(blockLen);
360
+ this.view = createView(this.buffer);
361
+ }
362
+ update(data) {
363
+ aexists(this);
364
+ abytes(data);
365
+ const { view, buffer, blockLen } = this;
366
+ const len = data.length;
367
+ let processed = false;
368
+ for (let pos = 0; pos < len;) {
369
+ const take = Math.min(blockLen - this.pos, len - pos);
370
+ // Fast path only when there is no buffered partial block: `take === blockLen` implies
371
+ // `this.pos === 0`, so we can process full blocks directly from the input view.
372
+ if (take === blockLen) {
373
+ const dataView = createView(data);
374
+ for (; blockLen <= len - pos; pos += blockLen)
375
+ this.process(dataView, pos);
376
+ processed = true;
377
+ continue;
378
+ }
379
+ // When the whole input is buffered in one go (common for short messages), passing `data`
380
+ // directly avoids allocating a subarray view.
381
+ buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);
382
+ this.pos += take;
383
+ pos += take;
384
+ if (this.pos === blockLen) {
385
+ this.process(view, 0);
386
+ this.pos = 0;
387
+ processed = true;
388
+ }
389
+ }
390
+ this.length += data.length;
391
+ // Shared schedule buffers only pick up input-derived words inside process(); if everything
392
+ // was buffered without processing, there is nothing to zero.
393
+ if (processed)
394
+ this.roundClean();
395
+ return this;
396
+ }
397
+ digestInto(out) {
398
+ aexists(this);
399
+ aoutput(out, this);
400
+ this.finished = true;
401
+ // Padding
402
+ // We can avoid allocation of buffer for padding completely if it
403
+ // was previously not allocated here. But it won't change performance.
404
+ const { buffer, view, blockLen, isLE } = this;
405
+ let { pos } = this;
406
+ // append the bit '1' to the message, then zero-pad the rest of the block
407
+ buffer[pos++] = 0b10000000;
408
+ buffer.fill(0, pos);
409
+ // we have less than padOffset left in buffer, so we cannot put length in
410
+ // current block, need process it and pad again
411
+ if (this.padOffset > blockLen - pos) {
412
+ this.process(view, 0);
413
+ buffer.fill(0);
414
+ }
415
+ // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from
416
+ // the padding fill above, and JS will overflow before user input can make that half non-zero.
417
+ // So we only need to write the low 64 bits here (`length * 8` only scales the exponent of an
418
+ // integer below 2**53, so the split inside the helper stays exact).
419
+ setU64FromNum(view, blockLen - 8, this.length * 8, isLE);
420
+ this.process(view, 0);
421
+ // The final block above is processed outside update(), so the shared message-schedule
422
+ // buffers (e.g. SHA256_W) would otherwise retain input-derived words after digest().
423
+ this.roundClean();
424
+ // digest() passes our own `buffer` as `out`; reuse its cached view instead of allocating one.
425
+ const oview = out === buffer ? view : createView(out);
426
+ const len = this.outputLen;
427
+ // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT
428
+ const outLen = len / 4;
429
+ const state = this.get();
430
+ // Subclass-misconfiguration invariant: outputLen must be 32-bit aligned and fit the state.
431
+ if (len % 4 || outLen > state.length)
432
+ throw new Error('invalid outputLen');
433
+ for (let i = 0; i < outLen; i++)
434
+ oview.setUint32(4 * i, state[i], isLE);
435
+ }
436
+ digest() {
437
+ const { buffer, outputLen } = this;
438
+ this.digestInto(buffer);
439
+ // Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return
440
+ // fresh bytes to the caller.
441
+ const res = buffer.slice(0, outputLen);
442
+ this.destroy();
443
+ return res;
444
+ }
445
+ _cloneIntoMeta(to) {
446
+ const { buffer, length, finished, destroyed, pos } = this;
447
+ to.destroyed = destroyed;
448
+ to.finished = finished;
449
+ to.length = length;
450
+ to.pos = pos;
451
+ // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and
452
+ // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.
453
+ if (pos)
454
+ to.buffer.set(buffer); // Avoid a hot modulo guard.
455
+ return to;
456
+ }
457
+ clone() {
458
+ return this._cloneInto();
459
+ }
460
+ }
461
+ /**
462
+ * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
463
+ * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
464
+ */
465
+ /** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the
466
+ * square roots of the first eight prime numbers. Exported as a shared table; callers must treat
467
+ * it as read-only because constructors copy words from it by index. */
468
+ const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
469
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
470
+ ]);
471
+
472
+ /**
473
+ * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
474
+ * SHA256 is the fastest hash implementable in JS, even faster than Blake3.
475
+ * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and
476
+ * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.
477
+ * @module
478
+ */
479
+ /**
480
+ * SHA-224 / SHA-256 round constants from RFC 6234 §5.1: the first 32 bits
481
+ * of the cube roots of the first 64 primes (2..311).
482
+ */
483
+ // prettier-ignore
484
+ const SHA256_K = /* @__PURE__ */ Uint32Array.from([
485
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
486
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
487
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
488
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
489
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
490
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
491
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
492
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
493
+ ]);
494
+ /** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 §6.2 step 1. */
495
+ const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
496
+ /** Internal SHA-224 / SHA-256 compression engine from RFC 6234 §6.2. */
497
+ class SHA2_32B extends HashMD {
498
+ // We cannot use array here since array allows indexing by variable
499
+ // which means optimizer/compiler cannot use registers.
500
+ // Numeric initializers matter: starting the fields as `undefined` changes
501
+ // V8's field representation and makes sha256 3x slower (measured).
502
+ A = 0;
503
+ B = 0;
504
+ C = 0;
505
+ D = 0;
506
+ E = 0;
507
+ F = 0;
508
+ G = 0;
509
+ H = 0;
510
+ constructor(outputLen, IV) {
511
+ super(64, outputLen, 8, false);
512
+ this.A = IV[0] | 0;
513
+ this.B = IV[1] | 0;
514
+ this.C = IV[2] | 0;
515
+ this.D = IV[3] | 0;
516
+ this.E = IV[4] | 0;
517
+ this.F = IV[5] | 0;
518
+ this.G = IV[6] | 0;
519
+ this.H = IV[7] | 0;
520
+ }
521
+ get() {
522
+ const { A, B, C, D, E, F, G, H } = this;
523
+ return [A, B, C, D, E, F, G, H];
524
+ }
525
+ // prettier-ignore
526
+ set(A, B, C, D, E, F, G, H) {
527
+ this.A = A | 0;
528
+ this.B = B | 0;
529
+ this.C = C | 0;
530
+ this.D = D | 0;
531
+ this.E = E | 0;
532
+ this.F = F | 0;
533
+ this.G = G | 0;
534
+ this.H = H | 0;
535
+ }
536
+ _cloneInto(to) {
537
+ (to ||= new this.constructor()).set(...this.get());
538
+ return this._cloneIntoMeta(to);
539
+ }
540
+ process(view, offset) {
541
+ // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
542
+ for (let i = 0; i < 16; i++, offset += 4)
543
+ SHA256_W[i] = view.getUint32(offset, false);
544
+ for (let i = 16; i < 64; i++) {
545
+ const W15 = SHA256_W[i - 15];
546
+ const W2 = SHA256_W[i - 2];
547
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);
548
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);
549
+ SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
550
+ }
551
+ // Compression function main loop, 64 rounds
552
+ let { A, B, C, D, E, F, G, H } = this;
553
+ for (let i = 0; i < 64; i++) {
554
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
555
+ const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
556
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
557
+ const T2 = (sigma0 + Maj(A, B, C)) | 0;
558
+ H = G;
559
+ G = F;
560
+ F = E;
561
+ E = (D + T1) | 0;
562
+ D = C;
563
+ C = B;
564
+ B = A;
565
+ A = (T1 + T2) | 0;
566
+ }
567
+ // Add the compressed chunk to the current hash value
568
+ A = (A + this.A) | 0;
569
+ B = (B + this.B) | 0;
570
+ C = (C + this.C) | 0;
571
+ D = (D + this.D) | 0;
572
+ E = (E + this.E) | 0;
573
+ F = (F + this.F) | 0;
574
+ G = (G + this.G) | 0;
575
+ H = (H + this.H) | 0;
576
+ this.set(A, B, C, D, E, F, G, H);
577
+ }
578
+ roundClean() {
579
+ clean(SHA256_W);
580
+ }
581
+ destroy() {
582
+ // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves
583
+ // update()/digest() callable on reused instances.
584
+ this.destroyed = true;
585
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
586
+ clean(this.buffer);
587
+ }
588
+ }
589
+ /** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */
590
+ class _SHA256 extends SHA2_32B {
591
+ constructor() {
592
+ super(32, SHA256_IV);
593
+ }
594
+ }
595
+ /**
596
+ * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:
597
+ *
598
+ * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.
599
+ * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
600
+ * - Each sha256 hash is executing 2^18 bit operations.
601
+ * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.
602
+ * @param msg - message bytes to hash
603
+ * @param opts - Reserved hash options.
604
+ * @returns Digest bytes.
605
+ * @example
606
+ * Hash a message with SHA2-256.
607
+ * ```ts
608
+ * sha256(new Uint8Array([97, 98, 99]));
609
+ * ```
610
+ */
611
+ const sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(),
612
+ /* @__PURE__ */ oidNist(0x01));
613
+
614
+ export { ahash as a, abytes as b, clean as c, aexists as d, aoutput as e, anumber as f, sha256 as s };