Created
January 17, 2023 08:17
-
-
Save nikita-mityagin/a2d0a4685654289ed4b23e7c292217c0 to your computer and use it in GitHub Desktop.
Tron blockchain base58 address validation Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import bs58 from "bs58"; | |
import jssha from "jssha"; | |
const sha256 = str => { | |
const inst = new jssha("SHA-256", "HEX"); | |
inst.update(str); | |
return inst.getHash("HEX"); | |
}; | |
/** | |
* Validates tron address | |
* | |
* @param addressBase58Check {string} tron address in base58check format (starting with T) | |
* @returns {boolean} true if given param is valid tron address and false otherwise | |
*/ | |
export function validateTronAddress(addressBase58Check) { | |
try { | |
if (typeof addressBase58Check !== "string" || addressBase58Check.length !== 34) return false; | |
const bytes = Buffer.from(bs58.decode(addressBase58Check)); | |
const checkSum = bytes.subarray(bytes.length - 4).toString("hex"); | |
const addressWithoutCheckSum = bytes.subarray(0, bytes.length - 4).toString("hex"); | |
const doubleHash = sha256(sha256(addressWithoutCheckSum)); | |
const expectedCheckSum = doubleHash.slice(0, 8); | |
return expectedCheckSum === checkSum; | |
} catch (e) { | |
console.log("Failed to validate tron address, treating as the address is wrong"); | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment