const leb = require('leb128') import {blake2bFinal, blake2bInit, blake2bUpdate} from "blakejs" import { decodeBase32 } from "./Encoder"; export function DecodeAddress(address: string): Buffer{ let payload; let checksum; let protocol = address[1]; switch(Number(protocol)){ case 0: //ID protocol if(address.length > 18){ throw Error("Invalid address"); } return Buffer.concat([ Buffer.from([Number(protocol)]), Buffer.from(leb.unsigned.encode(address.substr(2))), ]); case 1: //Secp256k1 protocol let addressDecoded = decodeBase32(address.slice(2).toUpperCase()); payload = addressDecoded.slice(0, -4); checksum = Buffer.from(addressDecoded.slice(-4)); if (payload.byteLength !== 20) { throw new Error("Invalid payload length"); } break; case 2: //Actor protocol let addressDecodedA = decodeBase32(address.slice(2).toUpperCase()); payload = addressDecodedA.slice(0, -4); checksum = Buffer.from(addressDecodedA.slice(-4)); if (payload.byteLength !== 20) { throw new Error("Invalid payload length"); } break; default: throw Error("Address type not supported"); } let bytesAddress = Buffer.concat([Buffer.from([Number(protocol)]), Buffer.from(payload)]); if (getChecksum(bytesAddress).toString("hex") !== checksum.toString("hex")) { throw new Error("Invalid checksum"); } return bytesAddress; } export function verifyAddressHelper(address: string): boolean{ try{ let addr = DecodeAddress(address); return true; }catch(Error){ return false } } function getChecksum(payload: Buffer) { const blakeCtx = blake2bInit(4); blake2bUpdate(blakeCtx, payload); return Buffer.from(blake2bFinal(blakeCtx)); }