ethers.js/src.ts/utils/base58.ts

65 lines
1.8 KiB
TypeScript
Raw Normal View History

2022-11-28 05:50:34 +03: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.
*
* @_subsection: api/utils:Base58 Encoding [base58]
*/
2022-09-05 23:14:43 +03:00
import { getBytes } from "./data.js";
import { assertArgument } from "./errors.js";
2022-11-28 05:50:34 +03:00
import { toBigInt } from "./maths.js";
2022-09-05 23:14:43 +03:00
import type { BytesLike } from "./index.js";
const Alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
let Lookup: null | Record<string, bigint> = null;
function getAlpha(letter: string): bigint {
if (Lookup == null) {
Lookup = { };
for (let i = 0; i < Alphabet.length; i++) {
Lookup[Alphabet[i]] = BigInt(i);
}
}
const result = Lookup[letter];
assertArgument(result != null, `invalid base58 value`, "letter", letter);
2022-09-05 23:14:43 +03:00
return result;
}
const BN_0 = BigInt(0);
const BN_58 = BigInt(58);
/**
2022-11-28 05:50:34 +03:00
* Encode %%value%% as a Base58-encoded string.
2022-09-05 23:14:43 +03:00
*/
export function encodeBase58(_value: BytesLike): string {
let value = toBigInt(getBytes(_value));
2022-09-05 23:14:43 +03:00
let result = "";
while (value) {
result = Alphabet[Number(value % BN_58)] + result;
value /= BN_58;
}
return result;
}
/**
* Decode the Base58-encoded %%value%%.
*/
2022-11-28 05:50:34 +03:00
export function decodeBase58(value: string): bigint {
2022-09-05 23:14:43 +03:00
let result = BN_0;
for (let i = 0; i < value.length; i++) {
result *= BN_58;
result += getAlpha(value[i]);
}
2022-11-28 05:50:34 +03:00
return result;
2022-09-05 23:14:43 +03:00
}