Search code examples
soliditytronsigner

how to get correct address using ecrecover in tron


The code block of getting signer address via ecrecover in solidity contract code is working well with Ethereum but in TRON it is returning wrong address My contract side code is

    function validate(string memory strTest,uint8 v, bytes32 r, bytes32 s) public view returns(address){
      bytes32 prefixedHash = keccak256(strTest);
      return ecrecover(keccak256(prefixedHash),v,r,s);
      // return ecrecover(prefixedHash,v,r,s):
   }

and dapp side code is

    msg = tronWeb.sha3("this is test string");
    var signature = await tronWeb.trx.sign(msg);
    var r=signature.substr(0,66);
    var s= "0x" + signature.substr(66,64);
    var v="0x" + signature.substr(signature.length-2);
    retValue = await thisContractInstance.validate("this is test string",v,r,s).call();

but in both cases ( one case is commented in contract side code) getting wrong signer address in TRON shasta network


Solution

  • Taken from here:

    The smart contract code:

    contract Verifier {
        function recoverAddr(bytes32 msgHash, uint8 v, bytes32 r, bytes32 s) returns (address) {
            return ecrecover(msgHash, v, r, s);
        }
    
        function isSigned(address _addr, bytes32 msgHash, uint8 v, bytes32 r, bytes32 s) returns (bool) {
            return ecrecover(msgHash, v, r, s) == _addr;
        }
    }
    

    The client code:

    const ethers = tronWeb.utils.ethersUtils;
    let contract = await tronWeb.contract().at(contract_address);
    let signingKey = new ethers.SigningKey(tronWeb.defaultPrivateKey);
    
    let message = "This is some message";
    let messageBytes = ethers.toUtf8Bytes(message);
    let messageDigest = ethers.keccak256(messageBytes);
    
    let signature = signingKey.signDigest(messageDigest);
    let hexAddress = await contract.recoverAddr(messageDigest, signature.v, signature.r, signature.s).call();