import {sha256} from 'js-sha256' const base58Chars = "rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz"; const base58M = base58Chars.split('').reduce((acc: { [k: string]: number }, x, i) => { acc[x] = i return acc }, {}) const Sha256 = (msg: string) => sha256(Buffer.from(msg, 'hex')) export function decodeBase58(data: string): Buffer{ const bytes = [0] for (let i = 0; i < data.length; i++) { const c = data[i] if (!(c in base58M)) throw new Error('Non-base58 character') for (let j = 0; j < bytes.length; j++) bytes[j] *= 58 bytes[0] += base58M[c] let carry = 0 for (let j = 0; j < bytes.length; ++j) { bytes[j] += carry carry = bytes[j] >> 8 bytes[j] &= 0xff } while (carry) { bytes.push(carry & 0xff) carry >>= 8 } } for (let i = 0; data[i] === 'r' && i < data.length - 1; i++) bytes.push(0) return verifyAndRemoveChecksum(Buffer.from(bytes.reverse())); } export function verifyBase58(data: string) : boolean { const bytes = [0] for (let i = 0; i < data.length; i++) { const c = data[i] if (!(c in base58M)) throw new Error('Non-base58 character') for (let j = 0; j < bytes.length; j++) bytes[j] *= 58 bytes[0] += base58M[c] let carry = 0 for (let j = 0; j < bytes.length; ++j) { bytes[j] += carry carry = bytes[j] >> 8 bytes[j] &= 0xff } while (carry) { bytes.push(carry & 0xff) carry >>= 8 } } for (let i = 0; data[i] === 'r' && i < data.length - 1; i++) bytes.push(0) return verifyCheck(Buffer.from(bytes.reverse())); } function verifyCheck(data:Buffer) : boolean{ let address = data.toString('hex'); const checkSum = address.substr(-8); address = address.substr(0, address.length - 8) let checkSum1 = Sha256(Sha256(address)).substr(0, 8); if(`${checkSum}` === `${checkSum1}`) return true; return false; } function verifyAndRemoveChecksum(data: Buffer): Buffer{ let address = data.toString('hex'); const checkSum = address.substr(-8); address = address.substr(0, address.length - 8) let checkSum1 = Sha256(Sha256(address)).substr(0, 8); if(`${checkSum}` === `${checkSum1}`) return hexToBytes(address); throw new Error("Invalid address"); } function hexToBytes(hex: string) : Buffer{ for (var bytes = [], c = 0; c < hex.length; c += 2) bytes.push(parseInt(hex.substr(c, 2), 16)); return Buffer.from(bytes); }