-
Notifications
You must be signed in to change notification settings - Fork 307
/
utils.ts
628 lines (575 loc) · 18.7 KB
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
import { Logger } from './logger';
/**
* @ignore
*/
export const BLOCKSTACK_HANDLER = 'blockstack';
/**
* Time
* @private
* @ignore
*/
export function nextYear() {
return new Date(new Date().setFullYear(new Date().getFullYear() + 1));
}
/**
* Time
* @private
* @ignore
*/
export function nextMonth() {
return new Date(new Date().setMonth(new Date().getMonth() + 1));
}
/**
* Time
* @private
* @ignore
*/
export function nextHour() {
return new Date(new Date().setHours(new Date().getHours() + 1));
}
/**
* Converts megabytes to bytes. Returns 0 if the input is not a finite number.
* @ignore
*/
export function megabytesToBytes(megabytes: number): number {
if (!Number.isFinite(megabytes)) {
return 0;
}
return Math.floor(megabytes * 1024 * 1024);
}
/**
* Calculate the AES-CBC ciphertext output byte length a given input length.
* AES has a fixed block size of 16-bytes regardless key size.
* @ignore
*/
export function getAesCbcOutputLength(inputByteLength: number) {
// AES-CBC block mode rounds up to the next block size.
const cipherTextLength = (Math.floor(inputByteLength / 16) + 1) * 16;
return cipherTextLength;
}
/**
* Calculate the base64 encoded string length for a given input length.
* This is equivalent to the byte length when the string is ASCII or UTF8-8
* encoded.
* @param number
*/
export function getBase64OutputLength(inputByteLength: number) {
const encodedLength = Math.ceil(inputByteLength / 3) * 4;
return encodedLength;
}
/**
* Query Strings
* @private
* @ignore
*/
export function updateQueryStringParameter(uri: string, key: string, value: string) {
const re = new RegExp(`([?&])${key}=.*?(&|$)`, 'i');
const separator = uri.indexOf('?') !== -1 ? '&' : '?';
if (uri.match(re)) {
return uri.replace(re, `$1${key}=${value}$2`);
} else {
return `${uri}${separator}${key}=${value}`;
}
}
/**
* Versioning
* @param {string} v1 - the left half of the version inequality
* @param {string} v2 - right half of the version inequality
* @returns {bool} iff v1 >= v2
* @private
* @ignore
*/
export function isLaterVersion(v1: string, v2: string) {
if (v1 === undefined || v1 === '') {
v1 = '0.0.0';
}
if (v2 === undefined || v1 === '') {
v2 = '0.0.0';
}
const v1tuple = v1.split('.').map(x => parseInt(x, 10));
const v2tuple = v2.split('.').map(x => parseInt(x, 10));
for (let index = 0; index < v2.length; index++) {
if (index >= v1.length) {
v2tuple.push(0);
}
if (v1tuple[index] < v2tuple[index]) {
return false;
}
}
return true;
}
/**
* UUIDs
* @private
* @ignore
*/
export function makeUUID4() {
let d = new Date().getTime();
if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
d += performance.now(); // use high-precision timer if available
}
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
const r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);
});
}
/**
* Checks if both urls pass the same origin check & are absolute
* @param {[type]} uri1 first uri to check
* @param {[type]} uri2 second uri to check
* @return {Boolean} true if they pass the same origin check
* @private
* @ignore
*/
export function isSameOriginAbsoluteUrl(uri1: string, uri2: string) {
try {
const parsedUri1 = new URL(uri1);
const parsedUri2 = new URL(uri2);
const port1 =
parseInt(parsedUri1.port || '0', 10) | 0 || (parsedUri1.protocol === 'https:' ? 443 : 80);
const port2 =
parseInt(parsedUri2.port || '0', 10) | 0 || (parsedUri2.protocol === 'https:' ? 443 : 80);
const match = {
scheme: parsedUri1.protocol === parsedUri2.protocol,
hostname: parsedUri1.hostname === parsedUri2.hostname,
port: port1 === port2,
absolute:
(uri1.includes('http://') || uri1.includes('https://')) &&
(uri2.includes('http://') || uri2.includes('https://')),
};
return match.scheme && match.hostname && match.port && match.absolute;
} catch (error) {
console.log(error);
console.log('Parsing error in same URL origin check');
// Parse error
return false;
}
}
/**
* Returns the global scope `Window`, `WorkerGlobalScope`, or `NodeJS.Global` if available in the
* currently executing environment.
* @see https://developer.mozilla.org/en-US/docs/Web/API/Window/self
* @see https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/self
* @see https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope
*
* This could be switched to `globalThis` once it is standardized and widely available.
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis
* @ignore
*/
export function getGlobalScope(): Window {
if (typeof self !== 'undefined') {
return self;
}
if (typeof window !== 'undefined') {
return window;
}
// This function is meant to be called when accessing APIs that are typically only available in
// web-browser/DOM environments, but we also want to support situations where running in Node.js
// environment, and a polyfill was added to the Node.js `global` object scope without adding the
// `window` global object as well.
if (typeof global !== 'undefined') {
return global as unknown as Window;
}
throw new Error(
'Unexpected runtime environment - no supported global scope (`window`, `self`, `global`) available'
);
}
function getAPIUsageErrorMessage(
scopeObject: unknown,
apiName: string,
usageDesc?: string
): string {
if (usageDesc) {
return `Use of '${usageDesc}' requires \`${apiName}\` which is unavailable on the '${scopeObject}' object within the currently executing environment.`;
} else {
return `\`${apiName}\` is unavailable on the '${scopeObject}' object within the currently executing environment.`;
}
}
interface GetGlobalObjectOptions {
/**
* Throw an error if the object is not found.
* @default false
*/
throwIfUnavailable?: boolean;
/**
* Additional information to include in an error if thrown.
*/
usageDesc?: string;
/**
* If the object is not found, return an new empty object instead of undefined.
* Requires [[throwIfUnavailable]] to be falsey.
* @default false
*/
returnEmptyObject?: boolean;
}
/**
* Returns an object from the global scope (`Window` or `WorkerGlobalScope`) if it
* is available within the currently executing environment.
* When executing within the Node.js runtime these APIs are unavailable and will be
* `undefined` unless the API is provided via polyfill.
* @see https://developer.mozilla.org/en-US/docs/Web/API/Window/self
* @ignore
*/
export function getGlobalObject<K extends Extract<keyof Window, string>>(
name: K,
{ throwIfUnavailable, usageDesc, returnEmptyObject }: GetGlobalObjectOptions = {}
): Window[K] | undefined {
let globalScope: Window | undefined = undefined;
try {
globalScope = getGlobalScope();
if (globalScope) {
const obj = globalScope[name];
if (obj) {
return obj;
}
}
} catch (error) {
Logger.error(`Error getting object '${name}' from global scope '${globalScope}': ${error}`);
}
if (throwIfUnavailable) {
const errMsg = getAPIUsageErrorMessage(globalScope, name.toString(), usageDesc);
Logger.error(errMsg);
throw new Error(errMsg);
}
if (returnEmptyObject) {
return {} as any;
}
return undefined;
}
/**
* Returns a specified subset of objects from the global scope (`Window` or `WorkerGlobalScope`)
* if they are available within the currently executing environment.
* When executing within the Node.js runtime these APIs are unavailable will be `undefined`
* unless the API is provided via polyfill.
* @see https://developer.mozilla.org/en-US/docs/Web/API/Window/self
* @ignore
*/
export function getGlobalObjects<K extends Extract<keyof Window, string>>(
names: K[],
{ throwIfUnavailable, usageDesc, returnEmptyObject }: GetGlobalObjectOptions = {}
): Pick<Window, K> {
let globalScope: Window | undefined;
try {
globalScope = getGlobalScope();
} catch (error) {
Logger.error(`Error getting global scope: ${error}`);
if (throwIfUnavailable) {
const errMsg = getAPIUsageErrorMessage(globalScope, names[0].toString(), usageDesc);
Logger.error(errMsg);
throw errMsg;
} else if (returnEmptyObject) {
globalScope = {} as any;
}
}
const result: Pick<Window, K> = {} as any;
for (let i = 0; i < names.length; i++) {
const name = names[i];
try {
if (globalScope) {
const obj = globalScope[name];
if (obj) {
result[name] = obj;
} else if (throwIfUnavailable) {
const errMsg = getAPIUsageErrorMessage(globalScope, name.toString(), usageDesc);
Logger.error(errMsg);
throw new Error(errMsg);
} else if (returnEmptyObject) {
result[name] = {} as any;
}
}
} catch (error) {
if (throwIfUnavailable) {
const errMsg = getAPIUsageErrorMessage(globalScope, name.toString(), usageDesc);
Logger.error(errMsg);
throw new Error(errMsg);
}
}
}
return result;
}
// After removing bn.js library provide backward compatibility for users passing bn.js instance
type BN = import('bn.js'); // Type only import from @types/bn.js
export type IntegerType = number | string | bigint | Uint8Array | BN;
export function intToBytes(value: IntegerType, signed: boolean, byteLength: number): Uint8Array {
return bigIntToBytes(intToBigInt(value, signed), byteLength);
}
export function intToBigInt(value: IntegerType, signed: boolean): bigint {
let parsedValue = value;
if (typeof parsedValue === 'number') {
if (!Number.isInteger(parsedValue)) {
throw new RangeError(`Invalid value. Values of type 'number' must be an integer.`);
}
if (parsedValue > Number.MAX_SAFE_INTEGER) {
throw new RangeError(
`Invalid value. Values of type 'number' must be less than or equal to ${Number.MAX_SAFE_INTEGER}. For larger values, try using a BigInt instead.`
);
}
return BigInt(parsedValue);
}
if (typeof parsedValue === 'string') {
// If hex string then convert to bytes then fall through to the bytes condition
if (parsedValue.toLowerCase().startsWith('0x')) {
// Trim '0x' hex-prefix
let hex = parsedValue.slice(2);
// Allow odd-length strings like `0xf` -- some libs output these, or even just `0x${num.toString(16)}`
hex = hex.padStart(hex.length + (hex.length % 2), '0');
parsedValue = hexToBytes(hex);
} else {
try {
return BigInt(parsedValue);
} catch (error) {
if (error instanceof SyntaxError) {
throw new RangeError(`Invalid value. String integer '${parsedValue}' is not finite.`);
}
}
}
}
if (typeof parsedValue === 'bigint') {
return parsedValue;
}
if (parsedValue instanceof Uint8Array) {
if (signed) {
// Allow byte arrays smaller than 128-bits to be passed.
// This allows positive signed ints like `0x08` (8) or negative signed
// ints like `0xf8` (-8) to be passed without having to pad to 16 bytes.
const bn = fromTwos(
BigInt(`0x${bytesToHex(parsedValue)}`),
BigInt(parsedValue.byteLength * 8)
);
return BigInt(bn.toString());
} else {
return BigInt(`0x${bytesToHex(parsedValue)}`);
}
}
// After removing bn.js library provide backward compatibility for users passing bn.js instance
// For backward compatibility with bn.js check if it's a bn.js instance
if (
parsedValue != null &&
typeof parsedValue === 'object' &&
parsedValue.constructor.name === 'BN'
) {
return BigInt(parsedValue.toString());
}
throw new TypeError(
`Invalid value type. Must be a number, bigint, integer-string, hex-string, or Uint8Array.`
);
}
/**
* Adds a `0x` prefix to a string if it does not already have one.
*/
export function with0x(value: string): string {
return value.startsWith('0x') ? value : `0x${value}`;
}
/**
* Converts hex input string to bigint
* @param hex - hex input string without 0x prefix and in big endian format
* @example "6c7cde4d702830c1db34ef7c19e2776f59107afef39084776fc88bc78dbb9656"
* @ignore
*/
export function hexToBigInt(hex: string): bigint {
if (typeof hex !== 'string')
throw new TypeError(`hexToBigInt: expected string, got ${typeof hex}`);
// Big Endian
return BigInt(`0x${hex}`);
}
/**
* Converts IntegerType to hex string
* @ignore
*/
export function intToHex(integer: IntegerType, lengthBytes = 8): string {
const value = typeof integer === 'bigint' ? integer : intToBigInt(integer, false);
return value.toString(16).padStart(lengthBytes * 2, '0');
}
/**
* Converts hex string to integer
* @ignore
*/
export function hexToInt(hex: string): number {
return parseInt(hex, 16);
}
/**
* Converts bigint to byte array
* @param value bigint value to be converted
* @param length byte array optional length
* @return {Uint8Array} byte array
*/
export function bigIntToBytes(value: bigint, length: number = 16): Uint8Array {
const hex = intToHex(value, length);
return hexToBytes(hex);
}
/**
* Converts from signed number to two's complement
* MIN_VALUE = -(1 << (width - 1))
* MAX_VALUE = (1 << (width - 1)) - 1
* @ignore
*/
export function toTwos(value: bigint, width: bigint): bigint {
if (
value < -(BigInt(1) << (width - BigInt(1))) ||
(BigInt(1) << (width - BigInt(1))) - BigInt(1) < value
) {
throw `Unable to represent integer in width: ${width}`;
}
if (value >= BigInt(0)) {
return BigInt(value);
}
return value + (BigInt(1) << width);
}
/**
* Returns nth bit (right-to-left, zero-indexed)
*/
function nthBit(value: bigint, n: bigint) {
return value & (BigInt(1) << n);
}
/**
* Converts from two's complement to signed number
* @ignore
*/
export function fromTwos(value: bigint, width: bigint) {
if (nthBit(value, width - BigInt(1))) {
return value - (BigInt(1) << width);
}
return value;
}
// The following methods are based on `@noble/hashes` implementation
// https://github.com/paulmillr/noble-hashes
// Copyright (c) 2022 Paul Miller (https://paulmillr.com)
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the “Software”), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
const hexes = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
/**
* Converts bytes to the equivalent hex string
* @example
* ```
* bytesToHex(Uint8Array.from([0xde, 0xad, 0xbe, 0xef])) // 'deadbeef'
* ```
*/
export function bytesToHex(uint8a: Uint8Array): string {
// pre-caching improves the speed 6x
if (!(uint8a instanceof Uint8Array)) throw new Error('Uint8Array expected');
let hex = '';
for (const u of uint8a) {
hex += hexes[u];
}
return hex;
}
/**
* Converts a hex string to the equivalent bytes
* @example
* ```
* hexToBytes('deadbeef') // Uint8Array(4) [ 222, 173, 190, 239 ]
* hexToBytes('0xdeadbeef') // Uint8Array(4) [ 222, 173, 190, 239 ]
* ```
*/
export function hexToBytes(hex: string): Uint8Array {
if (typeof hex !== 'string') {
throw new TypeError(`hexToBytes: expected string, got ${typeof hex}`);
}
// todo: add use `without0x` from current `next` to replace duplicate trimming code
hex = hex.startsWith('0x') || hex.startsWith('0X') ? hex.slice(2) : hex; // remove 0x prefix
const paddedHex = hex.length % 2 ? `0${hex}` : hex; // left pad with a zero if odd length
const array = new Uint8Array(paddedHex.length / 2);
for (let i = 0; i < array.length; i++) {
const j = i * 2;
const hexByte = paddedHex.slice(j, j + 2);
const byte = Number.parseInt(hexByte, 16);
if (Number.isNaN(byte) || byte < 0) throw new Error('Invalid byte sequence');
array[i] = byte;
}
return array;
}
declare const TextEncoder: any;
declare const TextDecoder: any;
/**
* Converts a UTF-8 string to the equivalent bytes
* @example
* ```
* utf8ToBytes('stacks Ӿ'); // Uint8Array(9) [ 115, 116, 97, 99, 107, 115, 32, 211, 190 ];
* ```
*/
export function utf8ToBytes(str: string): Uint8Array {
return new TextEncoder().encode(str);
}
/**
* Converts bytes to the equivalent UTF-8 string
* @example
* ```
* bytesToUtf8(Uint8Array.from([115, 116, 97, 99, 107, 115, 32, 211, 190])); // 'stacks Ӿ'
* ```
*/
export function bytesToUtf8(arr: Uint8Array): string {
return new TextDecoder().decode(arr);
}
/**
* Converts an ASCII string to the equivalent bytes
* @example
* ```
* asciiToBytes('stacks $'); // Uint8Array(8) [ 115, 116, 97, 99, 107, 115, 32, 36 ]
* ```
*/
export function asciiToBytes(str: string) {
const byteArray = [];
for (let i = 0; i < str.length; i++) {
byteArray.push(str.charCodeAt(i) & 0xff); // ignore second bytes of UTF-16 character
}
return new Uint8Array(byteArray);
}
/**
* Converts bytes to the equivalent ASCII string
* @example
* ```
* bytesToAscii(Uint8Array.from([115, 116, 97, 99, 107, 115, 32, 36])); // 'stacks $'
* ```
*/
export function bytesToAscii(arr: Uint8Array) {
return String.fromCharCode.apply(null, arr as any as number[]);
}
function isNotOctet(octet: number) {
return !Number.isInteger(octet) || octet < 0 || octet > 255;
}
/** @ignore */
export function octetsToBytes(numbers: number[]) {
if (numbers.some(isNotOctet)) throw new Error('Some values are invalid bytes.');
return new Uint8Array(numbers);
}
/**
* Concats Uint8Array-s into one; like `Buffer.concat([buf1, buf2])`
* @example concatBytes(buf1, buf2)
* @ignore
*/
export function concatBytes(...arrays: Uint8Array[]): Uint8Array {
if (!arrays.every(a => a instanceof Uint8Array)) throw new Error('Uint8Array list expected');
if (arrays.length === 1) return arrays[0];
const length = arrays.reduce((a, arr) => a + arr.length, 0);
const result = new Uint8Array(length);
for (let i = 0, pad = 0; i < arrays.length; i++) {
const arr = arrays[i];
result.set(arr, pad);
pad += arr.length;
}
return result;
}
/** @ignore */
export function concatArray(elements: (Uint8Array | number[] | number)[]) {
return concatBytes(
...elements.map(e => {
if (typeof e === 'number') return octetsToBytes([e]);
if (e instanceof Array) return octetsToBytes(e);
return e;
})
);
}
/**
* Better `instanceof` check for types in different environments
* @ignore
*/
export function isInstance(object: any, type: any) {
return object instanceof type || object?.constructor?.name?.toLowerCase() === type.name;
}