utils.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
  2. // 100 lines of code in the file are duplicated from noble-hashes (utils).
  3. // This is OK: `abstract` directory does not use noble-hashes.
  4. // User may opt-in into using different hashing library. This way, noble-hashes
  5. // won't be included into their bundle.
  6. const _0n = /* @__PURE__ */ BigInt(0);
  7. const _1n = /* @__PURE__ */ BigInt(1);
  8. const _2n = /* @__PURE__ */ BigInt(2);
  9. export function isBytes(a) {
  10. return (a instanceof Uint8Array ||
  11. (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));
  12. }
  13. export function abytes(item) {
  14. if (!isBytes(item))
  15. throw new Error('Uint8Array expected');
  16. }
  17. // Array where index 0xf0 (240) is mapped to string 'f0'
  18. const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
  19. /**
  20. * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
  21. */
  22. export function bytesToHex(bytes) {
  23. abytes(bytes);
  24. // pre-caching improves the speed 6x
  25. let hex = '';
  26. for (let i = 0; i < bytes.length; i++) {
  27. hex += hexes[bytes[i]];
  28. }
  29. return hex;
  30. }
  31. export function numberToHexUnpadded(num) {
  32. const hex = num.toString(16);
  33. return hex.length & 1 ? `0${hex}` : hex;
  34. }
  35. export function hexToNumber(hex) {
  36. if (typeof hex !== 'string')
  37. throw new Error('hex string expected, got ' + typeof hex);
  38. // Big Endian
  39. return BigInt(hex === '' ? '0' : `0x${hex}`);
  40. }
  41. // We use optimized technique to convert hex string to byte array
  42. const asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };
  43. function asciiToBase16(char) {
  44. if (char >= asciis._0 && char <= asciis._9)
  45. return char - asciis._0;
  46. if (char >= asciis._A && char <= asciis._F)
  47. return char - (asciis._A - 10);
  48. if (char >= asciis._a && char <= asciis._f)
  49. return char - (asciis._a - 10);
  50. return;
  51. }
  52. /**
  53. * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
  54. */
  55. export function hexToBytes(hex) {
  56. if (typeof hex !== 'string')
  57. throw new Error('hex string expected, got ' + typeof hex);
  58. const hl = hex.length;
  59. const al = hl / 2;
  60. if (hl % 2)
  61. throw new Error('padded hex string expected, got unpadded hex of length ' + hl);
  62. const array = new Uint8Array(al);
  63. for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
  64. const n1 = asciiToBase16(hex.charCodeAt(hi));
  65. const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
  66. if (n1 === undefined || n2 === undefined) {
  67. const char = hex[hi] + hex[hi + 1];
  68. throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
  69. }
  70. array[ai] = n1 * 16 + n2;
  71. }
  72. return array;
  73. }
  74. // BE: Big Endian, LE: Little Endian
  75. export function bytesToNumberBE(bytes) {
  76. return hexToNumber(bytesToHex(bytes));
  77. }
  78. export function bytesToNumberLE(bytes) {
  79. abytes(bytes);
  80. return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
  81. }
  82. export function numberToBytesBE(n, len) {
  83. return hexToBytes(n.toString(16).padStart(len * 2, '0'));
  84. }
  85. export function numberToBytesLE(n, len) {
  86. return numberToBytesBE(n, len).reverse();
  87. }
  88. // Unpadded, rarely used
  89. export function numberToVarBytesBE(n) {
  90. return hexToBytes(numberToHexUnpadded(n));
  91. }
  92. /**
  93. * Takes hex string or Uint8Array, converts to Uint8Array.
  94. * Validates output length.
  95. * Will throw error for other types.
  96. * @param title descriptive title for an error e.g. 'private key'
  97. * @param hex hex string or Uint8Array
  98. * @param expectedLength optional, will compare to result array's length
  99. * @returns
  100. */
  101. export function ensureBytes(title, hex, expectedLength) {
  102. let res;
  103. if (typeof hex === 'string') {
  104. try {
  105. res = hexToBytes(hex);
  106. }
  107. catch (e) {
  108. throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`);
  109. }
  110. }
  111. else if (isBytes(hex)) {
  112. // Uint8Array.from() instead of hash.slice() because node.js Buffer
  113. // is instance of Uint8Array, and its slice() creates **mutable** copy
  114. res = Uint8Array.from(hex);
  115. }
  116. else {
  117. throw new Error(`${title} must be hex string or Uint8Array`);
  118. }
  119. const len = res.length;
  120. if (typeof expectedLength === 'number' && len !== expectedLength)
  121. throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);
  122. return res;
  123. }
  124. /**
  125. * Copies several Uint8Arrays into one.
  126. */
  127. export function concatBytes(...arrays) {
  128. let sum = 0;
  129. for (let i = 0; i < arrays.length; i++) {
  130. const a = arrays[i];
  131. abytes(a);
  132. sum += a.length;
  133. }
  134. const res = new Uint8Array(sum);
  135. for (let i = 0, pad = 0; i < arrays.length; i++) {
  136. const a = arrays[i];
  137. res.set(a, pad);
  138. pad += a.length;
  139. }
  140. return res;
  141. }
  142. // Compares 2 u8a-s in kinda constant time
  143. export function equalBytes(a, b) {
  144. if (a.length !== b.length)
  145. return false;
  146. let diff = 0;
  147. for (let i = 0; i < a.length; i++)
  148. diff |= a[i] ^ b[i];
  149. return diff === 0;
  150. }
  151. /**
  152. * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
  153. */
  154. export function utf8ToBytes(str) {
  155. if (typeof str !== 'string')
  156. throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
  157. return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
  158. }
  159. // Bit operations
  160. /**
  161. * Calculates amount of bits in a bigint.
  162. * Same as `n.toString(2).length`
  163. */
  164. export function bitLen(n) {
  165. let len;
  166. for (len = 0; n > _0n; n >>= _1n, len += 1)
  167. ;
  168. return len;
  169. }
  170. /**
  171. * Gets single bit at position.
  172. * NOTE: first bit position is 0 (same as arrays)
  173. * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`
  174. */
  175. export function bitGet(n, pos) {
  176. return (n >> BigInt(pos)) & _1n;
  177. }
  178. /**
  179. * Sets single bit at position.
  180. */
  181. export function bitSet(n, pos, value) {
  182. return n | ((value ? _1n : _0n) << BigInt(pos));
  183. }
  184. /**
  185. * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
  186. * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
  187. */
  188. export const bitMask = (n) => (_2n << BigInt(n - 1)) - _1n;
  189. // DRBG
  190. const u8n = (data) => new Uint8Array(data); // creates Uint8Array
  191. const u8fr = (arr) => Uint8Array.from(arr); // another shortcut
  192. /**
  193. * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
  194. * @returns function that will call DRBG until 2nd arg returns something meaningful
  195. * @example
  196. * const drbg = createHmacDRBG<Key>(32, 32, hmac);
  197. * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
  198. */
  199. export function createHmacDrbg(hashLen, qByteLen, hmacFn) {
  200. if (typeof hashLen !== 'number' || hashLen < 2)
  201. throw new Error('hashLen must be a number');
  202. if (typeof qByteLen !== 'number' || qByteLen < 2)
  203. throw new Error('qByteLen must be a number');
  204. if (typeof hmacFn !== 'function')
  205. throw new Error('hmacFn must be a function');
  206. // Step B, Step C: set hashLen to 8*ceil(hlen/8)
  207. let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
  208. let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same
  209. let i = 0; // Iterations counter, will throw when over 1000
  210. const reset = () => {
  211. v.fill(1);
  212. k.fill(0);
  213. i = 0;
  214. };
  215. const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)
  216. const reseed = (seed = u8n()) => {
  217. // HMAC-DRBG reseed() function. Steps D-G
  218. k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)
  219. v = h(); // v = hmac(k || v)
  220. if (seed.length === 0)
  221. return;
  222. k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)
  223. v = h(); // v = hmac(k || v)
  224. };
  225. const gen = () => {
  226. // HMAC-DRBG generate() function
  227. if (i++ >= 1000)
  228. throw new Error('drbg: tried 1000 values');
  229. let len = 0;
  230. const out = [];
  231. while (len < qByteLen) {
  232. v = h();
  233. const sl = v.slice();
  234. out.push(sl);
  235. len += v.length;
  236. }
  237. return concatBytes(...out);
  238. };
  239. const genUntil = (seed, pred) => {
  240. reset();
  241. reseed(seed); // Steps D-G
  242. let res = undefined; // Step H: grind until k is in [1..n-1]
  243. while (!(res = pred(gen())))
  244. reseed();
  245. reset();
  246. return res;
  247. };
  248. return genUntil;
  249. }
  250. // Validating curves and fields
  251. const validatorFns = {
  252. bigint: (val) => typeof val === 'bigint',
  253. function: (val) => typeof val === 'function',
  254. boolean: (val) => typeof val === 'boolean',
  255. string: (val) => typeof val === 'string',
  256. stringOrUint8Array: (val) => typeof val === 'string' || isBytes(val),
  257. isSafeInteger: (val) => Number.isSafeInteger(val),
  258. array: (val) => Array.isArray(val),
  259. field: (val, object) => object.Fp.isValid(val),
  260. hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),
  261. };
  262. // type Record<K extends string | number | symbol, T> = { [P in K]: T; }
  263. export function validateObject(object, validators, optValidators = {}) {
  264. const checkField = (fieldName, type, isOptional) => {
  265. const checkVal = validatorFns[type];
  266. if (typeof checkVal !== 'function')
  267. throw new Error(`Invalid validator "${type}", expected function`);
  268. const val = object[fieldName];
  269. if (isOptional && val === undefined)
  270. return;
  271. if (!checkVal(val, object)) {
  272. throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`);
  273. }
  274. };
  275. for (const [fieldName, type] of Object.entries(validators))
  276. checkField(fieldName, type, false);
  277. for (const [fieldName, type] of Object.entries(optValidators))
  278. checkField(fieldName, type, true);
  279. return object;
  280. }
  281. // validate type tests
  282. // const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };
  283. // const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!
  284. // // Should fail type-check
  285. // const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });
  286. // const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });
  287. // const z3 = validateObject(o, { test: 'boolean', z: 'bug' });
  288. // const z4 = validateObject(o, { a: 'boolean', z: 'bug' });
  289. //# sourceMappingURL=utils.js.map