ECDSA.sol 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. pragma solidity ^0.5.2;
  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 memory 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. // solhint-disable-next-line 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. return ecrecover(hash, v, r, s);
  40. }
  41. }
  42. /**
  43. * toEthSignedMessageHash
  44. * @dev prefix a bytes32 value with "\x19Ethereum Signed Message:"
  45. * and hash the result
  46. */
  47. function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
  48. // 32 is the length in bytes of hash,
  49. // enforced by the type signature above
  50. return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
  51. }
  52. }