ECRecovery.sol 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. pragma solidity ^0.4.11;
  2. /**
  3. * @title Eliptic curve signature operations
  4. *
  5. * @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d
  6. */
  7. library ECRecovery {
  8. /**
  9. * @dev Recover signer address from a message by using his signature
  10. * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address.
  11. * @param sig bytes signature, the signature is generated using web3.eth.sign()
  12. */
  13. function recover(bytes32 hash, bytes sig) constant returns (address) {
  14. bytes32 r;
  15. bytes32 s;
  16. uint8 v;
  17. //Check the signature length
  18. if (sig.length != 65) {
  19. return (address(0));
  20. }
  21. // Divide the signature in r, s and v variables
  22. assembly {
  23. r := mload(add(sig, 32))
  24. s := mload(add(sig, 64))
  25. v := byte(0, mload(add(sig, 96)))
  26. }
  27. // Version of signature should be 27 or 28, but 0 and 1 are also possible versions
  28. if (v < 27) {
  29. v += 27;
  30. }
  31. // If the version is correct return the signer address
  32. if (v != 27 && v != 28) {
  33. return (address(0));
  34. } else {
  35. return ecrecover(hash, v, r, s);
  36. }
  37. }
  38. }