ECRecovery.sol 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. pragma solidity ^0.4.24;
  2. /**
  3. * @title Elliptic curve signature operations
  4. * @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d
  5. * TODO Remove this library once solidity supports passing a signature to ecrecover.
  6. * See https://github.com/ethereum/solidity/issues/864
  7. */
  8. library ECRecovery {
  9. /**
  10. * @dev Recover signer address from a message by using their signature
  11. * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address.
  12. * @param sig bytes signature, the signature is generated using web3.eth.sign()
  13. */
  14. function recover(bytes32 hash, bytes sig)
  15. internal
  16. pure
  17. returns (address)
  18. {
  19. bytes32 r;
  20. bytes32 s;
  21. uint8 v;
  22. // Check the signature length
  23. if (sig.length != 65) {
  24. return (address(0));
  25. }
  26. // Divide the signature in r, s and v variables
  27. // ecrecover takes the signature parameters, and the only way to get them
  28. // currently is to use assembly.
  29. // solium-disable-next-line security/no-inline-assembly
  30. assembly {
  31. r := mload(add(sig, 32))
  32. s := mload(add(sig, 64))
  33. v := byte(0, mload(add(sig, 96)))
  34. }
  35. // Version of signature should be 27 or 28, but 0 and 1 are also possible versions
  36. if (v < 27) {
  37. v += 27;
  38. }
  39. // If the version is correct return the signer address
  40. if (v != 27 && v != 28) {
  41. return (address(0));
  42. } else {
  43. // solium-disable-next-line arg-overflow
  44. return ecrecover(hash, v, r, s);
  45. }
  46. }
  47. /**
  48. * toEthSignedMessageHash
  49. * @dev prefix a bytes32 value with "\x19Ethereum Signed Message:"
  50. * and hash the result
  51. */
  52. function toEthSignedMessageHash(bytes32 hash)
  53. internal
  54. pure
  55. returns (bytes32)
  56. {
  57. // 32 is the length in bytes of hash,
  58. // enforced by the type signature above
  59. return keccak256(
  60. abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)
  61. );
  62. }
  63. }