Guest User

Untitled

a guest
May 22nd, 2018
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. pragma solidity ^0.4.18;
  2.  
  3. library ECTools {
  4.  
  5. /**
  6. * @dev Recover signer address from a message by using his signature
  7. * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address.
  8. * @param sig bytes signature
  9. */
  10. function recover(bytes32 hash, bytes sig) public pure returns (address) {
  11. bytes32 r;
  12. bytes32 s;
  13. uint8 v;
  14.  
  15. //Check the signature length
  16. if (sig.length != 65) {
  17. return (address(0));
  18. }
  19.  
  20. // Divide the signature in r, s and v variables
  21. assembly {
  22. r := mload(add(sig, 32))
  23. s := mload(add(sig, 64))
  24. v := byte(0, mload(add(sig, 96)))
  25. }
  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.  
  32. // If the version is correct return the signer address
  33. if (v != 27 && v != 28) {
  34. return (address(0));
  35. } else {
  36. return ecrecover(hash, v, r, s);
  37. }
  38. }
  39.  
  40. function toEthereumSignedMessage(bytes32 _msg) public view returns (bytes32) {
  41. bytes memory prefix = "\x19Ethereum Signed Message:\n32";
  42. return keccak256(prefix, _msg);
  43. }
  44.  
  45. function prefixedRecover(bytes32 _msg, bytes sig) public view returns (address) {
  46. bytes32 ethSignedMsg = toEthereumSignedMessage(_msg);
  47. return recover(ethSignedMsg, sig);
  48. }
  49. }
  50.  
  51. contract ECToolsTest {
  52.  
  53. function recover(bytes32 _msg, bytes sig) public view returns (address) {
  54. return ECTools.prefixedRecover(_msg, sig);
  55. }
  56.  
  57. }
Add Comment
Please, Sign In to add comment