@ohos-ports/crypto 0.0.0-stage → 0.3.1-beta.1

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 (121) hide show
  1. package/LICENSE +7 -0
  2. package/README.md +60 -2
  3. package/dist/bech32.d.ts +53 -0
  4. package/dist/bech32.js +187 -0
  5. package/dist/blake2b.d.ts +7 -0
  6. package/dist/blake2b.js +213 -0
  7. package/dist/bls12_318.d.ts +48 -0
  8. package/dist/bls12_318.js +268 -0
  9. package/dist/ed25519.d.ts +55 -0
  10. package/dist/ed25519.js +721 -0
  11. package/dist/hasGlobalWebCrypto.d.ts +1 -0
  12. package/dist/hasGlobalWebCrypto.js +21 -0
  13. package/dist/hmacSHA512.d.ts +6 -0
  14. package/dist/hmacSHA512.js +14 -0
  15. package/dist/index.d.ts +14 -0
  16. package/dist/index.js +30 -0
  17. package/dist/keccak.d.ts +4 -0
  18. package/dist/keccak.js +43 -0
  19. package/dist/kes/constants.d.ts +2 -0
  20. package/dist/kes/constants.js +5 -0
  21. package/dist/kes/index.d.ts +0 -0
  22. package/dist/kes/index.js +0 -0
  23. package/dist/kes/macro/sum_kes.d.ts +15 -0
  24. package/dist/kes/macro/sum_kes.js +9 -0
  25. package/dist/kes/singleKes.d.ts +0 -0
  26. package/dist/kes/singleKes.js +0 -0
  27. package/dist/noble/_assert.d.ts +23 -0
  28. package/dist/noble/_assert.js +55 -0
  29. package/dist/noble/_md.d.ts +29 -0
  30. package/dist/noble/_md.js +170 -0
  31. package/dist/noble/_shortw_utils.d.ts +61 -0
  32. package/dist/noble/_shortw_utils.js +63 -0
  33. package/dist/noble/_u64.d.ts +28 -0
  34. package/dist/noble/_u64.js +116 -0
  35. package/dist/noble/abstract/bls.d.ts +119 -0
  36. package/dist/noble/abstract/bls.js +334 -0
  37. package/dist/noble/abstract/curve.d.ts +83 -0
  38. package/dist/noble/abstract/curve.js +319 -0
  39. package/dist/noble/abstract/edwards.d.ts +85 -0
  40. package/dist/noble/abstract/edwards.js +508 -0
  41. package/dist/noble/abstract/hash-to-curve.d.ts +57 -0
  42. package/dist/noble/abstract/hash-to-curve.js +220 -0
  43. package/dist/noble/abstract/modular.d.ts +122 -0
  44. package/dist/noble/abstract/modular.js +455 -0
  45. package/dist/noble/abstract/montgomery.d.ts +28 -0
  46. package/dist/noble/abstract/montgomery.js +172 -0
  47. package/dist/noble/abstract/utils.d.ts +106 -0
  48. package/dist/noble/abstract/utils.js +442 -0
  49. package/dist/noble/bls12_381.d.ts +95 -0
  50. package/dist/noble/bls12_381.js +1434 -0
  51. package/dist/noble/crypto.d.ts +1 -0
  52. package/dist/noble/crypto.js +4 -0
  53. package/dist/noble/curves/curve.d.ts +69 -0
  54. package/dist/noble/curves/curve.js +167 -0
  55. package/dist/noble/curves/modular.d.ts +122 -0
  56. package/dist/noble/curves/modular.js +442 -0
  57. package/dist/noble/curves/utils.d.ts +93 -0
  58. package/dist/noble/curves/utils.js +385 -0
  59. package/dist/noble/curves/weierstrass.d.ts +240 -0
  60. package/dist/noble/curves/weierstrass.js +1178 -0
  61. package/dist/noble/ed25519.d.ts +100 -0
  62. package/dist/noble/ed25519.js +494 -0
  63. package/dist/noble/hmac.d.ts +25 -0
  64. package/dist/noble/hmac.js +101 -0
  65. package/dist/noble/index.d.ts +2 -0
  66. package/dist/noble/index.js +20 -0
  67. package/dist/noble/keccak.d.ts +58 -0
  68. package/dist/noble/keccak.js +289 -0
  69. package/dist/noble/ripemd_160.d.ts +20 -0
  70. package/dist/noble/ripemd_160.js +147 -0
  71. package/dist/noble/secp256k1.d.ts +98 -0
  72. package/dist/noble/secp256k1.js +309 -0
  73. package/dist/noble/sha256.d.ts +34 -0
  74. package/dist/noble/sha256.js +146 -0
  75. package/dist/noble/sha512.d.ts +66 -0
  76. package/dist/noble/sha512.js +301 -0
  77. package/dist/noble/utils.d.ts +90 -0
  78. package/dist/noble/utils.js +278 -0
  79. package/dist/ripemd_160.d.ts +1 -0
  80. package/dist/ripemd_160.js +23 -0
  81. package/dist/rust_vrf_reimpl/curves.d.ts +162 -0
  82. package/dist/rust_vrf_reimpl/curves.js +4225 -0
  83. package/dist/rust_vrf_reimpl/vrf03.d.ts +60 -0
  84. package/dist/rust_vrf_reimpl/vrf03.js +373 -0
  85. package/dist/rust_vrf_reimpl/vrf10.d.ts +73 -0
  86. package/dist/rust_vrf_reimpl/vrf10.js +468 -0
  87. package/dist/rust_vrf_reimpl/vrf10_batch.d.ts +53 -0
  88. package/dist/rust_vrf_reimpl/vrf10_batch.js +245 -0
  89. package/dist/secp256k1.d.ts +4 -0
  90. package/dist/secp256k1.js +33 -0
  91. package/dist/sha2_256.d.ts +16 -0
  92. package/dist/sha2_256.js +403 -0
  93. package/dist/sha2_512.d.ts +16 -0
  94. package/dist/sha2_512.js +256 -0
  95. package/dist/sha3.d.ts +17 -0
  96. package/dist/sha3.js +181 -0
  97. package/dist/types.d.ts +26 -0
  98. package/dist/types.js +120 -0
  99. package/dist/utils/assert.d.ts +3 -0
  100. package/dist/utils/assert.js +55 -0
  101. package/dist/utils/base32.d.ts +5 -0
  102. package/dist/utils/base32.js +52 -0
  103. package/dist/utils/bigintToBuffer.d.ts +1 -0
  104. package/dist/utils/bigintToBuffer.js +27 -0
  105. package/dist/utils/bytesToHex.d.ts +2 -0
  106. package/dist/utils/bytesToHex.js +15 -0
  107. package/dist/utils/getRandomValues.d.ts +4 -0
  108. package/dist/utils/getRandomValues.js +12 -0
  109. package/dist/utils/hexToBytes.d.ts +2 -0
  110. package/dist/utils/hexToBytes.js +14 -0
  111. package/dist/utils/index.d.ts +3 -0
  112. package/dist/utils/index.js +19 -0
  113. package/dist/utils/positiveMod.d.ts +1 -0
  114. package/dist/utils/positiveMod.js +11 -0
  115. package/dist/utils/promisifySync.d.ts +0 -0
  116. package/dist/utils/promisifySync.js +0 -0
  117. package/dist/utils/rotr32.d.ts +2 -0
  118. package/dist/utils/rotr32.js +7 -0
  119. package/dist/vrf.d.ts +74 -0
  120. package/dist/vrf.js +286 -0
  121. package/package.json +49 -4
@@ -0,0 +1,385 @@
1
+ "use strict";
2
+ var __read = (this && this.__read) || function (o, n) {
3
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
4
+ if (!m) return o;
5
+ var i = m.call(o), r, ar = [], e;
6
+ try {
7
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
8
+ }
9
+ catch (error) { e = { error: error }; }
10
+ finally {
11
+ try {
12
+ if (r && !r.done && (m = i["return"])) m.call(i);
13
+ }
14
+ finally { if (e) throw e.error; }
15
+ }
16
+ return ar;
17
+ };
18
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
19
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
20
+ if (ar || !(i in from)) {
21
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
22
+ ar[i] = from[i];
23
+ }
24
+ }
25
+ return to.concat(ar || Array.prototype.slice.call(from));
26
+ };
27
+ var __values = (this && this.__values) || function(o) {
28
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
29
+ if (m) return m.call(o);
30
+ if (o && typeof o.length === "number") return {
31
+ next: function () {
32
+ if (o && i >= o.length) o = void 0;
33
+ return { value: o && o[i++], done: !o };
34
+ }
35
+ };
36
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.validateObject = exports.createHmacDrbg = exports.bitMask = exports.bitSet = exports.bitGet = exports.bitLen = exports.utf8ToBytes = exports.equalBytes = exports.concatBytes = exports.ensureBytes = exports.numberToVarBytesBE = exports.numberToBytesLE = exports.numberToBytesBE = exports.bytesToNumberLE = exports.bytesToNumberBE = exports.hexToBytes = exports.hexToNumber = exports.numberToHexUnpadded = exports.bytesToHex = exports.abytes = exports.isBytes = void 0;
40
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
41
+ // 100 lines of code in the file are duplicated from noble-hashes (utils).
42
+ // This is OK: `abstract` directory does not use noble-hashes.
43
+ // User may opt-in into using different hashing library. This way, noble-hashes
44
+ // won't be included into their bundle.
45
+ var _0n = BigInt(0);
46
+ var _1n = BigInt(1);
47
+ var _2n = BigInt(2);
48
+ function isBytes(a) {
49
+ return (a instanceof Uint8Array ||
50
+ (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));
51
+ }
52
+ exports.isBytes = isBytes;
53
+ function abytes(item) {
54
+ if (!isBytes(item))
55
+ throw new Error('Uint8Array expected');
56
+ }
57
+ exports.abytes = abytes;
58
+ // Array where index 0xf0 (240) is mapped to string 'f0'
59
+ var hexes = /* @__PURE__ */ Array.from({ length: 256 }, function (_, i) {
60
+ return i.toString(16).padStart(2, '0');
61
+ });
62
+ /**
63
+ * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
64
+ */
65
+ function bytesToHex(bytes) {
66
+ abytes(bytes);
67
+ // pre-caching improves the speed 6x
68
+ var hex = '';
69
+ for (var i = 0; i < bytes.length; i++) {
70
+ hex += hexes[bytes[i]];
71
+ }
72
+ return hex;
73
+ }
74
+ exports.bytesToHex = bytesToHex;
75
+ function numberToHexUnpadded(num) {
76
+ var hex = num.toString(16);
77
+ return hex.length & 1 ? "0".concat(hex) : hex;
78
+ }
79
+ exports.numberToHexUnpadded = numberToHexUnpadded;
80
+ function hexToNumber(hex) {
81
+ if (typeof hex !== 'string')
82
+ throw new Error('hex string expected, got ' + typeof hex);
83
+ // Big Endian
84
+ return BigInt(hex === '' ? '0' : "0x".concat(hex));
85
+ }
86
+ exports.hexToNumber = hexToNumber;
87
+ // We use optimized technique to convert hex string to byte array
88
+ var asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };
89
+ function asciiToBase16(char) {
90
+ if (char >= asciis._0 && char <= asciis._9)
91
+ return char - asciis._0;
92
+ if (char >= asciis._A && char <= asciis._F)
93
+ return char - (asciis._A - 10);
94
+ if (char >= asciis._a && char <= asciis._f)
95
+ return char - (asciis._a - 10);
96
+ return;
97
+ }
98
+ /**
99
+ * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
100
+ */
101
+ function hexToBytes(hex) {
102
+ if (typeof hex !== 'string')
103
+ throw new Error('hex string expected, got ' + typeof hex);
104
+ var hl = hex.length;
105
+ var al = hl / 2;
106
+ if (hl % 2)
107
+ throw new Error('padded hex string expected, got unpadded hex of length ' + hl);
108
+ var array = new Uint8Array(al);
109
+ for (var ai = 0, hi = 0; ai < al; ai++, hi += 2) {
110
+ var n1 = asciiToBase16(hex.charCodeAt(hi));
111
+ var n2 = asciiToBase16(hex.charCodeAt(hi + 1));
112
+ if (n1 === undefined || n2 === undefined) {
113
+ var char = hex[hi] + hex[hi + 1];
114
+ throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
115
+ }
116
+ array[ai] = n1 * 16 + n2;
117
+ }
118
+ return array;
119
+ }
120
+ exports.hexToBytes = hexToBytes;
121
+ // BE: Big Endian, LE: Little Endian
122
+ function bytesToNumberBE(bytes) {
123
+ return hexToNumber(bytesToHex(bytes));
124
+ }
125
+ exports.bytesToNumberBE = bytesToNumberBE;
126
+ function bytesToNumberLE(bytes) {
127
+ abytes(bytes);
128
+ return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
129
+ }
130
+ exports.bytesToNumberLE = bytesToNumberLE;
131
+ function numberToBytesBE(n, len) {
132
+ return hexToBytes(n.toString(16).padStart(len * 2, '0'));
133
+ }
134
+ exports.numberToBytesBE = numberToBytesBE;
135
+ function numberToBytesLE(n, len) {
136
+ return numberToBytesBE(n, len).reverse();
137
+ }
138
+ exports.numberToBytesLE = numberToBytesLE;
139
+ // Unpadded, rarely used
140
+ function numberToVarBytesBE(n) {
141
+ return hexToBytes(numberToHexUnpadded(n));
142
+ }
143
+ exports.numberToVarBytesBE = numberToVarBytesBE;
144
+ /**
145
+ * Takes hex string or Uint8Array, converts to Uint8Array.
146
+ * Validates output length.
147
+ * Will throw error for other types.
148
+ * @param title descriptive title for an error e.g. 'private key'
149
+ * @param hex hex string or Uint8Array
150
+ * @param expectedLength optional, will compare to result array's length
151
+ * @returns
152
+ */
153
+ function ensureBytes(title, hex, expectedLength) {
154
+ var res;
155
+ if (typeof hex === 'string') {
156
+ try {
157
+ res = hexToBytes(hex);
158
+ }
159
+ catch (e) {
160
+ throw new Error("".concat(title, " must be valid hex string, got \"").concat(hex, "\". Cause: ").concat(e));
161
+ }
162
+ }
163
+ else if (isBytes(hex)) {
164
+ // Uint8Array.from() instead of hash.slice() because node Buffer
165
+ // is instance of Uint8Array, and its slice() creates **mutable** copy
166
+ res = Uint8Array.from(hex);
167
+ }
168
+ else {
169
+ throw new Error("".concat(title, " must be hex string or Uint8Array"));
170
+ }
171
+ var len = res.length;
172
+ if (typeof expectedLength === 'number' && len !== expectedLength)
173
+ throw new Error("".concat(title, " expected ").concat(expectedLength, " bytes, got ").concat(len));
174
+ return res;
175
+ }
176
+ exports.ensureBytes = ensureBytes;
177
+ /**
178
+ * Copies several Uint8Arrays into one.
179
+ */
180
+ function concatBytes() {
181
+ var arrays = [];
182
+ for (var _i = 0; _i < arguments.length; _i++) {
183
+ arrays[_i] = arguments[_i];
184
+ }
185
+ var sum = 0;
186
+ for (var i = 0; i < arrays.length; i++) {
187
+ var a = arrays[i];
188
+ abytes(a);
189
+ sum += a.length;
190
+ }
191
+ var res = new Uint8Array(sum);
192
+ for (var i = 0, pad = 0; i < arrays.length; i++) {
193
+ var a = arrays[i];
194
+ res.set(a, pad);
195
+ pad += a.length;
196
+ }
197
+ return res;
198
+ }
199
+ exports.concatBytes = concatBytes;
200
+ // Compares 2 u8a-s in kinda constant time
201
+ function equalBytes(a, b) {
202
+ if (a.length !== b.length)
203
+ return false;
204
+ var diff = 0;
205
+ for (var i = 0; i < a.length; i++)
206
+ diff |= a[i] ^ b[i];
207
+ return diff === 0;
208
+ }
209
+ exports.equalBytes = equalBytes;
210
+ /**
211
+ * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
212
+ */
213
+ function utf8ToBytes(str) {
214
+ if (typeof str !== 'string')
215
+ throw new Error("utf8ToBytes expected string, got ".concat(typeof str));
216
+ return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
217
+ }
218
+ exports.utf8ToBytes = utf8ToBytes;
219
+ // Bit operations
220
+ /**
221
+ * Calculates amount of bits in a bigint.
222
+ * Same as `n.toString(2).length`
223
+ */
224
+ function bitLen(n) {
225
+ var len;
226
+ for (len = 0; n > _0n; n >>= _1n, len += 1)
227
+ ;
228
+ return len;
229
+ }
230
+ exports.bitLen = bitLen;
231
+ /**
232
+ * Gets single bit at position.
233
+ * NOTE: first bit position is 0 (same as arrays)
234
+ * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`
235
+ */
236
+ function bitGet(n, pos) {
237
+ return (n >> BigInt(pos)) & _1n;
238
+ }
239
+ exports.bitGet = bitGet;
240
+ /**
241
+ * Sets single bit at position.
242
+ */
243
+ function bitSet(n, pos, value) {
244
+ return n | ((value ? _1n : _0n) << BigInt(pos));
245
+ }
246
+ exports.bitSet = bitSet;
247
+ /**
248
+ * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
249
+ * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
250
+ */
251
+ var bitMask = function (n) { return (_2n << BigInt(n - 1)) - _1n; };
252
+ exports.bitMask = bitMask;
253
+ // DRBG
254
+ var u8n = function (data) { return new Uint8Array(data); }; // creates Uint8Array
255
+ var u8fr = function (arr) { return Uint8Array.from(arr); }; // another shortcut
256
+ /**
257
+ * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
258
+ * @returns function that will call DRBG until 2nd arg returns something meaningful
259
+ * @example
260
+ * const drbg = createHmacDRBG<Key>(32, 32, hmac);
261
+ * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
262
+ */
263
+ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
264
+ if (typeof hashLen !== 'number' || hashLen < 2)
265
+ throw new Error('hashLen must be a number');
266
+ if (typeof qByteLen !== 'number' || qByteLen < 2)
267
+ throw new Error('qByteLen must be a number');
268
+ if (typeof hmacFn !== 'function')
269
+ throw new Error('hmacFn must be a function');
270
+ // Step B, Step C: set hashLen to 8*ceil(hlen/8)
271
+ var v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
272
+ var k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same
273
+ var i = 0; // Iterations counter, will throw when over 1000
274
+ var reset = function () {
275
+ v.fill(1);
276
+ k.fill(0);
277
+ i = 0;
278
+ };
279
+ var h = function () {
280
+ var b = [];
281
+ for (var _i = 0; _i < arguments.length; _i++) {
282
+ b[_i] = arguments[_i];
283
+ }
284
+ return hmacFn.apply(void 0, __spreadArray([k, v], __read(b), false));
285
+ }; // hmac(k)(v, ...values)
286
+ var reseed = function (seed) {
287
+ if (seed === void 0) { seed = u8n(); }
288
+ // HMAC-DRBG reseed() function. Steps D-G
289
+ k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)
290
+ v = h(); // v = hmac(k || v)
291
+ if (seed.length === 0)
292
+ return;
293
+ k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)
294
+ v = h(); // v = hmac(k || v)
295
+ };
296
+ var gen = function () {
297
+ // HMAC-DRBG generate() function
298
+ if (i++ >= 1000)
299
+ throw new Error('drbg: tried 1000 values');
300
+ var len = 0;
301
+ var out = [];
302
+ while (len < qByteLen) {
303
+ v = h();
304
+ var sl = v.slice();
305
+ out.push(sl);
306
+ len += v.length;
307
+ }
308
+ return concatBytes.apply(void 0, __spreadArray([], __read(out), false));
309
+ };
310
+ var genUntil = function (seed, pred) {
311
+ reset();
312
+ reseed(seed); // Steps D-G
313
+ var res = undefined; // Step H: grind until k is in [1..n-1]
314
+ while (!(res = pred(gen())))
315
+ reseed();
316
+ reset();
317
+ return res;
318
+ };
319
+ return genUntil;
320
+ }
321
+ exports.createHmacDrbg = createHmacDrbg;
322
+ // Validating curves and fields
323
+ var validatorFns = {
324
+ bigint: function (val) { return typeof val === 'bigint'; },
325
+ function: function (val) { return typeof val === 'function'; },
326
+ boolean: function (val) { return typeof val === 'boolean'; },
327
+ string: function (val) { return typeof val === 'string'; },
328
+ stringOrUint8Array: function (val) { return typeof val === 'string' || isBytes(val); },
329
+ isSafeInteger: function (val) { return Number.isSafeInteger(val); },
330
+ array: function (val) { return Array.isArray(val); },
331
+ field: function (val, object) { return object.Fp.isValid(val); },
332
+ hash: function (val) { return typeof val === 'function' && Number.isSafeInteger(val.outputLen); },
333
+ };
334
+ // type Record<K extends string | number | symbol, T> = { [P in K]: T; }
335
+ function validateObject(object, validators, optValidators) {
336
+ var e_1, _b, e_2, _c;
337
+ if (optValidators === void 0) { optValidators = {}; }
338
+ var checkField = function (fieldName, type, isOptional) {
339
+ var checkVal = validatorFns[type];
340
+ if (typeof checkVal !== 'function')
341
+ throw new Error("Invalid validator \"".concat(type, "\", expected function"));
342
+ var val = object[fieldName];
343
+ if (isOptional && val === undefined)
344
+ return;
345
+ if (!checkVal(val, object)) {
346
+ throw new Error("Invalid param ".concat(String(fieldName), "=").concat(val, " (").concat(typeof val, "), expected ").concat(type));
347
+ }
348
+ };
349
+ try {
350
+ for (var _d = __values(Object.entries(validators)), _e = _d.next(); !_e.done; _e = _d.next()) {
351
+ var _g = __read(_e.value, 2), fieldName = _g[0], type = _g[1];
352
+ checkField(fieldName, type, false);
353
+ }
354
+ }
355
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
356
+ finally {
357
+ try {
358
+ if (_e && !_e.done && (_b = _d.return)) _b.call(_d);
359
+ }
360
+ finally { if (e_1) throw e_1.error; }
361
+ }
362
+ try {
363
+ for (var _h = __values(Object.entries(optValidators)), _j = _h.next(); !_j.done; _j = _h.next()) {
364
+ var _k = __read(_j.value, 2), fieldName = _k[0], type = _k[1];
365
+ checkField(fieldName, type, true);
366
+ }
367
+ }
368
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
369
+ finally {
370
+ try {
371
+ if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
372
+ }
373
+ finally { if (e_2) throw e_2.error; }
374
+ }
375
+ return object;
376
+ }
377
+ exports.validateObject = validateObject;
378
+ // validate type tests
379
+ // const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };
380
+ // const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!
381
+ // // Should fail type-check
382
+ // const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });
383
+ // const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });
384
+ // const z3 = validateObject(o, { test: 'boolean', z: 'bug' });
385
+ // const z4 = validateObject(o, { a: 'boolean', z: 'bug' });
@@ -0,0 +1,240 @@
1
+ /// <reference types="node" />
2
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
3
+ import * as mod from '../abstract/modular.js';
4
+ import * as ut from '../abstract/utils.js';
5
+ import { CHash, Hex, PrivKey } from '../abstract/utils.js';
6
+ import { Group, GroupConstructor, BasicCurve, AffinePoint } from '../abstract/curve.js';
7
+ export type { AffinePoint };
8
+ type HmacFnSync = (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array;
9
+ type EndomorphismOpts = {
10
+ beta: bigint;
11
+ splitScalar: (k: bigint) => {
12
+ k1neg: boolean;
13
+ k1: bigint;
14
+ k2neg: boolean;
15
+ k2: bigint;
16
+ };
17
+ };
18
+ export type BasicWCurve<T> = BasicCurve<T> & {
19
+ a: T;
20
+ b: T;
21
+ allowedPrivateKeyLengths?: readonly number[];
22
+ wrapPrivateKey?: boolean;
23
+ endo?: EndomorphismOpts;
24
+ isTorsionFree?: (c: ProjConstructor<T>, point: ProjPointType<T>) => boolean;
25
+ clearCofactor?: (c: ProjConstructor<T>, point: ProjPointType<T>) => ProjPointType<T>;
26
+ };
27
+ type Entropy = Hex | boolean;
28
+ export type SignOpts = {
29
+ lowS?: boolean;
30
+ extraEntropy?: Entropy;
31
+ prehash?: boolean;
32
+ };
33
+ export type VerOpts = {
34
+ lowS?: boolean;
35
+ prehash?: boolean;
36
+ };
37
+ /**
38
+ * ### Design rationale for types
39
+ *
40
+ * * Interaction between classes from different curves should fail:
41
+ * `k256.Point.BASE.add(p256.Point.BASE)`
42
+ * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime
43
+ * * Different calls of `curve()` would return different classes -
44
+ * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,
45
+ * it won't affect others
46
+ *
47
+ * TypeScript can't infer types for classes created inside a function. Classes is one instance of nominative types in TypeScript and interfaces only check for shape, so it's hard to create unique type for every function call.
48
+ *
49
+ * We can use generic types via some param, like curve opts, but that would:
50
+ * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)
51
+ * which is hard to debug.
52
+ * 2. Params can be generic and we can't enforce them to be constant value:
53
+ * if somebody creates curve from non-constant params,
54
+ * it would be allowed to interact with other curves with non-constant params
55
+ *
56
+ * TODO: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol
57
+ */
58
+ export interface ProjPointType<T> extends Group<ProjPointType<T>> {
59
+ readonly px: T;
60
+ readonly py: T;
61
+ readonly pz: T;
62
+ get x(): T;
63
+ get y(): T;
64
+ multiply(scalar: bigint): ProjPointType<T>;
65
+ toAffine(iz?: T): AffinePoint<T>;
66
+ isTorsionFree(): boolean;
67
+ clearCofactor(): ProjPointType<T>;
68
+ assertValidity(): void;
69
+ hasEvenY(): boolean;
70
+ toRawBytes(isCompressed?: boolean): Uint8Array;
71
+ toHex(isCompressed?: boolean): string;
72
+ multiplyUnsafe(scalar: bigint): ProjPointType<T>;
73
+ multiplyAndAddUnsafe(Q: ProjPointType<T>, a: bigint, b: bigint): ProjPointType<T> | undefined;
74
+ _setWindowSize(windowSize: number): void;
75
+ }
76
+ export interface ProjConstructor<T> extends GroupConstructor<ProjPointType<T>> {
77
+ new (x: T, y: T, z: T): ProjPointType<T>;
78
+ fromAffine(p: AffinePoint<T>): ProjPointType<T>;
79
+ fromHex(hex: Hex): ProjPointType<T>;
80
+ fromPrivateKey(privateKey: PrivKey): ProjPointType<T>;
81
+ normalizeZ(points: ProjPointType<T>[]): ProjPointType<T>[];
82
+ }
83
+ export type CurvePointsType<T> = BasicWCurve<T> & {
84
+ fromBytes?: (bytes: Uint8Array) => AffinePoint<T>;
85
+ toBytes?: (c: ProjConstructor<T>, point: ProjPointType<T>, isCompressed: boolean) => Uint8Array;
86
+ };
87
+ declare function validatePointOpts<T>(curve: CurvePointsType<T>): Readonly<{
88
+ readonly nBitLength: number;
89
+ readonly nByteLength: number;
90
+ readonly Fp: mod.IField<T>;
91
+ readonly n: bigint;
92
+ readonly h: bigint;
93
+ readonly hEff?: bigint | undefined;
94
+ readonly Gx: T;
95
+ readonly Gy: T;
96
+ readonly allowInfinityPoint?: boolean | undefined;
97
+ readonly a: T;
98
+ readonly b: T;
99
+ readonly allowedPrivateKeyLengths?: readonly number[] | undefined;
100
+ readonly wrapPrivateKey?: boolean | undefined;
101
+ readonly endo?: EndomorphismOpts | undefined;
102
+ readonly isTorsionFree?: ((c: ProjConstructor<T>, point: ProjPointType<T>) => boolean) | undefined;
103
+ readonly clearCofactor?: ((c: ProjConstructor<T>, point: ProjPointType<T>) => ProjPointType<T>) | undefined;
104
+ readonly fromBytes?: ((bytes: Uint8Array) => AffinePoint<T>) | undefined;
105
+ readonly toBytes?: ((c: ProjConstructor<T>, point: ProjPointType<T>, isCompressed: boolean) => Uint8Array) | undefined;
106
+ readonly p: bigint;
107
+ }>;
108
+ export type CurvePointsRes<T> = {
109
+ CURVE: ReturnType<typeof validatePointOpts<T>>;
110
+ ProjectivePoint: ProjConstructor<T>;
111
+ normPrivateKeyToScalar: (key: PrivKey) => bigint;
112
+ weierstrassEquation: (x: T) => T;
113
+ isWithinCurveOrder: (num: bigint) => boolean;
114
+ };
115
+ export declare const DER: {
116
+ Err: {
117
+ new (m?: string): {
118
+ name: string;
119
+ message: string;
120
+ stack?: string | undefined;
121
+ };
122
+ captureStackTrace(targetObject: object, constructorOpt?: Function | undefined): void;
123
+ prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined;
124
+ stackTraceLimit: number;
125
+ };
126
+ _parseInt(data: Uint8Array): {
127
+ d: bigint;
128
+ l: Uint8Array;
129
+ };
130
+ toSig(hex: string | Uint8Array): {
131
+ r: bigint;
132
+ s: bigint;
133
+ };
134
+ hexFromSig(sig: {
135
+ r: bigint;
136
+ s: bigint;
137
+ }): string;
138
+ };
139
+ export declare function weierstrassPoints<T>(opts: CurvePointsType<T>): CurvePointsRes<T>;
140
+ export interface SignatureType {
141
+ readonly r: bigint;
142
+ readonly s: bigint;
143
+ readonly recovery?: number;
144
+ assertValidity(): void;
145
+ addRecoveryBit(recovery: number): RecoveredSignatureType;
146
+ hasHighS(): boolean;
147
+ normalizeS(): SignatureType;
148
+ recoverPublicKey(msgHash: Hex): ProjPointType<bigint>;
149
+ toCompactRawBytes(): Uint8Array;
150
+ toCompactHex(): string;
151
+ toDERRawBytes(isCompressed?: boolean): Uint8Array;
152
+ toDERHex(isCompressed?: boolean): string;
153
+ }
154
+ export type RecoveredSignatureType = SignatureType & {
155
+ readonly recovery: number;
156
+ };
157
+ export type SignatureConstructor = {
158
+ new (r: bigint, s: bigint): SignatureType;
159
+ fromCompact(hex: Hex): SignatureType;
160
+ fromDER(hex: Hex): SignatureType;
161
+ };
162
+ type SignatureLike = {
163
+ r: bigint;
164
+ s: bigint;
165
+ };
166
+ export type PubKey = Hex | ProjPointType<bigint>;
167
+ export type CurveType = BasicWCurve<bigint> & {
168
+ hash: CHash;
169
+ hmac: HmacFnSync;
170
+ randomBytes: (bytesLength?: number) => Uint8Array;
171
+ lowS?: boolean;
172
+ bits2int?: (bytes: Uint8Array) => bigint;
173
+ bits2int_modN?: (bytes: Uint8Array) => bigint;
174
+ };
175
+ declare function validateOpts(curve: CurveType): Readonly<{
176
+ readonly nBitLength: number;
177
+ readonly nByteLength: number;
178
+ readonly Fp: mod.IField<bigint>;
179
+ readonly n: bigint;
180
+ readonly h: bigint;
181
+ readonly hEff?: bigint | undefined;
182
+ readonly Gx: bigint;
183
+ readonly Gy: bigint;
184
+ readonly allowInfinityPoint?: boolean | undefined;
185
+ readonly a: bigint;
186
+ readonly b: bigint;
187
+ readonly allowedPrivateKeyLengths?: readonly number[] | undefined;
188
+ readonly wrapPrivateKey?: boolean | undefined;
189
+ readonly endo?: EndomorphismOpts | undefined;
190
+ readonly isTorsionFree?: ((c: ProjConstructor<bigint>, point: ProjPointType<bigint>) => boolean) | undefined;
191
+ readonly clearCofactor?: ((c: ProjConstructor<bigint>, point: ProjPointType<bigint>) => ProjPointType<bigint>) | undefined;
192
+ readonly hash: ut.CHash;
193
+ readonly hmac: HmacFnSync;
194
+ readonly randomBytes: (bytesLength?: number | undefined) => Uint8Array;
195
+ lowS: boolean;
196
+ readonly bits2int?: ((bytes: Uint8Array) => bigint) | undefined;
197
+ readonly bits2int_modN?: ((bytes: Uint8Array) => bigint) | undefined;
198
+ readonly p: bigint;
199
+ }>;
200
+ export type CurveFn = {
201
+ CURVE: ReturnType<typeof validateOpts>;
202
+ getPublicKey: (privateKey: PrivKey, isCompressed?: boolean) => Uint8Array;
203
+ getSharedSecret: (privateA: PrivKey, publicB: Hex, isCompressed?: boolean) => Uint8Array;
204
+ sign: (msgHash: Hex, privKey: PrivKey, opts?: SignOpts) => RecoveredSignatureType;
205
+ verify: (signature: Hex | SignatureLike, msgHash: Hex, publicKey: Hex, opts?: VerOpts) => boolean;
206
+ ProjectivePoint: ProjConstructor<bigint>;
207
+ Signature: SignatureConstructor;
208
+ utils: {
209
+ normPrivateKeyToScalar: (key: PrivKey) => bigint;
210
+ isValidPrivateKey(privateKey: PrivKey): boolean;
211
+ randomPrivateKey: () => Uint8Array;
212
+ precompute: (windowSize?: number, point?: ProjPointType<bigint>) => ProjPointType<bigint>;
213
+ };
214
+ };
215
+ export declare function weierstrass(curveDef: CurveType): CurveFn;
216
+ /**
217
+ * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.
218
+ * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.
219
+ * b = True and y = sqrt(u / v) if (u / v) is square in F, and
220
+ * b = False and y = sqrt(Z * (u / v)) otherwise.
221
+ * @param Fp
222
+ * @param Z
223
+ * @returns
224
+ */
225
+ export declare function SWUFpSqrtRatio<T>(Fp: mod.IField<T>, Z: T): (u: T, v: T) => {
226
+ isValid: boolean;
227
+ value: T;
228
+ };
229
+ /**
230
+ * Simplified Shallue-van de Woestijne-Ulas Method
231
+ * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2
232
+ */
233
+ export declare function mapToCurveSimpleSWU<T>(Fp: mod.IField<T>, opts: {
234
+ A: T;
235
+ B: T;
236
+ Z: T;
237
+ }): (u: T) => {
238
+ x: T;
239
+ y: T;
240
+ };