@decryption/base 0.2.0
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.
- package/LICENSE +21 -0
- package/README.md +75 -0
- package/esm/index.js +1056 -0
- package/index.d.ts +555 -0
- package/index.js +1062 -0
- package/package.json +44 -0
package/index.js
ADDED
|
@@ -0,0 +1,1062 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
+
exports.bytes = exports.stringToBytes = exports.str = exports.bytesToString = exports.hex = exports.__TESTS = exports.utf8 = exports.ascii = exports.bech32m = exports.bech32 = exports.base58check = exports.createBase58check = exports.base58xmr = exports.base58xrp = exports.base58flickr = exports.base58 = exports.base64urlnopad = exports.base64url = exports.base64nopad = exports.base64 = exports.base32crockford = exports.base32hexnopad = exports.base32hex = exports.base32nopad = exports.base32 = exports.base16 = exports.utils = void 0;
|
|
5
|
+
function isBytes(a) {
|
|
6
|
+
// Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases. The
|
|
7
|
+
// fallback still requires a real ArrayBuffer view, so plain JSON-deserialized
|
|
8
|
+
// `{ constructor: ... }` spoofing is rejected. `BYTES_PER_ELEMENT === 1` keeps the
|
|
9
|
+
// fallback on byte-oriented views.
|
|
10
|
+
return (a instanceof Uint8Array ||
|
|
11
|
+
(ArrayBuffer.isView(a) &&
|
|
12
|
+
a.constructor.name === 'Uint8Array' &&
|
|
13
|
+
'BYTES_PER_ELEMENT' in a &&
|
|
14
|
+
a.BYTES_PER_ELEMENT === 1));
|
|
15
|
+
}
|
|
16
|
+
/** Asserts something is Uint8Array. */
|
|
17
|
+
function abytes(b) {
|
|
18
|
+
if (!isBytes(b))
|
|
19
|
+
throw new TypeError('Uint8Array expected');
|
|
20
|
+
}
|
|
21
|
+
function isArrayOf(isString, arr) {
|
|
22
|
+
if (!Array.isArray(arr))
|
|
23
|
+
return false;
|
|
24
|
+
if (arr.length === 0)
|
|
25
|
+
return true;
|
|
26
|
+
if (isString) {
|
|
27
|
+
return arr.every((item) => typeof item === 'string');
|
|
28
|
+
}
|
|
29
|
+
else {
|
|
30
|
+
return arr.every((item) => Number.isSafeInteger(item));
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
function afn(input) {
|
|
34
|
+
if (typeof input !== 'function')
|
|
35
|
+
throw new TypeError('function expected');
|
|
36
|
+
return true;
|
|
37
|
+
}
|
|
38
|
+
function astr(label, input) {
|
|
39
|
+
if (typeof input !== 'string')
|
|
40
|
+
throw new TypeError(`${label}: string expected`);
|
|
41
|
+
return true;
|
|
42
|
+
}
|
|
43
|
+
function anumber(n) {
|
|
44
|
+
if (typeof n !== 'number')
|
|
45
|
+
throw new TypeError(`number expected, got ${typeof n}`);
|
|
46
|
+
if (!Number.isSafeInteger(n))
|
|
47
|
+
throw new RangeError(`invalid integer: ${n}`);
|
|
48
|
+
}
|
|
49
|
+
function aArr(input) {
|
|
50
|
+
if (!Array.isArray(input))
|
|
51
|
+
throw new TypeError('array expected');
|
|
52
|
+
}
|
|
53
|
+
function astrArr(label, input) {
|
|
54
|
+
if (!isArrayOf(true, input))
|
|
55
|
+
throw new TypeError(`${label}: array of strings expected`);
|
|
56
|
+
}
|
|
57
|
+
function anumArr(label, input) {
|
|
58
|
+
if (!isArrayOf(false, input))
|
|
59
|
+
throw new TypeError(`${label}: array of numbers expected`);
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* @__NO_SIDE_EFFECTS__
|
|
63
|
+
*/
|
|
64
|
+
function chain(...args) {
|
|
65
|
+
const id = (a) => a;
|
|
66
|
+
// Wrap call in closure so JIT can inline calls
|
|
67
|
+
const wrap = (a, b) => (c) => a(b(c));
|
|
68
|
+
// Construct chain of args[-1].encode(args[-2].encode([...]))
|
|
69
|
+
const encode = args.map((x) => x.encode).reduceRight(wrap, id);
|
|
70
|
+
// Construct chain of args[0].decode(args[1].decode(...))
|
|
71
|
+
const decode = args.map((x) => x.decode).reduce(wrap, id);
|
|
72
|
+
return { encode, decode };
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Encodes integer radix representation to array of strings using alphabet and back.
|
|
76
|
+
* Could also be array of strings.
|
|
77
|
+
* @__NO_SIDE_EFFECTS__
|
|
78
|
+
*/
|
|
79
|
+
function alphabet(letters) {
|
|
80
|
+
// mapping 1 to "b"
|
|
81
|
+
const lettersA = typeof letters === 'string' ? letters.split('') : letters;
|
|
82
|
+
const len = lettersA.length;
|
|
83
|
+
astrArr('alphabet', lettersA);
|
|
84
|
+
// mapping "b" to 1
|
|
85
|
+
const indexes = new Map(lettersA.map((l, i) => [l, i]));
|
|
86
|
+
return {
|
|
87
|
+
encode: (digits) => {
|
|
88
|
+
aArr(digits);
|
|
89
|
+
return digits.map((i) => {
|
|
90
|
+
if (!Number.isSafeInteger(i) || i < 0 || i >= len)
|
|
91
|
+
throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${letters}`);
|
|
92
|
+
return lettersA[i];
|
|
93
|
+
});
|
|
94
|
+
},
|
|
95
|
+
decode: (input) => {
|
|
96
|
+
aArr(input);
|
|
97
|
+
return input.map((letter) => {
|
|
98
|
+
astr('alphabet.decode', letter);
|
|
99
|
+
const i = indexes.get(letter);
|
|
100
|
+
if (i === undefined)
|
|
101
|
+
throw new Error(`Unknown letter: "${letter}". Allowed: ${letters}`);
|
|
102
|
+
return i;
|
|
103
|
+
});
|
|
104
|
+
},
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* @__NO_SIDE_EFFECTS__
|
|
109
|
+
*/
|
|
110
|
+
function join(separator = '') {
|
|
111
|
+
astr('join', separator);
|
|
112
|
+
// join('') is only lossless when each chunk is already unambiguous, such as single-symbol alphabets.
|
|
113
|
+
// Multi-character tokens need a separator that cannot appear inside the chunks.
|
|
114
|
+
return {
|
|
115
|
+
encode: (from) => {
|
|
116
|
+
astrArr('join.decode', from);
|
|
117
|
+
return from.join(separator);
|
|
118
|
+
},
|
|
119
|
+
decode: (to) => {
|
|
120
|
+
astr('join.decode', to);
|
|
121
|
+
return to.split(separator);
|
|
122
|
+
},
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Pad strings array so it has integer number of bits
|
|
127
|
+
* @__NO_SIDE_EFFECTS__
|
|
128
|
+
*/
|
|
129
|
+
function padding(bits, chr = '=') {
|
|
130
|
+
anumber(bits);
|
|
131
|
+
astr('padding', chr);
|
|
132
|
+
return {
|
|
133
|
+
encode(data) {
|
|
134
|
+
astrArr('padding.encode', data);
|
|
135
|
+
// Mutates the intermediate token array in place while appending pad chars.
|
|
136
|
+
// utils.padding callers that need to preserve their input should pass a copy.
|
|
137
|
+
while ((data.length * bits) % 8)
|
|
138
|
+
data.push(chr);
|
|
139
|
+
return data;
|
|
140
|
+
},
|
|
141
|
+
decode(input) {
|
|
142
|
+
astrArr('padding.decode', input);
|
|
143
|
+
let end = input.length;
|
|
144
|
+
if ((end * bits) % 8)
|
|
145
|
+
throw new Error('padding: invalid, string should have whole number of bytes');
|
|
146
|
+
for (; end > 0 && input[end - 1] === chr; end--) {
|
|
147
|
+
const last = end - 1;
|
|
148
|
+
const byte = last * bits;
|
|
149
|
+
if (byte % 8 === 0)
|
|
150
|
+
throw new Error('padding: invalid, string has too much padding');
|
|
151
|
+
}
|
|
152
|
+
return input.slice(0, end);
|
|
153
|
+
},
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* @__NO_SIDE_EFFECTS__
|
|
158
|
+
*/
|
|
159
|
+
function normalize(fn) {
|
|
160
|
+
afn(fn);
|
|
161
|
+
return { encode: (from) => from, decode: (to) => fn(to) };
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Slow: O(n^2) time complexity
|
|
165
|
+
*/
|
|
166
|
+
function convertRadix(data, from, to) {
|
|
167
|
+
// base 1 is impossible
|
|
168
|
+
if (from < 2)
|
|
169
|
+
throw new RangeError(`convertRadix: invalid from=${from}, base cannot be less than 2`);
|
|
170
|
+
if (to < 2)
|
|
171
|
+
throw new RangeError(`convertRadix: invalid to=${to}, base cannot be less than 2`);
|
|
172
|
+
aArr(data);
|
|
173
|
+
if (!data.length)
|
|
174
|
+
return [];
|
|
175
|
+
let pos = 0;
|
|
176
|
+
const res = [];
|
|
177
|
+
const digits = Array.from(data, (d) => {
|
|
178
|
+
anumber(d);
|
|
179
|
+
if (d < 0 || d >= from)
|
|
180
|
+
throw new Error(`invalid integer: ${d}`);
|
|
181
|
+
return d;
|
|
182
|
+
});
|
|
183
|
+
const dlen = digits.length;
|
|
184
|
+
while (true) {
|
|
185
|
+
let carry = 0;
|
|
186
|
+
let done = true;
|
|
187
|
+
for (let i = pos; i < dlen; i++) {
|
|
188
|
+
const digit = digits[i];
|
|
189
|
+
const fromCarry = from * carry;
|
|
190
|
+
const digitBase = fromCarry + digit;
|
|
191
|
+
if (!Number.isSafeInteger(digitBase) ||
|
|
192
|
+
fromCarry / from !== carry ||
|
|
193
|
+
digitBase - digit !== fromCarry) {
|
|
194
|
+
throw new Error('convertRadix: carry overflow');
|
|
195
|
+
}
|
|
196
|
+
const div = digitBase / to;
|
|
197
|
+
carry = digitBase % to;
|
|
198
|
+
const rounded = Math.floor(div);
|
|
199
|
+
digits[i] = rounded;
|
|
200
|
+
if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase)
|
|
201
|
+
throw new Error('convertRadix: carry overflow');
|
|
202
|
+
if (!done)
|
|
203
|
+
continue;
|
|
204
|
+
else if (!rounded)
|
|
205
|
+
pos = i;
|
|
206
|
+
else
|
|
207
|
+
done = false;
|
|
208
|
+
}
|
|
209
|
+
res.push(carry);
|
|
210
|
+
if (done)
|
|
211
|
+
break;
|
|
212
|
+
}
|
|
213
|
+
// Preserve explicit leading zero digits so callers like base58 keep zero-prefix semantics.
|
|
214
|
+
for (let i = 0; i < data.length - 1 && data[i] === 0; i++)
|
|
215
|
+
res.push(0);
|
|
216
|
+
return res.reverse();
|
|
217
|
+
}
|
|
218
|
+
const gcd = (a, b) => (b === 0 ? a : gcd(b, a % b));
|
|
219
|
+
// Maximum carry width before the `pos` cycle repeats.
|
|
220
|
+
// Residues advance in gcd(from, to) steps, so the largest pre-drain width is from + (to - gcd).
|
|
221
|
+
const radix2carry = /* @__NO_SIDE_EFFECTS__ */ (from, to) => from + (to - gcd(from, to));
|
|
222
|
+
const powers = /* @__PURE__ */ (() => {
|
|
223
|
+
let res = [];
|
|
224
|
+
for (let i = 0; i < 40; i++)
|
|
225
|
+
res.push(2 ** i);
|
|
226
|
+
return res;
|
|
227
|
+
})();
|
|
228
|
+
/**
|
|
229
|
+
* Implemented with numbers, because BigInt is 5x slower
|
|
230
|
+
*/
|
|
231
|
+
function convertRadix2(data, from, to, padding) {
|
|
232
|
+
aArr(data);
|
|
233
|
+
if (from <= 0 || from > 32)
|
|
234
|
+
throw new RangeError(`convertRadix2: wrong from=${from}`);
|
|
235
|
+
if (to <= 0 || to > 32)
|
|
236
|
+
throw new RangeError(`convertRadix2: wrong to=${to}`);
|
|
237
|
+
if (radix2carry(from, to) > 32) {
|
|
238
|
+
throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`);
|
|
239
|
+
}
|
|
240
|
+
let carry = 0;
|
|
241
|
+
let pos = 0; // bitwise position in current element
|
|
242
|
+
const max = powers[from];
|
|
243
|
+
const mask = powers[to] - 1;
|
|
244
|
+
const res = [];
|
|
245
|
+
for (const n of data) {
|
|
246
|
+
anumber(n);
|
|
247
|
+
if (n >= max)
|
|
248
|
+
throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);
|
|
249
|
+
carry = (carry << from) | n;
|
|
250
|
+
if (pos + from > 32)
|
|
251
|
+
throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);
|
|
252
|
+
pos += from;
|
|
253
|
+
for (; pos >= to; pos -= to)
|
|
254
|
+
res.push(((carry >> (pos - to)) & mask) >>> 0);
|
|
255
|
+
const pow = powers[pos];
|
|
256
|
+
if (pow === undefined)
|
|
257
|
+
throw new Error('invalid carry');
|
|
258
|
+
carry &= pow - 1; // clean carry, otherwise it will cause overflow
|
|
259
|
+
}
|
|
260
|
+
carry = (carry << (to - pos)) & mask;
|
|
261
|
+
// Canonical decode paths reject leftover whole input words and non-zero pad bits.
|
|
262
|
+
// For Bech32 5->8 regrouping, this is the "4 bits or less, all zeroes" tail rule.
|
|
263
|
+
if (!padding && pos >= from)
|
|
264
|
+
throw new Error('Excess padding');
|
|
265
|
+
if (!padding && carry > 0)
|
|
266
|
+
throw new Error(`Non-zero padding: ${carry}`);
|
|
267
|
+
if (padding && pos > 0)
|
|
268
|
+
res.push(carry >>> 0);
|
|
269
|
+
return res;
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* @__NO_SIDE_EFFECTS__
|
|
273
|
+
*/
|
|
274
|
+
function radix(num) {
|
|
275
|
+
anumber(num);
|
|
276
|
+
const _256 = 2 ** 8;
|
|
277
|
+
// Base-range and carry-overflow checks live in convertRadix so encode/decode reject unsupported bases symmetrically.
|
|
278
|
+
return {
|
|
279
|
+
encode: (bytes) => {
|
|
280
|
+
if (!isBytes(bytes))
|
|
281
|
+
throw new TypeError('radix.encode input should be Uint8Array');
|
|
282
|
+
return convertRadix(Array.from(bytes), _256, num);
|
|
283
|
+
},
|
|
284
|
+
decode: (digits) => {
|
|
285
|
+
anumArr('radix.decode', digits);
|
|
286
|
+
return Uint8Array.from(convertRadix(digits, num, _256));
|
|
287
|
+
},
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* If both bases are power of same number (like `2**8 <-> 2**64`),
|
|
292
|
+
* there is a linear algorithm. For now we have implementation for power-of-two bases only.
|
|
293
|
+
* @__NO_SIDE_EFFECTS__
|
|
294
|
+
*/
|
|
295
|
+
function radix2(bits, revPadding = false) {
|
|
296
|
+
anumber(bits);
|
|
297
|
+
if (bits <= 0 || bits > 32)
|
|
298
|
+
throw new RangeError('radix2: bits should be in (0..32]');
|
|
299
|
+
if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32)
|
|
300
|
+
throw new RangeError('radix2: carry overflow');
|
|
301
|
+
// revPadding flips which direction allows a partial zero tail.
|
|
302
|
+
// Default pads 8->bits and rejects extra bits on bits->8; `true` does the opposite.
|
|
303
|
+
return {
|
|
304
|
+
encode: (bytes) => {
|
|
305
|
+
if (!isBytes(bytes))
|
|
306
|
+
throw new TypeError('radix2.encode input should be Uint8Array');
|
|
307
|
+
return convertRadix2(Array.from(bytes), 8, bits, !revPadding);
|
|
308
|
+
},
|
|
309
|
+
decode: (digits) => {
|
|
310
|
+
anumArr('radix2.decode', digits);
|
|
311
|
+
return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));
|
|
312
|
+
},
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
function unsafeWrapper(fn) {
|
|
316
|
+
afn(fn);
|
|
317
|
+
return function (...args) {
|
|
318
|
+
// Only for *Unsafe APIs that intentionally collapse validation failures to `undefined`.
|
|
319
|
+
// Do not wrap code that needs to preserve exception details.
|
|
320
|
+
try {
|
|
321
|
+
return fn.apply(null, args);
|
|
322
|
+
}
|
|
323
|
+
catch (e) { }
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
function checksum(len, fn) {
|
|
327
|
+
anumber(len);
|
|
328
|
+
// Reject degenerate zero-byte checksums up front so callers don't accidentally
|
|
329
|
+
// build a no-op checksum stage.
|
|
330
|
+
if (len <= 0)
|
|
331
|
+
throw new RangeError(`checksum length must be positive: ${len}`);
|
|
332
|
+
afn(fn);
|
|
333
|
+
const _fn = fn;
|
|
334
|
+
// Uses the first `len` bytes of fn(data) in both directions.
|
|
335
|
+
// Current call sites rely on `len > 0` and checksum functions that return at least that many bytes.
|
|
336
|
+
return {
|
|
337
|
+
encode(data) {
|
|
338
|
+
if (!isBytes(data))
|
|
339
|
+
throw new TypeError('checksum.encode: input should be Uint8Array');
|
|
340
|
+
const sum = _fn(data).slice(0, len);
|
|
341
|
+
const res = new Uint8Array(data.length + len);
|
|
342
|
+
res.set(data);
|
|
343
|
+
res.set(sum, data.length);
|
|
344
|
+
return res;
|
|
345
|
+
},
|
|
346
|
+
decode(data) {
|
|
347
|
+
if (!isBytes(data))
|
|
348
|
+
throw new TypeError('checksum.decode: input should be Uint8Array');
|
|
349
|
+
const payload = data.slice(0, -len);
|
|
350
|
+
const oldChecksum = data.slice(-len);
|
|
351
|
+
const newChecksum = _fn(payload).slice(0, len);
|
|
352
|
+
for (let i = 0; i < len; i++)
|
|
353
|
+
if (newChecksum[i] !== oldChecksum[i])
|
|
354
|
+
throw new Error('Invalid checksum');
|
|
355
|
+
return payload;
|
|
356
|
+
},
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
// prettier-ignore
|
|
360
|
+
/**
|
|
361
|
+
* Low-level building blocks used by the exported codecs.
|
|
362
|
+
* @example
|
|
363
|
+
* Build a radix-32 coder from the low-level helpers.
|
|
364
|
+
* ```ts
|
|
365
|
+
* import { utils } from '@decryption/base';
|
|
366
|
+
* utils.radix2(5).encode(Uint8Array.from([1, 2, 3]));
|
|
367
|
+
* ```
|
|
368
|
+
*/
|
|
369
|
+
exports.utils = Object.freeze({
|
|
370
|
+
alphabet, chain, checksum, convertRadix, convertRadix2, radix, radix2, join, padding,
|
|
371
|
+
});
|
|
372
|
+
// RFC 4648 aka RFC 3548
|
|
373
|
+
// ---------------------
|
|
374
|
+
/**
|
|
375
|
+
* base16 encoding from RFC 4648.
|
|
376
|
+
* This codec uses RFC 4648 Table 5's uppercase alphabet directly.
|
|
377
|
+
* RFC 4648 §8 calls base16 "case-insensitive hex encoding", but we intentionally do not case-fold decode input here.
|
|
378
|
+
* Use `hex` for case-insensitive hex decoding.
|
|
379
|
+
* @example
|
|
380
|
+
* ```js
|
|
381
|
+
* base16.encode(Uint8Array.from([0x12, 0xab]));
|
|
382
|
+
* // => '12AB'
|
|
383
|
+
* ```
|
|
384
|
+
*/
|
|
385
|
+
exports.base16 = Object.freeze(chain(radix2(4), alphabet('0123456789ABCDEF'), join('')));
|
|
386
|
+
/**
|
|
387
|
+
* base32 encoding from RFC 4648. Has padding.
|
|
388
|
+
* RFC 4648 §6 Table 3 uses uppercase letters, and RFC 4648 §3.4 allows applications to choose
|
|
389
|
+
* upper- or lowercase alphabets. We keep the published uppercase table and do not case-fold decode input.
|
|
390
|
+
* Use `base32nopad` for unpadded version.
|
|
391
|
+
* Also check out `base32hex`, `base32hexnopad`, `base32crockford`.
|
|
392
|
+
* @example
|
|
393
|
+
* ```js
|
|
394
|
+
* base32.encode(Uint8Array.from([0x12, 0xab]));
|
|
395
|
+
* // => 'CKVQ===='
|
|
396
|
+
* base32.decode('CKVQ====');
|
|
397
|
+
* // => Uint8Array.from([0x12, 0xab])
|
|
398
|
+
* ```
|
|
399
|
+
*/
|
|
400
|
+
exports.base32 = Object.freeze(chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), padding(5), join('')));
|
|
401
|
+
/**
|
|
402
|
+
* base32 encoding from RFC 4648. No padding.
|
|
403
|
+
* This variant inherits RFC 4648 base32's uppercase table and intentionally does not case-fold decode input.
|
|
404
|
+
* Use `base32` for padded version.
|
|
405
|
+
* Also check out `base32hex`, `base32hexnopad`, `base32crockford`.
|
|
406
|
+
* @example
|
|
407
|
+
* ```js
|
|
408
|
+
* base32nopad.encode(Uint8Array.from([0x12, 0xab]));
|
|
409
|
+
* // => 'CKVQ'
|
|
410
|
+
* base32nopad.decode('CKVQ');
|
|
411
|
+
* // => Uint8Array.from([0x12, 0xab])
|
|
412
|
+
* ```
|
|
413
|
+
*/
|
|
414
|
+
exports.base32nopad = Object.freeze(chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), join('')));
|
|
415
|
+
/**
|
|
416
|
+
* base32 encoding from RFC 4648. Padded. Compared to ordinary `base32`, slightly different alphabet.
|
|
417
|
+
* RFC 4648 §7 Table 4 uses uppercase letters, and we intentionally keep that table without case-folding decode input.
|
|
418
|
+
* Use `base32hexnopad` for unpadded version.
|
|
419
|
+
* @example
|
|
420
|
+
* ```js
|
|
421
|
+
* base32hex.encode(Uint8Array.from([0x12, 0xab]));
|
|
422
|
+
* // => '2ALG===='
|
|
423
|
+
* base32hex.decode('2ALG====');
|
|
424
|
+
* // => Uint8Array.from([0x12, 0xab])
|
|
425
|
+
* ```
|
|
426
|
+
*/
|
|
427
|
+
exports.base32hex = Object.freeze(chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), padding(5), join('')));
|
|
428
|
+
/**
|
|
429
|
+
* base32 encoding from RFC 4648. No padding. Compared to ordinary `base32`, slightly different alphabet.
|
|
430
|
+
* This variant inherits RFC 4648 base32hex's uppercase table and intentionally does not case-fold decode input.
|
|
431
|
+
* Use `base32hex` for padded version.
|
|
432
|
+
* @example
|
|
433
|
+
* ```js
|
|
434
|
+
* base32hexnopad.encode(Uint8Array.from([0x12, 0xab]));
|
|
435
|
+
* // => '2ALG'
|
|
436
|
+
* base32hexnopad.decode('2ALG');
|
|
437
|
+
* // => Uint8Array.from([0x12, 0xab])
|
|
438
|
+
* ```
|
|
439
|
+
*/
|
|
440
|
+
exports.base32hexnopad = Object.freeze(chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), join('')));
|
|
441
|
+
/**
|
|
442
|
+
* base32 encoding from RFC 4648. Doug Crockford's version.
|
|
443
|
+
* See {@link https://www.crockford.com/base32.html | Douglas Crockford's Base32}.
|
|
444
|
+
* @example
|
|
445
|
+
* ```js
|
|
446
|
+
* base32crockford.encode(Uint8Array.from([0x12, 0xab]));
|
|
447
|
+
* // => '2ANG'
|
|
448
|
+
* base32crockford.decode('2ANG');
|
|
449
|
+
* // => Uint8Array.from([0x12, 0xab])
|
|
450
|
+
* ```
|
|
451
|
+
*/
|
|
452
|
+
exports.base32crockford = Object.freeze(chain(radix2(5), alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'), join(''), normalize((s) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1'))));
|
|
453
|
+
// Built-in base64 conversion https://caniuse.com/mdn-javascript_builtins_uint8array_frombase64
|
|
454
|
+
// Require both directions before taking the native fast path, so base64/base64url don't mix native and JS behavior.
|
|
455
|
+
// prettier-ignore
|
|
456
|
+
const hasBase64Builtin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toBase64 === 'function' &&
|
|
457
|
+
typeof Uint8Array.fromBase64 === 'function')();
|
|
458
|
+
// Native `Uint8Array.fromBase64()` accepts these ASCII whitespace chars.
|
|
459
|
+
// Reject them first so the native base64 path still follows RFC 4648 §3.3.
|
|
460
|
+
// ASCII whitespace is U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, or U+0020 SPACE
|
|
461
|
+
const ASCII_WHITESPACE = /[\t\n\f\r ]/;
|
|
462
|
+
const decodeBase64Builtin = (s, isUrl) => {
|
|
463
|
+
astr('base64', s);
|
|
464
|
+
const alphabet = isUrl ? 'base64url' : 'base64';
|
|
465
|
+
// Per spec, .fromBase64 already throws on any other non-alphabet symbols except ASCII whitespace
|
|
466
|
+
// And checking just for whitespace makes decoding about 3x faster than a full range check.
|
|
467
|
+
// lastChunkHandling: 'strict' rejects loose tails and non-zero pad bits so native decoding stays canonical.
|
|
468
|
+
if (s.length > 0 && ASCII_WHITESPACE.test(s))
|
|
469
|
+
throw new Error('invalid base64');
|
|
470
|
+
return Uint8Array.fromBase64(s, { alphabet, lastChunkHandling: 'strict' });
|
|
471
|
+
};
|
|
472
|
+
/**
|
|
473
|
+
* base64 from RFC 4648. Padded.
|
|
474
|
+
* Use `base64nopad` for unpadded version.
|
|
475
|
+
* Also check out `base64url`, `base64urlnopad`.
|
|
476
|
+
* Falls back to built-in function, when available.
|
|
477
|
+
* @example
|
|
478
|
+
* ```js
|
|
479
|
+
* base64.encode(Uint8Array.from([0x12, 0xab]));
|
|
480
|
+
* // => 'Eqs='
|
|
481
|
+
* base64.decode('Eqs=');
|
|
482
|
+
* // => Uint8Array.from([0x12, 0xab])
|
|
483
|
+
* ```
|
|
484
|
+
*/
|
|
485
|
+
// prettier-ignore
|
|
486
|
+
exports.base64 = Object.freeze(hasBase64Builtin ? {
|
|
487
|
+
encode(b) { abytes(b); return b.toBase64(); },
|
|
488
|
+
decode(s) { return decodeBase64Builtin(s, false); },
|
|
489
|
+
} : chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), padding(6), join('')));
|
|
490
|
+
/**
|
|
491
|
+
* base64 from RFC 4648. No padding.
|
|
492
|
+
* Use `base64` for padded version.
|
|
493
|
+
* @example
|
|
494
|
+
* ```js
|
|
495
|
+
* base64nopad.encode(Uint8Array.from([0x12, 0xab]));
|
|
496
|
+
* // => 'Eqs'
|
|
497
|
+
* base64nopad.decode('Eqs');
|
|
498
|
+
* // => Uint8Array.from([0x12, 0xab])
|
|
499
|
+
* ```
|
|
500
|
+
*/
|
|
501
|
+
exports.base64nopad = Object.freeze(chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), join('')));
|
|
502
|
+
/**
|
|
503
|
+
* base64 from RFC 4648, using URL-safe alphabet. Padded.
|
|
504
|
+
* Use `base64urlnopad` for unpadded version.
|
|
505
|
+
* Falls back to built-in function, when available.
|
|
506
|
+
* @example
|
|
507
|
+
* ```js
|
|
508
|
+
* base64url.encode(Uint8Array.from([0x12, 0xab]));
|
|
509
|
+
* // => 'Eqs='
|
|
510
|
+
* base64url.decode('Eqs=');
|
|
511
|
+
* // => Uint8Array.from([0x12, 0xab])
|
|
512
|
+
* ```
|
|
513
|
+
*/
|
|
514
|
+
// prettier-ignore
|
|
515
|
+
exports.base64url = Object.freeze(hasBase64Builtin ? {
|
|
516
|
+
encode(b) { abytes(b); return b.toBase64({ alphabet: 'base64url' }); },
|
|
517
|
+
decode(s) { return decodeBase64Builtin(s, true); },
|
|
518
|
+
} : chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), padding(6), join('')));
|
|
519
|
+
/**
|
|
520
|
+
* base64 from RFC 4648, using URL-safe alphabet. No padding.
|
|
521
|
+
* Use `base64url` for padded version.
|
|
522
|
+
* @example
|
|
523
|
+
* ```js
|
|
524
|
+
* base64urlnopad.encode(Uint8Array.from([0x12, 0xab]));
|
|
525
|
+
* // => 'Eqs'
|
|
526
|
+
* base64urlnopad.decode('Eqs');
|
|
527
|
+
* // => Uint8Array.from([0x12, 0xab])
|
|
528
|
+
* ```
|
|
529
|
+
*/
|
|
530
|
+
exports.base64urlnopad = Object.freeze(chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), join('')));
|
|
531
|
+
// base58 code
|
|
532
|
+
// -----------
|
|
533
|
+
const genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc) => chain(radix(58), alphabet(abc), join(''));
|
|
534
|
+
/**
|
|
535
|
+
* base58: base64 without ambigous characters +, /, 0, O, I, l.
|
|
536
|
+
* Quadratic (O(n^2)) - so, can't be used on large inputs.
|
|
537
|
+
* @example
|
|
538
|
+
* ```js
|
|
539
|
+
* const text = base58.encode(Uint8Array.from([0, 1, 2]));
|
|
540
|
+
* base58.decode(text);
|
|
541
|
+
* // => Uint8Array.from([0, 1, 2])
|
|
542
|
+
* ```
|
|
543
|
+
*/
|
|
544
|
+
exports.base58 = Object.freeze(genBase58('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'));
|
|
545
|
+
/**
|
|
546
|
+
* base58: flickr version. Check out `base58`.
|
|
547
|
+
* @example
|
|
548
|
+
* Round-trip bytes with the Flickr alphabet.
|
|
549
|
+
* ```ts
|
|
550
|
+
* const text = base58flickr.encode(Uint8Array.from([0, 1, 2]));
|
|
551
|
+
* base58flickr.decode(text);
|
|
552
|
+
* ```
|
|
553
|
+
*/
|
|
554
|
+
exports.base58flickr = Object.freeze(genBase58('123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'));
|
|
555
|
+
/**
|
|
556
|
+
* base58: XRP version. Check out `base58`.
|
|
557
|
+
* @example
|
|
558
|
+
* Round-trip bytes with the XRP alphabet.
|
|
559
|
+
* ```ts
|
|
560
|
+
* const text = base58xrp.encode(Uint8Array.from([0, 1, 2]));
|
|
561
|
+
* base58xrp.decode(text);
|
|
562
|
+
* ```
|
|
563
|
+
*/
|
|
564
|
+
exports.base58xrp = Object.freeze(genBase58('rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz'));
|
|
565
|
+
// Data len (index) -> encoded block len.
|
|
566
|
+
// Monero pads each 1..8-byte block to this fixed base58 width so decode can recover the tail length.
|
|
567
|
+
const XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];
|
|
568
|
+
/**
|
|
569
|
+
* base58: XMR version. Check out `base58`.
|
|
570
|
+
* Done in 8-byte blocks (which equals 11 chars in decoding). Last (non-full) block padded with '1' to size in XMR_BLOCK_LEN.
|
|
571
|
+
* Block encoding significantly reduces quadratic complexity of base58.
|
|
572
|
+
* @example
|
|
573
|
+
* Round-trip bytes with the Monero block codec.
|
|
574
|
+
* ```ts
|
|
575
|
+
* const text = base58xmr.encode(Uint8Array.from([0, 1, 2]));
|
|
576
|
+
* base58xmr.decode(text);
|
|
577
|
+
* ```
|
|
578
|
+
*/
|
|
579
|
+
exports.base58xmr = Object.freeze({
|
|
580
|
+
encode(data) {
|
|
581
|
+
abytes(data);
|
|
582
|
+
let res = '';
|
|
583
|
+
for (let i = 0; i < data.length; i += 8) {
|
|
584
|
+
const block = data.subarray(i, i + 8);
|
|
585
|
+
res += exports.base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], '1');
|
|
586
|
+
}
|
|
587
|
+
return res;
|
|
588
|
+
},
|
|
589
|
+
decode(str) {
|
|
590
|
+
astr('base58xmr.decode', str);
|
|
591
|
+
let res = [];
|
|
592
|
+
for (let i = 0; i < str.length; i += 11) {
|
|
593
|
+
const slice = str.slice(i, i + 11);
|
|
594
|
+
const blockLen = XMR_BLOCK_LEN.indexOf(slice.length);
|
|
595
|
+
const block = exports.base58.decode(slice);
|
|
596
|
+
for (let j = 0; j < block.length - blockLen; j++) {
|
|
597
|
+
if (block[j] !== 0)
|
|
598
|
+
throw new Error('base58xmr: wrong padding');
|
|
599
|
+
}
|
|
600
|
+
res = res.concat(Array.from(block.slice(block.length - blockLen)));
|
|
601
|
+
}
|
|
602
|
+
return Uint8Array.from(res);
|
|
603
|
+
},
|
|
604
|
+
});
|
|
605
|
+
/**
|
|
606
|
+
* Method, which creates base58check encoder.
|
|
607
|
+
* Requires function, calculating sha256.
|
|
608
|
+
* Callers must include any version bytes in `data`; this helper only applies the
|
|
609
|
+
* 4-byte double-SHA256 checksum used by Bitcoin Base58Check.
|
|
610
|
+
* @param sha256 - Function used to calculate the checksum hash.
|
|
611
|
+
* @returns base58check codec using 4 checksum bytes.
|
|
612
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
613
|
+
* @example
|
|
614
|
+
* Create a base58check codec from a SHA-256 implementation.
|
|
615
|
+
* ```ts
|
|
616
|
+
* import { createBase58check } from '@decryption/base';
|
|
617
|
+
* import { sha256 } from '@decryption/hashes/sha2';
|
|
618
|
+
* const coder = createBase58check(sha256);
|
|
619
|
+
* coder.encode(Uint8Array.from([1, 2, 3]));
|
|
620
|
+
* ```
|
|
621
|
+
*/
|
|
622
|
+
const createBase58check = (sha256) => {
|
|
623
|
+
// Validate the hash function at construction time so wrong inputs fail before returning a coder.
|
|
624
|
+
afn(sha256);
|
|
625
|
+
const _sha256 = sha256;
|
|
626
|
+
return chain(checksum(4, (data) => _sha256(_sha256(data))), exports.base58);
|
|
627
|
+
};
|
|
628
|
+
exports.createBase58check = createBase58check;
|
|
629
|
+
/**
|
|
630
|
+
* Use `createBase58check` instead.
|
|
631
|
+
* @deprecated Use {@link createBase58check} instead.
|
|
632
|
+
* Callers must include any version bytes in `data`; this alias keeps the same
|
|
633
|
+
* 4-byte double-SHA256 checksum behavior as `createBase58check`.
|
|
634
|
+
* @param sha256 - Function used to calculate the checksum hash.
|
|
635
|
+
* @returns base58check codec using 4 checksum bytes.
|
|
636
|
+
* @example
|
|
637
|
+
* Create a base58check codec with the deprecated alias.
|
|
638
|
+
* ```ts
|
|
639
|
+
* import { base58check } from '@decryption/base';
|
|
640
|
+
* import { sha256 } from '@decryption/hashes/sha2';
|
|
641
|
+
* const coder = base58check(sha256);
|
|
642
|
+
* coder.encode(Uint8Array.from([1, 2, 3]));
|
|
643
|
+
* ```
|
|
644
|
+
*/
|
|
645
|
+
exports.base58check = exports.createBase58check;
|
|
646
|
+
// BIP 173 character table: data values 0..31 map to `qpzry9x8gf2tvdw0s3jn54khce6mua7l`.
|
|
647
|
+
const BECH_ALPHABET = chain(alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'), join(''));
|
|
648
|
+
// BIP 173 `bech32_polymod` GEN coefficients.
|
|
649
|
+
const POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];
|
|
650
|
+
// BIP 173 step split: this applies the polymod state transition before callers xor in the next 5-bit value.
|
|
651
|
+
function bech32Polymod(pre) {
|
|
652
|
+
const b = pre >> 25;
|
|
653
|
+
let chk = (pre & 0x1ffffff) << 5;
|
|
654
|
+
for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {
|
|
655
|
+
if (((b >> i) & 1) === 1)
|
|
656
|
+
chk ^= POLYMOD_GENERATORS[i];
|
|
657
|
+
}
|
|
658
|
+
return chk;
|
|
659
|
+
}
|
|
660
|
+
function bechChecksum(prefix, words, encodingConst = 1) {
|
|
661
|
+
const len = prefix.length;
|
|
662
|
+
let chk = 1;
|
|
663
|
+
for (let i = 0; i < len; i++) {
|
|
664
|
+
const c = prefix.charCodeAt(i);
|
|
665
|
+
if (c < 33 || c > 126)
|
|
666
|
+
throw new Error(`Invalid prefix (${prefix})`);
|
|
667
|
+
chk = bech32Polymod(chk) ^ (c >> 5);
|
|
668
|
+
}
|
|
669
|
+
chk = bech32Polymod(chk);
|
|
670
|
+
for (let i = 0; i < len; i++)
|
|
671
|
+
chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f);
|
|
672
|
+
for (let v of words)
|
|
673
|
+
chk = bech32Polymod(chk) ^ v;
|
|
674
|
+
for (let i = 0; i < 6; i++)
|
|
675
|
+
chk = bech32Polymod(chk);
|
|
676
|
+
// BIP 173/BIP 350: xor the final checksum constant, then emit the 30-bit state as six 5-bit symbols.
|
|
677
|
+
chk ^= encodingConst;
|
|
678
|
+
return BECH_ALPHABET.encode(convertRadix2([chk % powers[30]], 30, 5, false));
|
|
679
|
+
}
|
|
680
|
+
/**
|
|
681
|
+
* @__NO_SIDE_EFFECTS__
|
|
682
|
+
*/
|
|
683
|
+
function genBech32(encoding) {
|
|
684
|
+
// BIP 173 uses final xor constant 1; BIP 350 swaps in 0x2bc830a3 for Bech32m.
|
|
685
|
+
const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3;
|
|
686
|
+
const _words = radix2(5);
|
|
687
|
+
const fromWords = _words.decode;
|
|
688
|
+
const toWords = _words.encode;
|
|
689
|
+
const fromWordsUnsafe = unsafeWrapper(fromWords);
|
|
690
|
+
function encode(prefix, words, limit = 90) {
|
|
691
|
+
astr('bech32.encode prefix', prefix);
|
|
692
|
+
if (isBytes(words))
|
|
693
|
+
words = Array.from(words);
|
|
694
|
+
anumArr('bech32.encode', words);
|
|
695
|
+
const plen = prefix.length;
|
|
696
|
+
if (plen === 0)
|
|
697
|
+
throw new TypeError(`Invalid prefix length ${plen}`);
|
|
698
|
+
// Total output is hrp + `1` separator + payload words + 6 checksum chars.
|
|
699
|
+
const actualLength = plen + 7 + words.length;
|
|
700
|
+
if (limit !== false && actualLength > limit)
|
|
701
|
+
throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);
|
|
702
|
+
const lowered = prefix.toLowerCase();
|
|
703
|
+
const sum = bechChecksum(lowered, words, ENCODING_CONST);
|
|
704
|
+
return `${lowered}1${BECH_ALPHABET.encode(words)}${sum}`;
|
|
705
|
+
}
|
|
706
|
+
function decode(str, limit = 90) {
|
|
707
|
+
astr('bech32.decode input', str);
|
|
708
|
+
const slen = str.length;
|
|
709
|
+
// Minimum length is 1-char hrp + `1` separator + 6-char checksum.
|
|
710
|
+
if (slen < 8 || (limit !== false && slen > limit))
|
|
711
|
+
throw new TypeError(`invalid string length: ${slen} (${str}). Expected (8..${limit})`);
|
|
712
|
+
// don't allow mixed case
|
|
713
|
+
const lowered = str.toLowerCase();
|
|
714
|
+
if (str !== lowered && str !== str.toUpperCase())
|
|
715
|
+
throw new Error(`String must be lowercase or uppercase`);
|
|
716
|
+
const sepIndex = lowered.lastIndexOf('1');
|
|
717
|
+
if (sepIndex === 0 || sepIndex === -1)
|
|
718
|
+
throw new Error(`Letter "1" must be present between prefix and data only`);
|
|
719
|
+
const prefix = lowered.slice(0, sepIndex);
|
|
720
|
+
const data = lowered.slice(sepIndex + 1);
|
|
721
|
+
if (data.length < 6)
|
|
722
|
+
throw new Error('Data must be at least 6 characters long');
|
|
723
|
+
const words = BECH_ALPHABET.decode(data).slice(0, -6);
|
|
724
|
+
const sum = bechChecksum(prefix, words, ENCODING_CONST);
|
|
725
|
+
if (!data.endsWith(sum))
|
|
726
|
+
throw new Error(`Invalid checksum in ${str}: expected "${sum}"`);
|
|
727
|
+
return { prefix, words };
|
|
728
|
+
}
|
|
729
|
+
const decodeUnsafe = unsafeWrapper(decode);
|
|
730
|
+
function decodeToBytes(str) {
|
|
731
|
+
// Keep the byte helper unbounded; callers that need the default BIP 173 length cap should use decode(str).
|
|
732
|
+
const { prefix, words } = decode(str, false);
|
|
733
|
+
return {
|
|
734
|
+
prefix,
|
|
735
|
+
words,
|
|
736
|
+
bytes: fromWords(words),
|
|
737
|
+
};
|
|
738
|
+
}
|
|
739
|
+
function encodeFromBytes(prefix, bytes) {
|
|
740
|
+
// Keep the convenience wrapper on encode()'s default 90-char cap; custom limits should call encode(prefix, toWords(bytes), limit).
|
|
741
|
+
return encode(prefix, toWords(bytes));
|
|
742
|
+
}
|
|
743
|
+
return {
|
|
744
|
+
encode,
|
|
745
|
+
decode,
|
|
746
|
+
encodeFromBytes,
|
|
747
|
+
decodeToBytes,
|
|
748
|
+
decodeUnsafe,
|
|
749
|
+
fromWords,
|
|
750
|
+
fromWordsUnsafe,
|
|
751
|
+
toWords,
|
|
752
|
+
};
|
|
753
|
+
}
|
|
754
|
+
/**
|
|
755
|
+
* bech32 from BIP 173. Operates on words.
|
|
756
|
+
* For high-level helpers, check out {@link https://github.com/paulmillr/scure-btc-signer | scure-btc-signer}.
|
|
757
|
+
* @example
|
|
758
|
+
* Convert bytes to words, encode them, then decode back.
|
|
759
|
+
* ```ts
|
|
760
|
+
* const words = bech32.toWords(Uint8Array.from([1, 2, 3]));
|
|
761
|
+
* const text = bech32.encode('bc', words);
|
|
762
|
+
* bech32.decode(text);
|
|
763
|
+
* ```
|
|
764
|
+
*/
|
|
765
|
+
exports.bech32 = Object.freeze(genBech32('bech32'));
|
|
766
|
+
/**
|
|
767
|
+
* bech32m from BIP 350. Operates on words.
|
|
768
|
+
* It was to mitigate `bech32` weaknesses.
|
|
769
|
+
* For high-level helpers, check out {@link https://github.com/paulmillr/scure-btc-signer | scure-btc-signer}.
|
|
770
|
+
* @example
|
|
771
|
+
* Convert bytes to words, encode them with bech32m, then decode back.
|
|
772
|
+
* ```ts
|
|
773
|
+
* const words = bech32m.toWords(Uint8Array.from([1, 2, 3]));
|
|
774
|
+
* const text = bech32m.encode('bc', words);
|
|
775
|
+
* bech32m.decode(text);
|
|
776
|
+
* ```
|
|
777
|
+
*/
|
|
778
|
+
exports.bech32m = Object.freeze(genBech32('bech32m'));
|
|
779
|
+
/**
|
|
780
|
+
* ASCII-to-byte decoder. Rejects non-ASCII text and bytes instead of doing UTF-8 replacement.
|
|
781
|
+
* Method names follow `BytesCoder`, so `encode(bytes)` returns a string and `decode(string)` returns bytes.
|
|
782
|
+
* @example
|
|
783
|
+
* ```js
|
|
784
|
+
* const b = ascii.decode("ABC"); // => new Uint8Array([ 65, 66, 67 ])
|
|
785
|
+
* const str = ascii.encode(b); // "ABC"
|
|
786
|
+
* ```
|
|
787
|
+
*/
|
|
788
|
+
exports.ascii = Object.freeze({
|
|
789
|
+
encode(data) {
|
|
790
|
+
abytes(data);
|
|
791
|
+
let res = '';
|
|
792
|
+
for (let i = 0; i < data.length; i++) {
|
|
793
|
+
const byte = data[i];
|
|
794
|
+
// ASCII is 7-bit; reject bytes outside 0x00..0x7f instead of silently widening to
|
|
795
|
+
// Latin-1/UTF-8.
|
|
796
|
+
if (byte > 127)
|
|
797
|
+
throw new RangeError(`bytes contain non-ASCII byte ${byte} at position ${i}`);
|
|
798
|
+
res += String.fromCharCode(byte);
|
|
799
|
+
}
|
|
800
|
+
return res;
|
|
801
|
+
},
|
|
802
|
+
decode(str) {
|
|
803
|
+
if (typeof str !== 'string')
|
|
804
|
+
throw new TypeError('ascii string expected, got ' + typeof str);
|
|
805
|
+
const res = new Uint8Array(str.length);
|
|
806
|
+
for (let i = 0; i < str.length; i++) {
|
|
807
|
+
// Indexed access is much faster than Uint8Array.from(str, mapFn) here and keeps
|
|
808
|
+
// exact error positions.
|
|
809
|
+
const charCode = str.charCodeAt(i);
|
|
810
|
+
if (charCode > 127) {
|
|
811
|
+
throw new RangeError(`string contains non-ASCII character "${str[i]}" with code ${charCode} at position ${i}`);
|
|
812
|
+
}
|
|
813
|
+
res[i] = charCode;
|
|
814
|
+
}
|
|
815
|
+
return res;
|
|
816
|
+
},
|
|
817
|
+
});
|
|
818
|
+
const _isWellFormedShim = (str) => {
|
|
819
|
+
// encodeURI rejects malformed UTF-16, giving a compact fallback that matches native
|
|
820
|
+
// isWellFormed on our tests/fuzz corpus.
|
|
821
|
+
try {
|
|
822
|
+
return encodeURI(str) !== null;
|
|
823
|
+
}
|
|
824
|
+
catch {
|
|
825
|
+
return false;
|
|
826
|
+
}
|
|
827
|
+
};
|
|
828
|
+
const _isWellFormed = /* @__PURE__ */ (() =>
|
|
829
|
+
// Pick the native check once so utf8.decode doesn't re-probe String.prototype on every call.
|
|
830
|
+
typeof ''.isWellFormed === 'function'
|
|
831
|
+
? (str) => str.isWellFormed()
|
|
832
|
+
: _isWellFormedShim)();
|
|
833
|
+
// This fallback stays small because strict UTF-8 only needs fatal decoding plus well-formed
|
|
834
|
+
// UTF-16 checks, not the replacement, streaming, or legacy-encoding behavior of full platform
|
|
835
|
+
// text codecs.
|
|
836
|
+
const utf8Fallback = /* @__PURE__ */ Object.freeze({
|
|
837
|
+
encode(data) {
|
|
838
|
+
abytes(data);
|
|
839
|
+
let res = '';
|
|
840
|
+
for (let i = 0; i < data.length;) {
|
|
841
|
+
const a = data[i++];
|
|
842
|
+
if (a < 0b1000_0000) {
|
|
843
|
+
res += String.fromCharCode(a);
|
|
844
|
+
continue;
|
|
845
|
+
}
|
|
846
|
+
if (a < 0b1100_0010 || i >= data.length)
|
|
847
|
+
throw new TypeError(`invalid utf8 at byte ${i - 1}`);
|
|
848
|
+
const b = data[i++];
|
|
849
|
+
if ((b & 0b1100_0000) !== 0b1000_0000)
|
|
850
|
+
throw new TypeError(`invalid utf8 at byte ${i - 1}`);
|
|
851
|
+
let cp = ((a & 0b0001_1111) << 6) | (b & 0b0011_1111);
|
|
852
|
+
if (a >= 0b1110_0000) {
|
|
853
|
+
if (i >= data.length)
|
|
854
|
+
throw new TypeError(`invalid utf8 at byte ${i - 1}`);
|
|
855
|
+
const c = data[i++];
|
|
856
|
+
if ((c & 0b1100_0000) !== 0b1000_0000 ||
|
|
857
|
+
(a === 0b1110_0000 && b < 0b1010_0000) ||
|
|
858
|
+
(a === 0xed && b >= 0b1010_0000))
|
|
859
|
+
throw new TypeError(`invalid utf8 at byte ${i - 1}`);
|
|
860
|
+
cp = ((a & 0b0000_1111) << 12) | ((b & 0b0011_1111) << 6) | (c & 0b0011_1111);
|
|
861
|
+
if (a >= 0b1111_0000) {
|
|
862
|
+
if (i >= data.length)
|
|
863
|
+
throw new TypeError(`invalid utf8 at byte ${i - 1}`);
|
|
864
|
+
const d = data[i++];
|
|
865
|
+
if (a > 0b1111_0100 ||
|
|
866
|
+
(d & 0b1100_0000) !== 0b1000_0000 ||
|
|
867
|
+
(a === 0b1111_0000 && b < 0b1001_0000) ||
|
|
868
|
+
(a === 0b1111_0100 && b >= 0b1001_0000))
|
|
869
|
+
throw new TypeError(`invalid utf8 at byte ${i - 1}`);
|
|
870
|
+
cp =
|
|
871
|
+
((a & 7) << 18) |
|
|
872
|
+
((b & 0b0011_1111) << 12) |
|
|
873
|
+
((c & 0b0011_1111) << 6) |
|
|
874
|
+
(d & 0b0011_1111);
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
if (cp < 0x10000)
|
|
878
|
+
res += String.fromCharCode(cp);
|
|
879
|
+
else {
|
|
880
|
+
cp -= 0x10000;
|
|
881
|
+
res += String.fromCharCode((cp >> 10) + 0xd800, (cp & 0x3ff) + 0xdc00);
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
return res;
|
|
885
|
+
},
|
|
886
|
+
decode(str) {
|
|
887
|
+
astr('utf8', str);
|
|
888
|
+
if (!_isWellFormed(str))
|
|
889
|
+
throw new TypeError('utf8 expected well-formed string');
|
|
890
|
+
// Direct Uint8Array writes are much faster than number[] + Uint8Array.from on Hermes and
|
|
891
|
+
// large Node inputs.
|
|
892
|
+
const res = new Uint8Array(str.length * 3);
|
|
893
|
+
let pos = 0;
|
|
894
|
+
for (let i = 0; i < str.length; i++) {
|
|
895
|
+
let c = str.charCodeAt(i);
|
|
896
|
+
if (c < 0b1000_0000) {
|
|
897
|
+
res[pos++] = c;
|
|
898
|
+
continue;
|
|
899
|
+
}
|
|
900
|
+
if (c >= 0xd800 && c <= 0xdfff) {
|
|
901
|
+
const d = str.charCodeAt(++i);
|
|
902
|
+
c = 0x10000 + ((c - 0xd800) << 10) + d - 0xdc00;
|
|
903
|
+
}
|
|
904
|
+
if (c >= 0x10000) {
|
|
905
|
+
res[pos++] = (c >> 18) | 0b1111_0000;
|
|
906
|
+
res[pos++] = ((c >> 12) & 0b0011_1111) | 0b1000_0000;
|
|
907
|
+
}
|
|
908
|
+
else if (c >= 0x800)
|
|
909
|
+
res[pos++] = (c >> 12) | 0b1110_0000;
|
|
910
|
+
else
|
|
911
|
+
res[pos++] = (c >> 6) | 0b1100_0000;
|
|
912
|
+
if (c >= 0x800)
|
|
913
|
+
res[pos++] = ((c >> 6) & 0b0011_1111) | 0b1000_0000;
|
|
914
|
+
res[pos++] = (c & 0b0011_1111) | 0b1000_0000;
|
|
915
|
+
}
|
|
916
|
+
return res.subarray(0, pos);
|
|
917
|
+
},
|
|
918
|
+
});
|
|
919
|
+
/**
|
|
920
|
+
* Strict UTF-8-to-byte decoder. Uses built-in TextDecoder / TextEncoder when available.
|
|
921
|
+
* Method names follow `BytesCoder`, so `encode(bytes)` returns a string and
|
|
922
|
+
* `decode(string)` returns bytes.
|
|
923
|
+
* `encode(bytes)` requires Uint8Array input, preserves an explicit leading BOM, and
|
|
924
|
+
* throws on invalid UTF-8 bytes.
|
|
925
|
+
* `decode(string)` requires a primitive string and throws on malformed UTF-16 strings with
|
|
926
|
+
* lone surrogates.
|
|
927
|
+
* @example
|
|
928
|
+
* ```js
|
|
929
|
+
* const b = utf8.decode("hey"); // => new Uint8Array([ 104, 101, 121 ])
|
|
930
|
+
* const str = utf8.encode(b); // "hey"
|
|
931
|
+
* ```
|
|
932
|
+
*/
|
|
933
|
+
exports.utf8 = (() => {
|
|
934
|
+
let _utf8Encoder;
|
|
935
|
+
let _utf8Decoder;
|
|
936
|
+
const utf8Builtin = {
|
|
937
|
+
// ignoreBOM preserves an explicit leading U+FEFF;
|
|
938
|
+
// fatal rejects invalid UTF-8 bytes instead of replacing them.
|
|
939
|
+
encode(data) {
|
|
940
|
+
abytes(data);
|
|
941
|
+
return (_utf8Decoder || (_utf8Decoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }))).decode(data);
|
|
942
|
+
},
|
|
943
|
+
decode(str) {
|
|
944
|
+
astr('utf8', str);
|
|
945
|
+
if (!_isWellFormed(str))
|
|
946
|
+
throw new TypeError('utf8 expected well-formed string');
|
|
947
|
+
return (_utf8Encoder || (_utf8Encoder = new TextEncoder())).encode(str);
|
|
948
|
+
},
|
|
949
|
+
};
|
|
950
|
+
return Object.freeze({
|
|
951
|
+
// Select each direction once at module init, since
|
|
952
|
+
// TextEncoder and TextDecoder can exist independently.
|
|
953
|
+
encode: typeof TextDecoder === 'function' ? utf8Builtin.encode : utf8Fallback.encode,
|
|
954
|
+
decode: typeof TextEncoder === 'function' ? utf8Builtin.decode : utf8Fallback.decode,
|
|
955
|
+
});
|
|
956
|
+
})();
|
|
957
|
+
// Keep fallback parity probes behind a test-only export until runtime fallback behavior is decided.
|
|
958
|
+
exports.__TESTS = Object.freeze({
|
|
959
|
+
utf8Fallback: utf8Fallback,
|
|
960
|
+
_isWellFormedShim: _isWellFormedShim,
|
|
961
|
+
});
|
|
962
|
+
// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
|
|
963
|
+
// prettier-ignore
|
|
964
|
+
const hasHexBuiltin = /* @__PURE__ */ (() =>
|
|
965
|
+
// Require both directions before enabling the native hex path so encode/decode stay symmetric.
|
|
966
|
+
typeof Uint8Array.from([]).toHex === 'function' &&
|
|
967
|
+
typeof Uint8Array.fromHex === 'function')();
|
|
968
|
+
// prettier-ignore
|
|
969
|
+
const hexBuiltin = {
|
|
970
|
+
// Keep local type guards so the native path preserves library-level input errors.
|
|
971
|
+
// Native toHex emits lowercase hex, matching the fallback alphabet and Node's hex strings.
|
|
972
|
+
encode(data) { abytes(data); return data.toHex(); },
|
|
973
|
+
// Native fromHex accepts either hex case and rejects odd-length / non-hex syntax.
|
|
974
|
+
decode(s) { astr('hex', s); return Uint8Array.fromHex(s); },
|
|
975
|
+
};
|
|
976
|
+
/**
|
|
977
|
+
* hex string decoder. Uses built-in function, when available.
|
|
978
|
+
* Lowercase codec; unlike `base16`, this variant accepts either hex case and emits lowercase.
|
|
979
|
+
* @example
|
|
980
|
+
* ```js
|
|
981
|
+
* const b = hex.decode("0102ff"); // => new Uint8Array([ 1, 2, 255 ])
|
|
982
|
+
* const str = hex.encode(b); // "0102ff"
|
|
983
|
+
* ```
|
|
984
|
+
*/
|
|
985
|
+
exports.hex = Object.freeze(hasHexBuiltin
|
|
986
|
+
? hexBuiltin
|
|
987
|
+
: chain(radix2(4), alphabet('0123456789abcdef'), join(''), normalize((s) => {
|
|
988
|
+
if (typeof s !== 'string' || s.length % 2 !== 0)
|
|
989
|
+
throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`);
|
|
990
|
+
return s.toLowerCase();
|
|
991
|
+
})));
|
|
992
|
+
// prettier-ignore
|
|
993
|
+
// Keep this registry aligned with CoderType/coderTypeError; only byte<->string codecs belong here.
|
|
994
|
+
const CODERS = {
|
|
995
|
+
utf8: exports.utf8, hex: exports.hex, base16: exports.base16, base32: exports.base32, base64: exports.base64, base64url: exports.base64url, base58: exports.base58, base58xmr: exports.base58xmr
|
|
996
|
+
};
|
|
997
|
+
const coderTypeError = 'Invalid encoding type. Available types: utf8, hex, base16, base32, base64, base64url, base58, base58xmr';
|
|
998
|
+
/**
|
|
999
|
+
* Encodes bytes with one of the built-in codecs.
|
|
1000
|
+
* @deprecated Use the codec directly, for example `hex.encode(bytes)`.
|
|
1001
|
+
* @param type - Codec name.
|
|
1002
|
+
* @param bytes - Bytes to encode.
|
|
1003
|
+
* @returns Encoded string.
|
|
1004
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
1005
|
+
* @example
|
|
1006
|
+
* ```ts
|
|
1007
|
+
* bytesToString('hex', Uint8Array.from([1, 2, 255]));
|
|
1008
|
+
* ```
|
|
1009
|
+
*/
|
|
1010
|
+
const bytesToString = (type, bytes) => {
|
|
1011
|
+
if (typeof type !== 'string' || !CODERS.hasOwnProperty(type))
|
|
1012
|
+
throw new TypeError(coderTypeError);
|
|
1013
|
+
if (!isBytes(bytes))
|
|
1014
|
+
throw new TypeError('bytesToString() expects Uint8Array');
|
|
1015
|
+
return CODERS[type].encode(bytes);
|
|
1016
|
+
};
|
|
1017
|
+
exports.bytesToString = bytesToString;
|
|
1018
|
+
/**
|
|
1019
|
+
* Alias for `bytesToString`.
|
|
1020
|
+
* @deprecated Use {@link bytesToString} or the codec directly instead.
|
|
1021
|
+
* @param type - Codec name.
|
|
1022
|
+
* @param bytes - Bytes to encode.
|
|
1023
|
+
* @returns Encoded string.
|
|
1024
|
+
* @example
|
|
1025
|
+
* ```ts
|
|
1026
|
+
* str('hex', Uint8Array.from([1, 2, 255]));
|
|
1027
|
+
* ```
|
|
1028
|
+
*/
|
|
1029
|
+
exports.str = exports.bytesToString; // as in python, but for bytes only
|
|
1030
|
+
/**
|
|
1031
|
+
* Decodes a string with one of the built-in codecs.
|
|
1032
|
+
* @deprecated Use the codec directly, for example `hex.decode(text)`.
|
|
1033
|
+
* @param type - Codec name.
|
|
1034
|
+
* @param str - Encoded string.
|
|
1035
|
+
* @returns Decoded bytes.
|
|
1036
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
1037
|
+
* @example
|
|
1038
|
+
* ```ts
|
|
1039
|
+
* stringToBytes('hex', '0102ff');
|
|
1040
|
+
* ```
|
|
1041
|
+
*/
|
|
1042
|
+
const stringToBytes = (type, str) => {
|
|
1043
|
+
// Match bytesToString's selector validation so hostile `toString()` coercions can't leak custom errors.
|
|
1044
|
+
if (typeof type !== 'string' || !CODERS.hasOwnProperty(type))
|
|
1045
|
+
throw new TypeError(coderTypeError);
|
|
1046
|
+
if (typeof str !== 'string')
|
|
1047
|
+
throw new TypeError('stringToBytes() expects string');
|
|
1048
|
+
return CODERS[type].decode(str);
|
|
1049
|
+
};
|
|
1050
|
+
exports.stringToBytes = stringToBytes;
|
|
1051
|
+
/**
|
|
1052
|
+
* Alias for `stringToBytes`.
|
|
1053
|
+
* @deprecated Use {@link stringToBytes} or the codec directly instead.
|
|
1054
|
+
* @param type - Codec name.
|
|
1055
|
+
* @param str - Encoded string.
|
|
1056
|
+
* @returns Decoded bytes.
|
|
1057
|
+
* @example
|
|
1058
|
+
* ```ts
|
|
1059
|
+
* bytes('hex', '0102ff');
|
|
1060
|
+
* ```
|
|
1061
|
+
*/
|
|
1062
|
+
exports.bytes = exports.stringToBytes;
|