{"ast":null,"code":"/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// 100 lines of code in the file are duplicated from noble-hashes (utils).\n// This is OK: `abstract` directory does not use noble-hashes.\n// User may opt-in into using different hashing library. This way, noble-hashes\n// won't be included into their bundle.\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst u8a = a => a instanceof Uint8Array;\nconst hexes = /* @__PURE__ */Array.from({\n  length: 256\n}, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n  if (!u8a(bytes)) throw new Error('Uint8Array expected');\n  // pre-caching improves the speed 6x\n  let hex = '';\n  for (let i = 0; i < bytes.length; i++) {\n    hex += hexes[bytes[i]];\n  }\n  return hex;\n}\nexport function numberToHexUnpadded(num) {\n  const hex = num.toString(16);\n  return hex.length & 1 ? `0${hex}` : hex;\n}\nexport function hexToNumber(hex) {\n  if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n  // Big Endian\n  return BigInt(hex === '' ? '0' : `0x${hex}`);\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n  if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n  const len = hex.length;\n  if (len % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + len);\n  const array = new Uint8Array(len / 2);\n  for (let i = 0; i < array.length; i++) {\n    const j = i * 2;\n    const hexByte = hex.slice(j, j + 2);\n    const byte = Number.parseInt(hexByte, 16);\n    if (Number.isNaN(byte) || byte < 0) throw new Error('Invalid byte sequence');\n    array[i] = byte;\n  }\n  return array;\n}\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes) {\n  return hexToNumber(bytesToHex(bytes));\n}\nexport function bytesToNumberLE(bytes) {\n  if (!u8a(bytes)) throw new Error('Uint8Array expected');\n  return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n}\nexport function numberToBytesBE(n, len) {\n  return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n, len) {\n  return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n) {\n  return hexToBytes(numberToHexUnpadded(n));\n}\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'private key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title, hex, expectedLength) {\n  let res;\n  if (typeof hex === 'string') {\n    try {\n      res = hexToBytes(hex);\n    } catch (e) {\n      throw new Error(`${title} must be valid hex string, got \"${hex}\". Cause: ${e}`);\n    }\n  } else if (u8a(hex)) {\n    // Uint8Array.from() instead of hash.slice() because node.js Buffer\n    // is instance of Uint8Array, and its slice() creates **mutable** copy\n    res = Uint8Array.from(hex);\n  } else {\n    throw new Error(`${title} must be hex string or Uint8Array`);\n  }\n  const len = res.length;\n  if (typeof expectedLength === 'number' && len !== expectedLength) throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);\n  return res;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n  const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));\n  let pad = 0; // walk through each item, ensure they have proper type\n  arrays.forEach(a => {\n    if (!u8a(a)) throw new Error('Uint8Array expected');\n    r.set(a, pad);\n    pad += a.length;\n  });\n  return r;\n}\nexport function equalBytes(b1, b2) {\n  // We don't care about timing attacks here\n  if (b1.length !== b2.length) return false;\n  for (let i = 0; i < b1.length; i++) if (b1[i] !== b2[i]) return false;\n  return true;\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n  if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n  return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n// Bit operations\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n */\nexport function bitLen(n) {\n  let len;\n  for (len = 0; n > _0n; n >>= _1n, len += 1);\n  return len;\n}\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n, pos) {\n  return n >> BigInt(pos) & _1n;\n}\n/**\n * Sets single bit at position.\n */\nexport const bitSet = (n, pos, value) => {\n  return n | (value ? _1n : _0n) << BigInt(pos);\n};\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = n => (_2n << BigInt(n - 1)) - _1n;\n// DRBG\nconst u8n = data => new Uint8Array(data); // creates Uint8Array\nconst u8fr = arr => Uint8Array.from(arr); // another shortcut\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n *   const drbg = createHmacDRBG<Key>(32, 32, hmac);\n *   drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg(hashLen, qByteLen, hmacFn) {\n  if (typeof hashLen !== 'number' || hashLen < 2) throw new Error('hashLen must be a number');\n  if (typeof qByteLen !== 'number' || qByteLen < 2) throw new Error('qByteLen must be a number');\n  if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function');\n  // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n  let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n  let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n  let i = 0; // Iterations counter, will throw when over 1000\n  const reset = () => {\n    v.fill(1);\n    k.fill(0);\n    i = 0;\n  };\n  const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n  const reseed = (seed = u8n()) => {\n    // HMAC-DRBG reseed() function. Steps D-G\n    k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)\n    v = h(); // v = hmac(k || v)\n    if (seed.length === 0) return;\n    k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)\n    v = h(); // v = hmac(k || v)\n  };\n  const gen = () => {\n    // HMAC-DRBG generate() function\n    if (i++ >= 1000) throw new Error('drbg: tried 1000 values');\n    let len = 0;\n    const out = [];\n    while (len < qByteLen) {\n      v = h();\n      const sl = v.slice();\n      out.push(sl);\n      len += v.length;\n    }\n    return concatBytes(...out);\n  };\n  const genUntil = (seed, pred) => {\n    reset();\n    reseed(seed); // Steps D-G\n    let res = undefined; // Step H: grind until k is in [1..n-1]\n    while (!(res = pred(gen()))) reseed();\n    reset();\n    return res;\n  };\n  return genUntil;\n}\n// Validating curves and fields\nconst validatorFns = {\n  bigint: val => typeof val === 'bigint',\n  function: val => typeof val === 'function',\n  boolean: val => typeof val === 'boolean',\n  string: val => typeof val === 'string',\n  stringOrUint8Array: val => typeof val === 'string' || val instanceof Uint8Array,\n  isSafeInteger: val => Number.isSafeInteger(val),\n  array: val => Array.isArray(val),\n  field: (val, object) => object.Fp.isValid(val),\n  hash: val => typeof val === 'function' && Number.isSafeInteger(val.outputLen)\n};\n// type Record<K extends string | number | symbol, T> = { [P in K]: T; }\nexport function validateObject(object, validators, optValidators = {}) {\n  const checkField = (fieldName, type, isOptional) => {\n    const checkVal = validatorFns[type];\n    if (typeof checkVal !== 'function') throw new Error(`Invalid validator \"${type}\", expected function`);\n    const val = object[fieldName];\n    if (isOptional && val === undefined) return;\n    if (!checkVal(val, object)) {\n      throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`);\n    }\n  };\n  for (const [fieldName, type] of Object.entries(validators)) checkField(fieldName, type, false);\n  for (const [fieldName, type] of Object.entries(optValidators)) checkField(fieldName, type, true);\n  return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n//# sourceMappingURL=utils.js.map","map":null,"metadata":{},"sourceType":"module","externalDependencies":[]}