UNPKG

@ordinalsbot/bitcoin-fee-estimator

Version:

A library for calculating Bitcoin transaction fees

39 lines (38 loc) 1.41 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.bs58Decode = bs58Decode; const crypto_1 = require("crypto"); const BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; function bs58Decode(input) { const result = []; 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 = (0, crypto_1.createHash)("sha256").update(Buffer.from(payload)).digest(); const hash2 = (0, crypto_1.createHash)("sha256").update(hash1).digest(); const expectedChecksum = hash2.subarray(0, 4); if (!Buffer.from(checksum).equals(expectedChecksum)) { throw new Error("Invalid checksum"); } return payload; }