12345678910111213141516171819202122232425262728293031323334353637383940414243444546 |
- const Ethers = require('ethers');
- const utils = require("./utils");
- const TRX_MESSAGE_HEADER = '\x19TRON Signed Message:\n32';
- module.exports.tronVerifyMessage = function (message = false, signature = false, address) {
- if(!utils.isHex(message))
- return false;
- if(message.substr(0, 2) == '0x')
- message = message.substring(2);
- if(signature.substr(0, 2) == '0x')
- signature = signature.substr(2);
- const messageBytes = [
- ...Ethers.utils.toUtf8Bytes(TRX_MESSAGE_HEADER),
- ...utils.code.hexStr2byteArray(message)
- ];
- const messageDigest = Ethers.utils.keccak256(messageBytes);
- const recovered = Ethers.utils.recoverAddress(messageDigest, {
- recoveryParam: signature.substring(128, 130) == '1c' ? 1 : 0,
- r: '0x' + signature.substring(0, 64),
- s: '0x' + signature.substring(64, 128)
- });
- const tronAddress = '41' + recovered.substr(2);
- const base58Address = fromHex(tronAddress);
- if (base58Address == fromHex(address))
- return true;
- return false;
- };
- function fromHex(address) {
- if(!utils.isHex(address))
- return address;
- return utils.crypto.getBase58CheckAddress(
- utils.code.hexStr2byteArray(address.replace(/^0x/,'41'))
- );
- }
|