tronWeb.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. const Ethers = require('ethers');
  2. const utils = require("./utils");
  3. const TRX_MESSAGE_HEADER = '\x19TRON Signed Message:\n32';
  4. module.exports.tronVerifyMessage = function (message = false, signature = false, address) {
  5. if(!utils.isHex(message))
  6. return false;
  7. if(message.substr(0, 2) == '0x')
  8. message = message.substring(2);
  9. if(signature.substr(0, 2) == '0x')
  10. signature = signature.substr(2);
  11. const messageBytes = [
  12. ...Ethers.utils.toUtf8Bytes(TRX_MESSAGE_HEADER),
  13. ...utils.code.hexStr2byteArray(message)
  14. ];
  15. const messageDigest = Ethers.utils.keccak256(messageBytes);
  16. const recovered = Ethers.utils.recoverAddress(messageDigest, {
  17. recoveryParam: signature.substring(128, 130) == '1c' ? 1 : 0,
  18. r: '0x' + signature.substring(0, 64),
  19. s: '0x' + signature.substring(64, 128)
  20. });
  21. const tronAddress = '41' + recovered.substr(2);
  22. const base58Address = fromHex(tronAddress);
  23. if (base58Address == fromHex(address))
  24. return true;
  25. return false;
  26. };
  27. function fromHex(address) {
  28. if(!utils.isHex(address))
  29. return address;
  30. return utils.crypto.getBase58CheckAddress(
  31. utils.code.hexStr2byteArray(address.replace(/^0x/,'41'))
  32. );
  33. }