Last active
January 22, 2021 08:56
-
-
Save chochinlu/1306e633b7353a6a5e0286fb5804ae8e to your computer and use it in GitHub Desktop.
validate TRON address (簡易版)
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
const ADDRESS_SIZE = 34; | |
const ADDRESS_PREFIX_BYTE = 0x41; | |
const ALPHABET_MAP = {}; | |
const BASE = 58 | |
const ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; | |
function decode58(string) { | |
if (string.length === 0) | |
return []; | |
let i; | |
let j; | |
const bytes = [0]; | |
for (i = 0; i < string.length; i++) { | |
const c = string[i]; | |
if (!(c in ALPHABET_MAP)) | |
throw new Error('Non-base58 character'); | |
for (j = 0; j < bytes.length; j++) | |
bytes[j] *= BASE; | |
bytes[0] += ALPHABET_MAP[c]; | |
let carry = 0; | |
for (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 (i = 0; string[i] === '1' && i < string.length - 1; i++) | |
bytes.push(0); | |
return bytes.reverse(); | |
} | |
function isAddressValid(base58Str) { | |
if (typeof (base58Str) !== 'string') | |
return false; | |
if (base58Str.length !== ADDRESS_SIZE) | |
return false; | |
let address = decode58(base58Str); | |
if (address.length !== 25) | |
return false; | |
if (address[0] !== ADDRESS_PREFIX_BYTE) | |
return false; | |
return true | |
// const checkSum = address.slice(21); | |
// address = address.slice(0, 21); | |
// const hash0 = SHA256(address); | |
// const hash1 = SHA256(hash0); | |
// const checkSum1 = hash1.slice(0, 4); | |
// if (checkSum[0] == checkSum1[0] && checkSum[1] == checkSum1[1] && checkSum[2] == | |
// checkSum1[2] && checkSum[3] == checkSum1[3] | |
//) { | |
// return true | |
//} | |
//return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment