import BigNumber from 'bignumber.js'; import { k12 } from '@noble/hashes/sha3-addons'; export function getCheckSum(data: Buffer) { let digest = k12(data); const checksum = digest.slice(0, 3); return checksum; } export function generateAddressHelper(publicKey: Buffer) { let newId = ''; for (let i = 0; i < 4; i++) { let longNUmber = new BigNumber(0); longNUmber.decimalPlaces(0); publicKey.slice(i * 8, (i + 1) * 8).forEach((val, index) => { longNUmber = longNUmber.plus(new BigNumber((val * 256 ** index).toString(2), 2)); }); for (let j = 0; j < 14; j++) { newId += String.fromCharCode(longNUmber.mod(26).plus(('A').charCodeAt(0)).toNumber()); longNUmber = longNUmber.div(26); } } // calculate checksum const checksum = getCheckSum(publicKey); // convert to int let identityBytesChecksum = (checksum[2] << 16) | (checksum[1] << 8) | checksum[0]; identityBytesChecksum = identityBytesChecksum & 0x3FFFF; for (let i = 0; i < 4; i++) { newId += String.fromCharCode(identityBytesChecksum % 26 + ('A').charCodeAt(0)); identityBytesChecksum = identityBytesChecksum / 26; } return newId; } export function verifyAddressHelper(identity) { if (!identity || identity.length != 60 || !/^[A-Z]+$/.test(identity)) // must be 60 upper case characters return false; const publicKey = publicKeyStringToBytes(identity); const idFromBytes = generateAddressHelper(Buffer.from(publicKey)); // todo: it would be enough to just check checksum bytes instead of compare complete id return identity === idFromBytes; } export function publicKeyStringToBytes(s) { const publicKeyBytes = new Uint8Array(32); const view = new DataView(publicKeyBytes.buffer, 0); for (let i = 0; i < 4; i++) { view.setBigUint64(i * 8, BigInt(0), true); for (let j = 14; j-- > 0; ) { view.setBigUint64(i * 8, view.getBigUint64(i * 8, true) * BigInt(26) + BigInt(s.charCodeAt(i * 14 + j)) - BigInt('A'.charCodeAt(0)), true); } } return publicKeyBytes; };