ECRecovery.sol 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. pragma solidity ^0.4.21;
  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) internal pure returns (address) {
  18. bytes32 r;
  19. bytes32 s;
  20. uint8 v;
  21. //Check the signature length
  22. if (sig.length != 65) {
  23. return (address(0));
  24. }
  25. // Divide the signature in r, s and v variables
  26. // ecrecover takes the signature parameters, and the only way to get them
  27. // currently is to use assembly.
  28. // solium-disable-next-line security/no-inline-assembly
  29. assembly {
  30. r := mload(add(sig, 32))
  31. s := mload(add(sig, 64))
  32. v := byte(0, mload(add(sig, 96)))
  33. }
  34. // Version of signature should be 27 or 28, but 0 and 1 are also possible versions
  35. if (v < 27) {
  36. v += 27;
  37. }
  38. // If the version is correct return the signer address
  39. if (v != 27 && v != 28) {
  40. return (address(0));
  41. } else {
  42. return ecrecover(hash, v, r, s);
  43. }
  44. }
  45. }