ECRecovery.sol 1.9 KB

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