2022-11-30 15:44:23 -05:00
|
|
|
/**
|
|
|
|
* The [Base58 Encoding](link-base58) scheme allows a **numeric** value
|
|
|
|
* to be encoded as a compact string using a radix of 58 using only
|
|
|
|
* alpha-numeric characters. Confusingly similar characters are omitted
|
|
|
|
* (i.e. ``"l0O"``).
|
|
|
|
*
|
|
|
|
* Note that Base58 encodes a **numeric** value, not arbitrary bytes,
|
|
|
|
* since any zero-bytes on the left would get removed. To mitigate this
|
|
|
|
* issue most schemes that use Base58 choose specific high-order values
|
|
|
|
* to ensure non-zero prefixes.
|
|
|
|
*
|
2022-12-02 21:27:06 -05:00
|
|
|
* @_subsection: api/utils:Base58 Encoding [about-base58]
|
2022-11-30 15:44:23 -05:00
|
|
|
*/
|
2022-09-15 22:58:45 -04:00
|
|
|
import { getBytes } from "./data.js";
|
2022-11-09 02:57:02 -05:00
|
|
|
import { assertArgument } from "./errors.js";
|
2022-11-30 15:44:23 -05:00
|
|
|
import { toBigInt } from "./maths.js";
|
2022-09-05 16:57:11 -04:00
|
|
|
const Alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
|
|
|
|
let Lookup = null;
|
|
|
|
function getAlpha(letter) {
|
|
|
|
if (Lookup == null) {
|
|
|
|
Lookup = {};
|
|
|
|
for (let i = 0; i < Alphabet.length; i++) {
|
|
|
|
Lookup[Alphabet[i]] = BigInt(i);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
const result = Lookup[letter];
|
2022-11-09 02:57:02 -05:00
|
|
|
assertArgument(result != null, `invalid base58 value`, "letter", letter);
|
2022-09-05 16:57:11 -04:00
|
|
|
return result;
|
|
|
|
}
|
|
|
|
const BN_0 = BigInt(0);
|
|
|
|
const BN_58 = BigInt(58);
|
|
|
|
/**
|
2022-11-30 15:44:23 -05:00
|
|
|
* Encode %%value%% as a Base58-encoded string.
|
2022-09-05 16:57:11 -04:00
|
|
|
*/
|
|
|
|
export function encodeBase58(_value) {
|
2024-01-02 19:12:56 -05:00
|
|
|
const bytes = getBytes(_value);
|
|
|
|
let value = toBigInt(bytes);
|
2022-09-05 16:57:11 -04:00
|
|
|
let result = "";
|
|
|
|
while (value) {
|
|
|
|
result = Alphabet[Number(value % BN_58)] + result;
|
|
|
|
value /= BN_58;
|
|
|
|
}
|
2024-01-02 19:12:56 -05:00
|
|
|
// Account for leading padding zeros
|
|
|
|
for (let i = 0; i < bytes.length; i++) {
|
|
|
|
if (bytes[i]) {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
result = Alphabet[0] + result;
|
|
|
|
}
|
2022-09-05 16:57:11 -04:00
|
|
|
return result;
|
|
|
|
}
|
|
|
|
/**
|
|
|
|
* Decode the Base58-encoded %%value%%.
|
|
|
|
*/
|
|
|
|
export function decodeBase58(value) {
|
|
|
|
let result = BN_0;
|
|
|
|
for (let i = 0; i < value.length; i++) {
|
|
|
|
result *= BN_58;
|
|
|
|
result += getAlpha(value[i]);
|
|
|
|
}
|
2022-11-30 15:44:23 -05:00
|
|
|
return result;
|
2022-09-05 16:57:11 -04:00
|
|
|
}
|
|
|
|
//# sourceMappingURL=base58.js.map
|