ECDSA.sol 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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 ECDSA {
  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 signature bytes signature, the signature is generated using web3.eth.sign()
  13. */
  14. function recover(bytes32 hash, bytes signature) internal pure returns (address) {
  15. bytes32 r;
  16. bytes32 s;
  17. uint8 v;
  18. // Check the signature length
  19. if (signature.length != 65) {
  20. return (address(0));
  21. }
  22. // Divide the signature in r, s and v variables
  23. // ecrecover takes the signature parameters, and the only way to get them
  24. // currently is to use assembly.
  25. // solium-disable-next-line security/no-inline-assembly
  26. assembly {
  27. r := mload(add(signature, 0x20))
  28. s := mload(add(signature, 0x40))
  29. v := byte(0, mload(add(signature, 0x60)))
  30. }
  31. // Version of signature should be 27 or 28, but 0 and 1 are also possible versions
  32. if (v < 27) {
  33. v += 27;
  34. }
  35. // If the version is correct return the signer address
  36. if (v != 27 && v != 28) {
  37. return (address(0));
  38. } else {
  39. // solium-disable-next-line arg-overflow
  40. return ecrecover(hash, v, r, s);
  41. }
  42. }
  43. /**
  44. * toEthSignedMessageHash
  45. * @dev prefix a bytes32 value with "\x19Ethereum Signed Message:"
  46. * and hash the result
  47. */
  48. function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
  49. // 32 is the length in bytes of hash,
  50. // enforced by the type signature above
  51. return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
  52. }
  53. }