@leofcoin/chain 1.10.13 → 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 +16 -295
  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-CFBGfpG1.js → index-CPQ5yvZ2.js} +1 -2
  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 +400 -135
  45. package/exports/chain.js +13 -291
  46. package/exports/connection-monitor.js +324 -0
  47. package/exports/node.js +2 -0
  48. package/exports/workers/machine-worker.js +400 -135
  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
@@ -6434,201 +6434,434 @@ const instrumentContractSource = (source) => {
6434
6434
  return output;
6435
6435
  };
6436
6436
 
6437
- function bytes(b, ...lengths) {
6438
- if (!(b instanceof Uint8Array))
6439
- throw new Error('Expected Uint8Array');
6440
- if (lengths.length > 0 && !lengths.includes(b.length))
6441
- throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);
6437
+ // Split a JS number into u32 halves without a BigInt allocation. Exact only for integers
6438
+ // `0 <= n < 2**53`; callers use it on byte / bit counters, which JS length math caps far below
6439
+ // that (an ArrayBuffer cannot exceed 2**53 - 1 bytes).
6440
+ const fromNumH = (n) => (n / 2 ** 32) | 0;
6441
+ const fromNumL = (n) => n >>> 0;
6442
+ // Drop-in replacement for `view.setBigUint64(byteOffset, BigInt(n), isLE)` without the per-call
6443
+ // BigInt allocation. Same `n < 2**53` precondition as `fromNumH`/`fromNumL`.
6444
+ function setU64FromNum(view, byteOffset, n, isLE) {
6445
+ const h = fromNumH(n);
6446
+ const l = fromNumL(n);
6447
+ view.setUint32(byteOffset, isLE ? l : h, isLE);
6448
+ view.setUint32(byteOffset + 4, isLE ? h : l, isLE);
6442
6449
  }
6443
- function exists(instance, checkFinished = true) {
6450
+
6451
+ /**
6452
+ * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.
6453
+ * @param a - value to test
6454
+ * @returns `true` when the value is a Uint8Array-compatible view.
6455
+ * @example
6456
+ * Check whether a value is a Uint8Array-compatible view.
6457
+ * ```ts
6458
+ * isBytes(new Uint8Array([1, 2, 3]));
6459
+ * ```
6460
+ */
6461
+ function isBytes(a) {
6462
+ // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.
6463
+ // The fallback still requires a real ArrayBuffer view, so plain
6464
+ // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and
6465
+ // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.
6466
+ return (a instanceof Uint8Array ||
6467
+ (ArrayBuffer.isView(a) &&
6468
+ a.constructor.name === 'Uint8Array' &&
6469
+ 'BYTES_PER_ELEMENT' in a &&
6470
+ a.BYTES_PER_ELEMENT === 1));
6471
+ }
6472
+ // Shared error-message prefix builder. Only called on throw paths, so assert
6473
+ // success paths never pay for the string concatenation.
6474
+ const atitle = (title) => (title ? `"${title}" ` : '');
6475
+ /**
6476
+ * Asserts something is Uint8Array.
6477
+ * @param value - value to validate
6478
+ * @param length - optional exact length constraint
6479
+ * @param title - label included in thrown errors
6480
+ * @returns The validated byte array.
6481
+ * @throws On wrong argument types. {@link TypeError}
6482
+ * @throws On wrong argument ranges or values. {@link RangeError}
6483
+ * @example
6484
+ * Validate that a value is a byte array.
6485
+ * ```ts
6486
+ * abytes(new Uint8Array([1, 2, 3]));
6487
+ * ```
6488
+ */
6489
+ function abytes(value, length, title = '') {
6490
+ // Success path first: this runs at the start of every update() / digestInto(), and the
6491
+ // common `abytes(data)` form must not pay for length handling it does not use.
6492
+ if (isBytes(value) && (length === undefined))
6493
+ return value;
6494
+ const bytes = isBytes(value);
6495
+ const ofLen = '';
6496
+ const got = bytes ? `length=${value.length}` : `type=${typeof value}`;
6497
+ const message = atitle(title) + 'expected Uint8Array' + ofLen + ', got ' + got;
6498
+ if (!bytes)
6499
+ throw new TypeError(message);
6500
+ throw new RangeError(message);
6501
+ }
6502
+ const aobject = (value, label) => {
6503
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
6504
+ throw new TypeError((label === 'object' ? '' : `"${label}" `) + 'expected object, got type=' + typeof value);
6505
+ };
6506
+ /**
6507
+ * Asserts a hash instance has not been destroyed or finished.
6508
+ * @param instance - hash instance to validate
6509
+ * @param checkFinished - whether to reject finalized instances
6510
+ * @throws If the hash instance has already been destroyed or finalized. {@link Error}
6511
+ * @example
6512
+ * Validate that a hash instance is still usable.
6513
+ * ```ts
6514
+ * import { aexists } from '@noble/hashes/utils.js';
6515
+ * import { sha256 } from '@noble/hashes/sha2.js';
6516
+ * const hash = sha256.create();
6517
+ * aexists(hash);
6518
+ * ```
6519
+ */
6520
+ function aexists(instance, checkFinished = true) {
6521
+ // Runs on every update()/digestInto(); the flags are library-owned booleans, so only their
6522
+ // truthiness is checked - re-validating their type per call was pure hot-path overhead.
6444
6523
  if (instance.destroyed)
6445
- throw new Error('Hash instance has been destroyed');
6524
+ throw new Error('hash was destroyed');
6446
6525
  if (checkFinished && instance.finished)
6447
- throw new Error('Hash#digest() has already been called');
6526
+ throw new Error('digest() was already called');
6448
6527
  }
6449
- function output(out, instance) {
6450
- bytes(out);
6528
+ /**
6529
+ * Asserts output is a sufficiently-sized byte array.
6530
+ * @param out - destination buffer
6531
+ * @param instance - hash instance providing output length
6532
+ * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.
6533
+ * @throws On wrong argument types. {@link TypeError}
6534
+ * @throws On wrong argument ranges or values. {@link RangeError}
6535
+ * @example
6536
+ * Validate a caller-provided digest buffer.
6537
+ * ```ts
6538
+ * import { aoutput } from '@noble/hashes/utils.js';
6539
+ * import { sha256 } from '@noble/hashes/sha2.js';
6540
+ * const hash = sha256.create();
6541
+ * aoutput(new Uint8Array(hash.outputLen), hash);
6542
+ * ```
6543
+ */
6544
+ function aoutput(out, instance) {
6545
+ abytes(out, undefined, 'output');
6546
+ // `outputLen` is a library-owned readonly number; the negated comparison keeps failing fast
6547
+ // when it is missing/NaN (comparisons with undefined/NaN are false) without an anumber() call.
6451
6548
  const min = instance.outputLen;
6452
- if (out.length < min) {
6453
- throw new Error(`digestInto() expects output buffer of length at least ${min}`);
6549
+ if (!(out.length >= min)) {
6550
+ throw new RangeError('"output" expected length >= ' + min);
6454
6551
  }
6455
6552
  }
6456
-
6457
- /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
6458
- // We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
6459
- // node.js versions earlier than v19 don't declare it in global scope.
6460
- // For node.js, package.json#exports field mapping rewrites import
6461
- // from `crypto` to `cryptoNode`, which imports native module.
6462
- // Makes the utils un-importable in browsers without a bundler.
6463
- // Once node.js 18 is deprecated, we can just drop the import.
6464
- const u8a = (a) => a instanceof Uint8Array;
6465
- // Cast array to view
6466
- const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
6467
- // The rotate right (circular right shift) operation for uint32
6468
- const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);
6469
- // big-endian hardware is rare. Just in case someone still decides to run hashes:
6470
- // early-throw an error because we don't support BE yet.
6471
- const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;
6472
- if (!isLE)
6473
- throw new Error('Non little-endian hardware is not supported');
6474
6553
  /**
6475
- * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
6554
+ * Zeroizes typed arrays in place. Warning: JS provides no guarantees.
6555
+ * @param arrays - arrays to overwrite with zeros
6556
+ * @example
6557
+ * Zeroize sensitive buffers in place.
6558
+ * ```ts
6559
+ * clean(new Uint8Array([1, 2, 3]));
6560
+ * ```
6476
6561
  */
6477
- function utf8ToBytes(str) {
6478
- if (typeof str !== 'string')
6479
- throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
6480
- return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
6562
+ function clean(...arrays) {
6563
+ for (let i = 0; i < arrays.length; i++) {
6564
+ arrays[i].fill(0);
6565
+ }
6481
6566
  }
6482
6567
  /**
6483
- * Normalizes (non-hex) string or Uint8Array to Uint8Array.
6484
- * Warning: when Uint8Array is passed, it would NOT get copied.
6485
- * Keep in mind for future mutable operations.
6568
+ * Creates a DataView for byte-level manipulation.
6569
+ * @param arr - source typed array
6570
+ * @returns DataView over the same buffer region.
6571
+ * @example
6572
+ * Create a DataView over an existing buffer.
6573
+ * ```ts
6574
+ * createView(new Uint8Array(4));
6575
+ * ```
6486
6576
  */
6487
- function toBytes(data) {
6488
- if (typeof data === 'string')
6489
- data = utf8ToBytes(data);
6490
- if (!u8a(data))
6491
- throw new Error(`expected Uint8Array, got ${typeof data}`);
6492
- return data;
6577
+ function createView(arr) {
6578
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
6493
6579
  }
6494
- // For runtime check if class implements interface
6495
- class Hash {
6496
- // Safe version that clones internal state
6497
- clone() {
6498
- return this._cloneInto();
6499
- }
6580
+ /**
6581
+ * Rotate-right operation for uint32 values.
6582
+ * @param word - source word
6583
+ * @param shift - shift amount in bits
6584
+ * @returns Rotated word.
6585
+ * @example
6586
+ * Rotate a 32-bit word to the right.
6587
+ * ```ts
6588
+ * rotr(0x12345678, 8);
6589
+ * ```
6590
+ */
6591
+ function rotr(word, shift) {
6592
+ return (word << (32 - shift)) | (word >>> shift);
6500
6593
  }
6501
- function wrapConstructor(hashCons) {
6502
- const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
6503
- const tmp = hashCons();
6594
+ /**
6595
+ * Merges default options and passed options.
6596
+ * @param defaults - base option object
6597
+ * @param opts - user overrides
6598
+ * @param title - label included in thrown override errors
6599
+ * @returns Merged option object. The merge mutates `defaults` in place.
6600
+ * @throws On wrong argument types. {@link TypeError}
6601
+ * @example
6602
+ * Merge user overrides onto default options.
6603
+ * ```ts
6604
+ * checkOpts({ dkLen: 32 }, { asyncTick: 10 });
6605
+ * ```
6606
+ */
6607
+ function checkOpts(defaults, opts, title = 'opts') {
6608
+ aobject(defaults, 'defaults');
6609
+ if (opts !== undefined)
6610
+ aobject(opts, title);
6611
+ const merged = Object.assign(defaults, opts);
6612
+ return merged;
6613
+ }
6614
+ /**
6615
+ * Creates a callable hash function from a stateful class constructor.
6616
+ * @param hashCons - hash constructor or factory
6617
+ * @param info - optional metadata such as DER OID
6618
+ * @returns Frozen callable hash wrapper with `.create()`.
6619
+ * Wrapper construction eagerly calls `hashCons(undefined)` once to read
6620
+ * `outputLen` / `blockLen`, so constructor side effects happen at module
6621
+ * init time.
6622
+ * @throws On wrong argument types. {@link TypeError}
6623
+ * @example
6624
+ * Wrap a stateful hash constructor into a callable helper.
6625
+ * ```ts
6626
+ * import { createHasher } from '@noble/hashes/utils.js';
6627
+ * import { sha256 } from '@noble/hashes/sha2.js';
6628
+ * const wrapped = createHasher(sha256.create, { oid: sha256.oid });
6629
+ * wrapped(new Uint8Array([1]));
6630
+ * ```
6631
+ */
6632
+ function createHasher(hashCons, info = {}) {
6633
+ if (typeof hashCons !== 'function')
6634
+ throw new TypeError('"hashCons" expected function, got type=' + typeof hashCons);
6635
+ info = checkOpts({}, info, 'info');
6636
+ const hashC = (msg, opts) => hashCons(opts)
6637
+ .update(msg)
6638
+ .digest();
6639
+ const tmp = hashCons(undefined);
6504
6640
  hashC.outputLen = tmp.outputLen;
6505
6641
  hashC.blockLen = tmp.blockLen;
6506
- hashC.create = () => hashCons();
6507
- return hashC;
6642
+ hashC.canXOF = tmp.canXOF;
6643
+ hashC.create = (opts) => hashCons(opts);
6644
+ Object.assign(hashC, info);
6645
+ return Object.freeze(hashC);
6508
6646
  }
6647
+ /**
6648
+ * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.
6649
+ * @param suffix - final OID byte for the selected hash.
6650
+ * The helper accepts any byte even though only the documented NIST hash
6651
+ * suffixes are meaningful downstream.
6652
+ * @returns Object containing the DER-encoded OID.
6653
+ * @example
6654
+ * Build OID metadata for a NIST hash.
6655
+ * ```ts
6656
+ * oidNist(0x01);
6657
+ * ```
6658
+ */
6659
+ const oidNist = (suffix) => ({
6660
+ // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.
6661
+ // Larger suffix values would need base-128 OID encoding and a different length byte.
6662
+ oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),
6663
+ });
6509
6664
 
6510
- // Polyfill for Safari 14
6511
- function setBigUint64(view, byteOffset, value, isLE) {
6512
- if (typeof view.setBigUint64 === 'function')
6513
- return view.setBigUint64(byteOffset, value, isLE);
6514
- const _32n = BigInt(32);
6515
- const _u32_max = BigInt(0xffffffff);
6516
- const wh = Number((value >> _32n) & _u32_max);
6517
- const wl = Number(value & _u32_max);
6518
- const h = isLE ? 4 : 0;
6519
- const l = isLE ? 0 : 4;
6520
- view.setUint32(byteOffset + h, wh, isLE);
6521
- view.setUint32(byteOffset + l, wl, isLE);
6665
+ /**
6666
+ * Internal Merkle-Damgard hash utils.
6667
+ * @module
6668
+ */
6669
+ /**
6670
+ * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.
6671
+ * Returns bits from `b` when `a` is set, otherwise from `c`.
6672
+ * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never
6673
+ * set the same bit.
6674
+ * @param a - selector word
6675
+ * @param b - word chosen when selector bit is set
6676
+ * @param c - word chosen when selector bit is clear
6677
+ * @returns Mixed 32-bit word.
6678
+ * @example
6679
+ * Combine three words with the shared 32-bit choice primitive.
6680
+ * ```ts
6681
+ * Chi(0xffffffff, 0x12345678, 0x87654321);
6682
+ * ```
6683
+ */
6684
+ function Chi(a, b, c) {
6685
+ return (a & b) ^ (~a & c);
6522
6686
  }
6523
- // Base SHA2 class (RFC 6234)
6524
- class SHA2 extends Hash {
6687
+ /**
6688
+ * Shared 32-bit majority primitive reused by SHA-256 and SHA-1.
6689
+ * Returns bits shared by at least two inputs.
6690
+ * @param a - first input word
6691
+ * @param b - second input word
6692
+ * @param c - third input word
6693
+ * @returns Mixed 32-bit word.
6694
+ * @example
6695
+ * Combine three words with the shared 32-bit majority primitive.
6696
+ * ```ts
6697
+ * Maj(0xffffffff, 0x12345678, 0x87654321);
6698
+ * ```
6699
+ */
6700
+ function Maj(a, b, c) {
6701
+ return (a & b) ^ (a & c) ^ (b & c);
6702
+ }
6703
+ /**
6704
+ * Merkle-Damgard hash construction base class.
6705
+ * Could be used to create MD5, RIPEMD, SHA1, SHA2.
6706
+ * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit
6707
+ * strings with partial-byte tails.
6708
+ * @param blockLen - internal block size in bytes
6709
+ * @param outputLen - digest size in bytes
6710
+ * @param padOffset - trailing length field size in bytes
6711
+ * @param isLE - whether length and state words are encoded in little-endian
6712
+ * @example
6713
+ * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.
6714
+ * ```ts
6715
+ * import { _SHA1 } from '@noble/hashes/legacy.js';
6716
+ * const hash = new _SHA1();
6717
+ * hash.update(new Uint8Array([97, 98, 99]));
6718
+ * hash.digest();
6719
+ * ```
6720
+ */
6721
+ class HashMD {
6722
+ blockLen;
6723
+ outputLen;
6724
+ canXOF = false;
6725
+ padOffset;
6726
+ isLE;
6727
+ // For partial updates less than block size
6728
+ buffer;
6729
+ view;
6730
+ finished = false;
6731
+ length = 0;
6732
+ pos = 0;
6733
+ destroyed = false;
6525
6734
  constructor(blockLen, outputLen, padOffset, isLE) {
6526
- super();
6527
6735
  this.blockLen = blockLen;
6528
6736
  this.outputLen = outputLen;
6529
6737
  this.padOffset = padOffset;
6530
6738
  this.isLE = isLE;
6531
- this.finished = false;
6532
- this.length = 0;
6533
- this.pos = 0;
6534
- this.destroyed = false;
6535
6739
  this.buffer = new Uint8Array(blockLen);
6536
6740
  this.view = createView(this.buffer);
6537
6741
  }
6538
6742
  update(data) {
6539
- exists(this);
6743
+ aexists(this);
6744
+ abytes(data);
6540
6745
  const { view, buffer, blockLen } = this;
6541
- data = toBytes(data);
6542
6746
  const len = data.length;
6747
+ let processed = false;
6543
6748
  for (let pos = 0; pos < len;) {
6544
6749
  const take = Math.min(blockLen - this.pos, len - pos);
6545
- // Fast path: we have at least one block in input, cast it to view and process
6750
+ // Fast path only when there is no buffered partial block: `take === blockLen` implies
6751
+ // `this.pos === 0`, so we can process full blocks directly from the input view.
6546
6752
  if (take === blockLen) {
6547
6753
  const dataView = createView(data);
6548
6754
  for (; blockLen <= len - pos; pos += blockLen)
6549
6755
  this.process(dataView, pos);
6756
+ processed = true;
6550
6757
  continue;
6551
6758
  }
6552
- buffer.set(data.subarray(pos, pos + take), this.pos);
6759
+ // When the whole input is buffered in one go (common for short messages), passing `data`
6760
+ // directly avoids allocating a subarray view.
6761
+ buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);
6553
6762
  this.pos += take;
6554
6763
  pos += take;
6555
6764
  if (this.pos === blockLen) {
6556
6765
  this.process(view, 0);
6557
6766
  this.pos = 0;
6767
+ processed = true;
6558
6768
  }
6559
6769
  }
6560
6770
  this.length += data.length;
6561
- this.roundClean();
6771
+ // Shared schedule buffers only pick up input-derived words inside process(); if everything
6772
+ // was buffered without processing, there is nothing to zero.
6773
+ if (processed)
6774
+ this.roundClean();
6562
6775
  return this;
6563
6776
  }
6564
6777
  digestInto(out) {
6565
- exists(this);
6566
- output(out, this);
6778
+ aexists(this);
6779
+ aoutput(out, this);
6567
6780
  this.finished = true;
6568
6781
  // Padding
6569
6782
  // We can avoid allocation of buffer for padding completely if it
6570
6783
  // was previously not allocated here. But it won't change performance.
6571
6784
  const { buffer, view, blockLen, isLE } = this;
6572
6785
  let { pos } = this;
6573
- // append the bit '1' to the message
6786
+ // append the bit '1' to the message, then zero-pad the rest of the block
6574
6787
  buffer[pos++] = 0b10000000;
6575
- this.buffer.subarray(pos).fill(0);
6576
- // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again
6788
+ buffer.fill(0, pos);
6789
+ // we have less than padOffset left in buffer, so we cannot put length in
6790
+ // current block, need process it and pad again
6577
6791
  if (this.padOffset > blockLen - pos) {
6578
6792
  this.process(view, 0);
6579
- pos = 0;
6793
+ buffer.fill(0);
6580
6794
  }
6581
- // Pad until full block byte with zeros
6582
- for (let i = pos; i < blockLen; i++)
6583
- buffer[i] = 0;
6584
- // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
6585
- // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
6586
- // So we just write lowest 64 bits of that value.
6587
- setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
6795
+ // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from
6796
+ // the padding fill above, and JS will overflow before user input can make that half non-zero.
6797
+ // So we only need to write the low 64 bits here (`length * 8` only scales the exponent of an
6798
+ // integer below 2**53, so the split inside the helper stays exact).
6799
+ setU64FromNum(view, blockLen - 8, this.length * 8, isLE);
6588
6800
  this.process(view, 0);
6589
- const oview = createView(out);
6801
+ // The final block above is processed outside update(), so the shared message-schedule
6802
+ // buffers (e.g. SHA256_W) would otherwise retain input-derived words after digest().
6803
+ this.roundClean();
6804
+ // digest() passes our own `buffer` as `out`; reuse its cached view instead of allocating one.
6805
+ const oview = out === buffer ? view : createView(out);
6590
6806
  const len = this.outputLen;
6591
- // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
6592
- if (len % 4)
6593
- throw new Error('_sha2: outputLen should be aligned to 32bit');
6807
+ // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT
6594
6808
  const outLen = len / 4;
6595
6809
  const state = this.get();
6596
- if (outLen > state.length)
6597
- throw new Error('_sha2: outputLen bigger than state');
6810
+ // Subclass-misconfiguration invariant: outputLen must be 32-bit aligned and fit the state.
6811
+ if (len % 4 || outLen > state.length)
6812
+ throw new Error('invalid outputLen');
6598
6813
  for (let i = 0; i < outLen; i++)
6599
6814
  oview.setUint32(4 * i, state[i], isLE);
6600
6815
  }
6601
6816
  digest() {
6602
6817
  const { buffer, outputLen } = this;
6603
6818
  this.digestInto(buffer);
6819
+ // Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return
6820
+ // fresh bytes to the caller.
6604
6821
  const res = buffer.slice(0, outputLen);
6605
6822
  this.destroy();
6606
6823
  return res;
6607
6824
  }
6608
- _cloneInto(to) {
6609
- to || (to = new this.constructor());
6610
- to.set(...this.get());
6611
- const { blockLen, buffer, length, finished, destroyed, pos } = this;
6825
+ _cloneIntoMeta(to) {
6826
+ const { buffer, length, finished, destroyed, pos } = this;
6827
+ to.destroyed = destroyed;
6828
+ to.finished = finished;
6612
6829
  to.length = length;
6613
6830
  to.pos = pos;
6614
- to.finished = finished;
6615
- to.destroyed = destroyed;
6616
- if (length % blockLen)
6617
- to.buffer.set(buffer);
6831
+ // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and
6832
+ // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.
6833
+ if (pos)
6834
+ to.buffer.set(buffer); // Avoid a hot modulo guard.
6618
6835
  return to;
6619
6836
  }
6837
+ clone() {
6838
+ return this._cloneInto();
6839
+ }
6620
6840
  }
6841
+ /**
6842
+ * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
6843
+ * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
6844
+ */
6845
+ /** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the
6846
+ * square roots of the first eight prime numbers. Exported as a shared table; callers must treat
6847
+ * it as read-only because constructors copy words from it by index. */
6848
+ const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
6849
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
6850
+ ]);
6621
6851
 
6622
- // SHA2-256 need to try 2^128 hashes to execute birthday attack.
6623
- // BTC network is doing 2^67 hashes/sec as per early 2023.
6624
- // Choice: a ? b : c
6625
- const Chi = (a, b, c) => (a & b) ^ (~a & c);
6626
- // Majority function, true if any two inpust is true
6627
- const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);
6628
- // Round constants:
6629
- // first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)
6852
+ /**
6853
+ * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
6854
+ * SHA256 is the fastest hash implementable in JS, even faster than Blake3.
6855
+ * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and
6856
+ * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.
6857
+ * @module
6858
+ */
6859
+ /**
6860
+ * SHA-224 / SHA-256 round constants from RFC 6234 §5.1: the first 32 bits
6861
+ * of the cube roots of the first 64 primes (2..311).
6862
+ */
6630
6863
  // prettier-ignore
6631
- const SHA256_K = /* @__PURE__ */ new Uint32Array([
6864
+ const SHA256_K = /* @__PURE__ */ Uint32Array.from([
6632
6865
  0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
6633
6866
  0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
6634
6867
  0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
@@ -6638,19 +6871,24 @@ const SHA256_K = /* @__PURE__ */ new Uint32Array([
6638
6871
  0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
6639
6872
  0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
6640
6873
  ]);
6641
- // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):
6642
- // prettier-ignore
6643
- const IV = /* @__PURE__ */ new Uint32Array([
6644
- 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
6645
- ]);
6646
- // Temporary buffer, not used to store anything between runs
6647
- // Named this way because it matches specification.
6874
+ /** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 §6.2 step 1. */
6648
6875
  const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
6649
- class SHA256 extends SHA2 {
6650
- constructor() {
6651
- super(64, 32, 8, false);
6652
- // We cannot use array here since array allows indexing by variable
6653
- // which means optimizer/compiler cannot use registers.
6876
+ /** Internal SHA-224 / SHA-256 compression engine from RFC 6234 §6.2. */
6877
+ class SHA2_32B extends HashMD {
6878
+ // We cannot use array here since array allows indexing by variable
6879
+ // which means optimizer/compiler cannot use registers.
6880
+ // Numeric initializers matter: starting the fields as `undefined` changes
6881
+ // V8's field representation and makes sha256 3x slower (measured).
6882
+ A = 0;
6883
+ B = 0;
6884
+ C = 0;
6885
+ D = 0;
6886
+ E = 0;
6887
+ F = 0;
6888
+ G = 0;
6889
+ H = 0;
6890
+ constructor(outputLen, IV) {
6891
+ super(64, outputLen, 8, false);
6654
6892
  this.A = IV[0] | 0;
6655
6893
  this.B = IV[1] | 0;
6656
6894
  this.C = IV[2] | 0;
@@ -6675,6 +6913,10 @@ class SHA256 extends SHA2 {
6675
6913
  this.G = G | 0;
6676
6914
  this.H = H | 0;
6677
6915
  }
6916
+ _cloneInto(to) {
6917
+ (to ||= new this.constructor()).set(...this.get());
6918
+ return this._cloneIntoMeta(to);
6919
+ }
6678
6920
  process(view, offset) {
6679
6921
  // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
6680
6922
  for (let i = 0; i < 16; i++, offset += 4)
@@ -6714,18 +6956,40 @@ class SHA256 extends SHA2 {
6714
6956
  this.set(A, B, C, D, E, F, G, H);
6715
6957
  }
6716
6958
  roundClean() {
6717
- SHA256_W.fill(0);
6959
+ clean(SHA256_W);
6718
6960
  }
6719
6961
  destroy() {
6962
+ // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves
6963
+ // update()/digest() callable on reused instances.
6964
+ this.destroyed = true;
6720
6965
  this.set(0, 0, 0, 0, 0, 0, 0, 0);
6721
- this.buffer.fill(0);
6966
+ clean(this.buffer);
6967
+ }
6968
+ }
6969
+ /** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */
6970
+ class _SHA256 extends SHA2_32B {
6971
+ constructor() {
6972
+ super(32, SHA256_IV);
6722
6973
  }
6723
6974
  }
6724
6975
  /**
6725
- * SHA2-256 hash function
6726
- * @param message - data that would be hashed
6976
+ * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:
6977
+ *
6978
+ * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.
6979
+ * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
6980
+ * - Each sha256 hash is executing 2^18 bit operations.
6981
+ * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.
6982
+ * @param msg - message bytes to hash
6983
+ * @param opts - Reserved hash options.
6984
+ * @returns Digest bytes.
6985
+ * @example
6986
+ * Hash a message with SHA2-256.
6987
+ * ```ts
6988
+ * sha256(new Uint8Array([97, 98, 99]));
6989
+ * ```
6727
6990
  */
6728
- const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());
6991
+ const sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(),
6992
+ /* @__PURE__ */ oidNist(0x01));
6729
6993
 
6730
6994
  const encoder = new TextEncoder();
6731
6995
  const INTEGER_ARRAYS = new Set([
@@ -8161,9 +8425,10 @@ const get = async ({ contract, method, params }) => {
8161
8425
  if (topLevelRead)
8162
8426
  beginExecution(`read:${contract}:${method}:${JSON.stringify(params ?? [], jsonStringifyBigInt$1)}`);
8163
8427
  try {
8164
- if (params?.length > 0)
8165
- return await contracts[contract][method](...params);
8166
- return contracts[contract][method];
8428
+ const member = contracts[contract][method];
8429
+ if (typeof member === 'function')
8430
+ return await member.apply(contracts[contract], params ?? []);
8431
+ return member;
8167
8432
  }
8168
8433
  finally {
8169
8434
  if (topLevelRead) {