import { sha256 } from "js-sha256"; import BigNumber from "bignumber.js"; var bigint = require('big-integer'); const CHARSET_RS = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ' const glog = [ 0, 0, 1, 18, 2, 5, 19, 11, 3, 29, 6, 27, 20, 8, 12, 23, 4, 10, 30, 17, 7, 22, 28, 26, 21, 25, 9, 16, 13, 14, 24, 15 ]; const gexp = [ 1, 2, 4, 8, 16, 5, 10, 20, 13, 26, 17, 7, 14, 28, 29, 31, 27, 19, 3, 6, 12, 24, 21, 15, 30, 25, 23, 11, 22, 9, 18, 1 ]; const CHARSET_RS_BYTE = [0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x4a, 0x4B, 0x4C, 0x4D, 0x4E, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a] export function verifyAddressHelper(address: string): boolean{ if(address.length == 26 && address.startsWith('ARDOR-')){ let data = address.split('-'); data.shift(); if(data.length != 4) return false; for(let value of data){ for(let char of value){ if(!CHARSET_RS.includes(char)) return false; } } return true; } return false; } export function getaccountIdHelper(publicKey: Buffer) : string{ let hash = Sha256(publicKey); hash = hash.slice(0,8).reverse(); return new BigNumber(hash.toString("hex"), 16).toFixed(0); } export function encodeAddressHelper(publicKey: Buffer): string{ let accountId = getaccountIdHelper(publicKey); let encodedBuffer = rsEncode(new BigNumber(accountId)); return "ARDOR-" + encodedBuffer.toString("ascii"); } //#region reed solomon const codeword_map = [3, 2, 1, 0, 7, 6, 5, 4, 13, 14, 15, 16, 12, 8, 9, 10, 11] export function rsEncode(value: BigNumber) : Buffer{ // Initializes output to 0's... let auxBuff = []; let encBuff = Buffer.alloc(20); // Spread 64-bit input in 5-bits groups... for(let k = 0; k< 13; k++){ auxBuff[k] = Number(bigint(shiftRight(value.toString(2), 5*k).toString()).and(bigint(0x1F))) } // Computes parity bytes... let fb = 0; for(let i = 12; i>=0; i--){ fb = auxBuff[i] ^ auxBuff[16]; auxBuff[16] = auxBuff[15] ^ gmult(30, fb); auxBuff[15] = auxBuff[14] ^ gmult(6, fb); auxBuff[14] = auxBuff[13] ^ gmult(9, fb); auxBuff[13] = gmult(17, fb); } // Encode plain+parity array... for(let i = 0, nIdx = 0; i<17; i++, nIdx++){ if(i == 4 || i == 8 || i == 12){ encBuff[nIdx++] = 0x2d; } encBuff[nIdx] = CHARSET_RS_BYTE[auxBuff[codeword_map[i]]]; } return Buffer.from(encBuff); } function shiftRight(toShift: string, steps: number){ //For some reason right shifting fails sometimes, so this is a quick fix. if(toShift.length % 2 != 0){ toShift = "0" + toShift; } for(let i = 0; i< steps; i++){ toShift = toShift.slice(0, toShift.length-1); toShift = "00" + toShift; } return new BigNumber(toShift, 2); } function gmult(a: number, b: number): number{ if(a==0 || b == 0) return 0; return gexp[(glog[a] + glog[b]) % 31]; } //#endregion const Sha256 = (msg: Buffer) => Buffer.from(sha256(msg), 'hex')