-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
index.ts
670 lines (620 loc) · 21.4 KB
/
index.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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */
export interface Coder<F, T> {
encode(from: F): T;
decode(to: T): F;
}
export interface BytesCoder extends Coder<Uint8Array, string> {
encode: (data: Uint8Array) => string;
decode: (str: string) => Uint8Array;
}
function isBytes(a: unknown): a is Uint8Array {
return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
}
function isArrayOf(isString: boolean, arr: any[]) {
if (!Array.isArray(arr)) return false;
if (arr.length === 0) return true;
if (isString) {
return arr.every((item) => typeof item === 'string');
} else {
return arr.every((item) => Number.isSafeInteger(item));
}
}
// no abytes: seems to have 10% slowdown. Why?!
function afn(input: Function): input is Function {
if (typeof input !== 'function') throw new Error('function expected');
return true;
}
function astr(label: string, input: unknown): input is string {
if (typeof input !== 'string') throw new Error(`${label}: string expected`);
return true;
}
function anumber(n: number) {
if (!Number.isSafeInteger(n)) throw new Error(`invalid integer: ${n}`);
}
export const assertNumber = anumber;
function aArr(input: any[]) {
if (!Array.isArray(input)) throw new Error('array expected');
}
function astrArr(label: string, input: string[]) {
if (!isArrayOf(true, input)) throw new Error(`${label}: array of strings expected`);
}
function anumArr(label: string, input: number[]) {
if (!isArrayOf(false, input)) throw new Error(`${label}: array of numbers expected`);
}
// TODO: some recusive type inference so it would check correct order of input/output inside rest?
// like <string, number>, <number, bytes>, <bytes, float>
type Chain = [Coder<any, any>, ...Coder<any, any>[]];
// Extract info from Coder type
type Input<F> = F extends Coder<infer T, any> ? T : never;
type Output<F> = F extends Coder<any, infer T> ? T : never;
// Generic function for arrays
type First<T> = T extends [infer U, ...any[]] ? U : never;
type Last<T> = T extends [...any[], infer U] ? U : never;
type Tail<T> = T extends [any, ...infer U] ? U : never;
type AsChain<C extends Chain, Rest = Tail<C>> = {
// C[K] = Coder<Input<C[K]>, Input<Rest[k]>>
[K in keyof C]: Coder<Input<C[K]>, Input<K extends keyof Rest ? Rest[K] : any>>;
};
/**
* @__NO_SIDE_EFFECTS__
*/
function chain<T extends Chain & AsChain<T>>(...args: T): Coder<Input<First<T>>, Output<Last<T>>> {
const id = (a: any) => a;
// Wrap call in closure so JIT can inline calls
const wrap = (a: any, b: any) => (c: any) => a(b(c));
// Construct chain of args[-1].encode(args[-2].encode([...]))
const encode = args.map((x) => x.encode).reduceRight(wrap, id);
// Construct chain of args[0].decode(args[1].decode(...))
const decode = args.map((x) => x.decode).reduce(wrap, id);
return { encode, decode };
}
/**
* Encodes integer radix representation to array of strings using alphabet and back.
* Could also be array of strings.
* @__NO_SIDE_EFFECTS__
*/
function alphabet(letters: string | string[]): Coder<number[], string[]> {
// mapping 1 to "b"
const lettersA = typeof letters === 'string' ? letters.split('') : letters;
const len = lettersA.length;
astrArr('alphabet', lettersA);
// mapping "b" to 1
const indexes = new Map(lettersA.map((l, i) => [l, i]));
return {
encode: (digits: number[]) => {
aArr(digits);
return digits.map((i) => {
if (!Number.isSafeInteger(i) || i < 0 || i >= len)
throw new Error(
`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${letters}`
);
return lettersA[i]!;
});
},
decode: (input: string[]): number[] => {
aArr(input);
return input.map((letter) => {
astr('alphabet.decode', letter);
const i = indexes.get(letter);
if (i === undefined) throw new Error(`Unknown letter: "${letter}". Allowed: ${letters}`);
return i;
});
},
};
}
/**
* @__NO_SIDE_EFFECTS__
*/
function join(separator = ''): Coder<string[], string> {
astr('join', separator);
return {
encode: (from) => {
astrArr('join.decode', from);
return from.join(separator);
},
decode: (to) => {
astr('join.decode', to);
return to.split(separator);
},
};
}
/**
* Pad strings array so it has integer number of bits
* @__NO_SIDE_EFFECTS__
*/
function padding(bits: number, chr = '='): Coder<string[], string[]> {
anumber(bits);
astr('padding', chr);
return {
encode(data: string[]): string[] {
astrArr('padding.encode', data);
while ((data.length * bits) % 8) data.push(chr);
return data;
},
decode(input: string[]): string[] {
astrArr('padding.decode', input);
let end = input.length;
if ((end * bits) % 8)
throw new Error('padding: invalid, string should have whole number of bytes');
for (; end > 0 && input[end - 1] === chr; end--) {
const last = end - 1;
const byte = last * bits;
if (byte % 8 === 0) throw new Error('padding: invalid, string has too much padding');
}
return input.slice(0, end);
},
};
}
/**
* @__NO_SIDE_EFFECTS__
*/
function normalize<T>(fn: (val: T) => T): Coder<T, T> {
afn(fn);
return { encode: (from: T) => from, decode: (to: T) => fn(to) };
}
/**
* Slow: O(n^2) time complexity
*/
function convertRadix(data: number[], from: number, to: number): number[] {
// base 1 is impossible
if (from < 2) throw new Error(`convertRadix: invalid from=${from}, base cannot be less than 2`);
if (to < 2) throw new Error(`convertRadix: invalid to=${to}, base cannot be less than 2`);
aArr(data);
if (!data.length) return [];
let pos = 0;
const res = [];
const digits = Array.from(data, (d) => {
anumber(d);
if (d < 0 || d >= from) throw new Error(`invalid integer: ${d}`);
return d;
});
const dlen = digits.length;
while (true) {
let carry = 0;
let done = true;
for (let i = pos; i < dlen; i++) {
const digit = digits[i]!;
const fromCarry = from * carry;
const digitBase = fromCarry + digit;
if (
!Number.isSafeInteger(digitBase) ||
fromCarry / from !== carry ||
digitBase - digit !== fromCarry
) {
throw new Error('convertRadix: carry overflow');
}
const div = digitBase / to;
carry = digitBase % to;
const rounded = Math.floor(div);
digits[i] = rounded;
if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase)
throw new Error('convertRadix: carry overflow');
if (!done) continue;
else if (!rounded) pos = i;
else done = false;
}
res.push(carry);
if (done) break;
}
for (let i = 0; i < data.length - 1 && data[i] === 0; i++) res.push(0);
return res.reverse();
}
const gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b));
const radix2carry = /* @__NO_SIDE_EFFECTS__ */ (from: number, to: number) =>
from + (to - gcd(from, to));
const powers: number[] = /* @__PURE__ */ (() => {
let res = [];
for (let i = 0; i < 40; i++) res.push(2 ** i);
return res;
})();
/**
* Implemented with numbers, because BigInt is 5x slower
*/
function convertRadix2(data: number[], from: number, to: number, padding: boolean): number[] {
aArr(data);
if (from <= 0 || from > 32) throw new Error(`convertRadix2: wrong from=${from}`);
if (to <= 0 || to > 32) throw new Error(`convertRadix2: wrong to=${to}`);
if (radix2carry(from, to) > 32) {
throw new Error(
`convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`
);
}
let carry = 0;
let pos = 0; // bitwise position in current element
const max = powers[from]!;
const mask = powers[to]! - 1;
const res: number[] = [];
for (const n of data) {
anumber(n);
if (n >= max) throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);
carry = (carry << from) | n;
if (pos + from > 32) throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);
pos += from;
for (; pos >= to; pos -= to) res.push(((carry >> (pos - to)) & mask) >>> 0);
const pow = powers[pos];
if (pow === undefined) throw new Error('invalid carry');
carry &= pow - 1; // clean carry, otherwise it will cause overflow
}
carry = (carry << (to - pos)) & mask;
if (!padding && pos >= from) throw new Error('Excess padding');
if (!padding && carry > 0) throw new Error(`Non-zero padding: ${carry}`);
if (padding && pos > 0) res.push(carry >>> 0);
return res;
}
/**
* @__NO_SIDE_EFFECTS__
*/
function radix(num: number): Coder<Uint8Array, number[]> {
anumber(num);
const _256 = 2 ** 8;
return {
encode: (bytes: Uint8Array) => {
if (!isBytes(bytes)) throw new Error('radix.encode input should be Uint8Array');
return convertRadix(Array.from(bytes), _256, num);
},
decode: (digits: number[]) => {
anumArr('radix.decode', digits);
return Uint8Array.from(convertRadix(digits, num, _256));
},
};
}
/**
* If both bases are power of same number (like `2**8 <-> 2**64`),
* there is a linear algorithm. For now we have implementation for power-of-two bases only.
* @__NO_SIDE_EFFECTS__
*/
function radix2(bits: number, revPadding = false): Coder<Uint8Array, number[]> {
anumber(bits);
if (bits <= 0 || bits > 32) throw new Error('radix2: bits should be in (0..32]');
if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32)
throw new Error('radix2: carry overflow');
return {
encode: (bytes: Uint8Array) => {
if (!isBytes(bytes)) throw new Error('radix2.encode input should be Uint8Array');
return convertRadix2(Array.from(bytes), 8, bits, !revPadding);
},
decode: (digits: number[]) => {
anumArr('radix2.decode', digits);
return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));
},
};
}
type ArgumentTypes<F extends Function> = F extends (...args: infer A) => any ? A : never;
function unsafeWrapper<T extends (...args: any) => any>(fn: T) {
afn(fn);
return function (...args: ArgumentTypes<T>): ReturnType<T> | void {
try {
return fn.apply(null, args);
} catch (e) {}
};
}
function checksum(
len: number,
fn: (data: Uint8Array) => Uint8Array
): Coder<Uint8Array, Uint8Array> {
anumber(len);
afn(fn);
return {
encode(data: Uint8Array) {
if (!isBytes(data)) throw new Error('checksum.encode: input should be Uint8Array');
const sum = fn(data).slice(0, len);
const res = new Uint8Array(data.length + len);
res.set(data);
res.set(sum, data.length);
return res;
},
decode(data: Uint8Array) {
if (!isBytes(data)) throw new Error('checksum.decode: input should be Uint8Array');
const payload = data.slice(0, -len);
const oldChecksum = data.slice(-len);
const newChecksum = fn(payload).slice(0, len);
for (let i = 0; i < len; i++)
if (newChecksum[i] !== oldChecksum[i]) throw new Error('Invalid checksum');
return payload;
},
};
}
// prettier-ignore
export const utils = {
alphabet, chain, checksum, convertRadix, convertRadix2, radix, radix2, join, padding,
};
// RFC 4648 aka RFC 3548
// ---------------------
/**
* base16 encoding.
*/
export const base16: BytesCoder = chain(radix2(4), alphabet('0123456789ABCDEF'), join(''));
export const base32: BytesCoder = chain(
radix2(5),
alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'),
padding(5),
join('')
);
export const base32nopad: BytesCoder = chain(
radix2(5),
alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'),
join('')
);
export const base32hex: BytesCoder = chain(
radix2(5),
alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'),
padding(5),
join('')
);
export const base32hexnopad: BytesCoder = chain(
radix2(5),
alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'),
join('')
);
export const base32crockford: BytesCoder = chain(
radix2(5),
alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'),
join(''),
normalize((s: string) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1'))
);
/**
* base64 with padding. For no padding, use `base64nopad`.
* @example
* const b = base64.decode('A951'); // Uint8Array.from([ 3, 222, 117 ])
* base64.encode(b); // 'A951'
*/
export const base64: BytesCoder = chain(
radix2(6),
alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'),
padding(6),
join('')
);
/**
* base64 without padding.
*/
export const base64nopad: BytesCoder = chain(
radix2(6),
alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'),
join('')
);
export const base64url: BytesCoder = chain(
radix2(6),
alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'),
padding(6),
join('')
);
export const base64urlnopad: BytesCoder = chain(
radix2(6),
alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'),
join('')
);
// base58 code
// -----------
const genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc: string) =>
chain(radix(58), alphabet(abc), join(''));
/**
* Base58: base64 without characters +, /, 0, O, I, l.
* Quadratic (O(n^2)) - so, can't be used on large inputs.
*/
export const base58: BytesCoder = genBase58(
'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
);
export const base58flickr: BytesCoder = genBase58(
'123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
);
export const base58xrp: BytesCoder = genBase58(
'rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz'
);
// Data len (index) -> encoded block len
const XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];
/**
* XMR version of base58.
* Done in 8-byte blocks (which equals 11 chars in decoding). Last (non-full) block padded with '1' to size in XMR_BLOCK_LEN.
* Block encoding significantly reduces quadratic complexity of base58.
*/
export const base58xmr: BytesCoder = {
encode(data: Uint8Array) {
let res = '';
for (let i = 0; i < data.length; i += 8) {
const block = data.subarray(i, i + 8);
res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length]!, '1');
}
return res;
},
decode(str: string) {
let res: number[] = [];
for (let i = 0; i < str.length; i += 11) {
const slice = str.slice(i, i + 11);
const blockLen = XMR_BLOCK_LEN.indexOf(slice.length);
const block = base58.decode(slice);
for (let j = 0; j < block.length - blockLen; j++) {
if (block[j] !== 0) throw new Error('base58xmr: wrong padding');
}
res = res.concat(Array.from(block.slice(block.length - blockLen)));
}
return Uint8Array.from(res);
},
};
export const createBase58check = (sha256: (data: Uint8Array) => Uint8Array): BytesCoder =>
chain(
checksum(4, (data) => sha256(sha256(data))),
base58
);
/**
* Use `createBase58check` instead.
* @deprecated
*/
export const base58check = createBase58check;
// Bech32 code
// -----------
export interface Bech32Decoded<Prefix extends string = string> {
prefix: Prefix;
words: number[];
}
export interface Bech32DecodedWithArray<Prefix extends string = string> {
prefix: Prefix;
words: number[];
bytes: Uint8Array;
}
const BECH_ALPHABET: Coder<number[], string> = chain(
alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'),
join('')
);
const POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];
function bech32Polymod(pre: number): number {
const b = pre >> 25;
let chk = (pre & 0x1ffffff) << 5;
for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {
if (((b >> i) & 1) === 1) chk ^= POLYMOD_GENERATORS[i]!;
}
return chk;
}
function bechChecksum(prefix: string, words: number[], encodingConst = 1): string {
const len = prefix.length;
let chk = 1;
for (let i = 0; i < len; i++) {
const c = prefix.charCodeAt(i);
if (c < 33 || c > 126) throw new Error(`Invalid prefix (${prefix})`);
chk = bech32Polymod(chk) ^ (c >> 5);
}
chk = bech32Polymod(chk);
for (let i = 0; i < len; i++) chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f);
for (let v of words) chk = bech32Polymod(chk) ^ v;
for (let i = 0; i < 6; i++) chk = bech32Polymod(chk);
chk ^= encodingConst;
return BECH_ALPHABET.encode(convertRadix2([chk % powers[30]!], 30, 5, false));
}
export interface Bech32 {
encode<Prefix extends string>(
prefix: Prefix,
words: number[] | Uint8Array,
limit?: number | false
): `${Lowercase<Prefix>}1${string}`;
decode<Prefix extends string>(
str: `${Prefix}1${string}`,
limit?: number | false
): Bech32Decoded<Prefix>;
encodeFromBytes(prefix: string, bytes: Uint8Array): string;
decodeToBytes(str: string): Bech32DecodedWithArray;
decodeUnsafe(str: string, limit?: number | false): void | Bech32Decoded<string>;
fromWords(to: number[]): Uint8Array;
fromWordsUnsafe(to: number[]): void | Uint8Array;
toWords(from: Uint8Array): number[];
}
/**
* @__NO_SIDE_EFFECTS__
*/
function genBech32(encoding: 'bech32' | 'bech32m'): Bech32 {
const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3;
const _words = radix2(5);
const fromWords = _words.decode;
const toWords = _words.encode;
const fromWordsUnsafe = unsafeWrapper(fromWords);
function encode<Prefix extends string>(
prefix: Prefix,
words: number[] | Uint8Array,
limit: number | false = 90
): `${Lowercase<Prefix>}1${string}` {
astr('bech32.encode prefix', prefix);
if (isBytes(words)) words = Array.from(words);
anumArr('bech32.encode', words);
const plen = prefix.length;
if (plen === 0) throw new TypeError(`Invalid prefix length ${plen}`);
const actualLength = plen + 7 + words.length;
if (limit !== false && actualLength > limit)
throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);
const lowered = prefix.toLowerCase();
const sum = bechChecksum(lowered, words, ENCODING_CONST);
return `${lowered}1${BECH_ALPHABET.encode(words)}${sum}` as `${Lowercase<Prefix>}1${string}`;
}
function decode<Prefix extends string>(
str: `${Prefix}1${string}`,
limit?: number | false
): Bech32Decoded<Prefix>;
function decode(str: string, limit?: number | false): Bech32Decoded;
function decode(str: string, limit: number | false = 90): Bech32Decoded {
astr('bech32.decode input', str);
const slen = str.length;
if (slen < 8 || (limit !== false && slen > limit))
throw new TypeError(`invalid string length: ${slen} (${str}). Expected (8..${limit})`);
// don't allow mixed case
const lowered = str.toLowerCase();
if (str !== lowered && str !== str.toUpperCase())
throw new Error(`String must be lowercase or uppercase`);
const sepIndex = lowered.lastIndexOf('1');
if (sepIndex === 0 || sepIndex === -1)
throw new Error(`Letter "1" must be present between prefix and data only`);
const prefix = lowered.slice(0, sepIndex);
const data = lowered.slice(sepIndex + 1);
if (data.length < 6) throw new Error('Data must be at least 6 characters long');
const words = BECH_ALPHABET.decode(data).slice(0, -6);
const sum = bechChecksum(prefix, words, ENCODING_CONST);
if (!data.endsWith(sum)) throw new Error(`Invalid checksum in ${str}: expected "${sum}"`);
return { prefix, words };
}
const decodeUnsafe = unsafeWrapper(decode);
function decodeToBytes(str: string): Bech32DecodedWithArray {
const { prefix, words } = decode(str, false);
return { prefix, words, bytes: fromWords(words) };
}
function encodeFromBytes(prefix: string, bytes: Uint8Array) {
return encode(prefix, toWords(bytes));
}
return {
encode,
decode,
encodeFromBytes,
decodeToBytes,
decodeUnsafe,
fromWords,
fromWordsUnsafe,
toWords,
};
}
/**
* Low-level bech32 operations. Operates on words.
*/
export const bech32: Bech32 = genBech32('bech32');
export const bech32m: Bech32 = genBech32('bech32m');
declare const TextEncoder: any;
declare const TextDecoder: any;
/**
* UTF-8-to-byte decoder. Uses built-in TextDecoder / TextEncoder.
* @example
* const b = utf8.decode("hey"); // => new Uint8Array([ 104, 101, 121 ])
* const str = utf8.encode(b); // "hey"
*/
export const utf8: BytesCoder = {
encode: (data) => new TextDecoder().decode(data),
decode: (str) => new TextEncoder().encode(str),
};
/**
* hex string decoder.
* @example
* const b = hex.decode("0102ff"); // => new Uint8Array([ 1, 2, 255 ])
* const str = hex.encode(b); // "0102ff"
*/
export const hex: BytesCoder = chain(
radix2(4),
alphabet('0123456789abcdef'),
join(''),
normalize((s: string) => {
if (typeof s !== 'string' || s.length % 2 !== 0)
throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`);
return s.toLowerCase();
})
);
// prettier-ignore
const CODERS = {
utf8, hex, base16, base32, base64, base64url, base58, base58xmr
};
type CoderType = keyof typeof CODERS;
const coderTypeError =
'Invalid encoding type. Available types: utf8, hex, base16, base32, base64, base64url, base58, base58xmr';
export const bytesToString = (type: CoderType, bytes: Uint8Array): string => {
if (typeof type !== 'string' || !CODERS.hasOwnProperty(type)) throw new TypeError(coderTypeError);
if (!isBytes(bytes)) throw new TypeError('bytesToString() expects Uint8Array');
return CODERS[type].encode(bytes);
};
export const str = bytesToString; // as in python, but for bytes only
export const stringToBytes = (type: CoderType, str: string): Uint8Array => {
if (!CODERS.hasOwnProperty(type)) throw new TypeError(coderTypeError);
if (typeof str !== 'string') throw new TypeError('stringToBytes() expects string');
return CODERS[type].decode(str);
};
export const bytes = stringToBytes;