@ordinalsbot/bitcoin-fee-estimator
Version:
A library for calculating Bitcoin transaction fees
46 lines (34 loc) • 1.22 kB
text/typescript
import { createHash } from "crypto";
const BASE58_ALPHABET =
"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
export function bs58Decode(input: string): number[] {
const result: number[] = [];
let leadingZeros = 0;
for (let i = 0; i < input.length && input[i] === "1"; i++) {
leadingZeros++;
}
let value = BigInt(0);
for (let i = leadingZeros; i < input.length; i++) {
const c = input[i];
const index = BASE58_ALPHABET.indexOf(c);
if (index === -1) throw new Error("Invalid Base58 character");
value = value * BigInt(58) + BigInt(index);
}
while (value > 0) {
result.unshift(Number(value % BigInt(256)));
value = value / BigInt(256);
}
for (let i = 0; i < leadingZeros; i++) {
result.unshift(0);
}
if (result.length < 4) throw new Error("Invalid checksum");
const payload = result.slice(0, -4);
const checksum = result.slice(-4);
const hash1 = createHash("sha256").update(Buffer.from(payload)).digest();
const hash2 = createHash("sha256").update(hash1).digest();
const expectedChecksum = hash2.subarray(0, 4);
if (!Buffer.from(checksum).equals(expectedChecksum)) {
throw new Error("Invalid checksum");
}
return payload;
}