Created
February 27, 2024 16:13
-
-
Save ZigBalthazar/a732440a5a366871bb2ebae3684f2f9d to your computer and use it in GitHub Desktop.
solidity-eip712-verify
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pragma solidity ^0.7.6; | |
pragma abicoder v2; | |
import "openzeppelin-solidity/contracts/cryptography/ECDSA.sol"; | |
contract Authentication { | |
using ECDSA for bytes32; | |
string public constant name = "EIP712Authentication"; | |
string public constant version = "1.0.0"; | |
struct EIP712Domain { | |
string name; | |
string version; | |
} | |
string private constant EIP712_DOMAIN_TYPE = | |
"EIP712Domain(string name,string version)"; | |
bytes32 public constant EIP712_DOMAIN_TYPEHASH = | |
keccak256(abi.encodePacked(EIP712_DOMAIN_TYPE)); | |
struct Auth { | |
string nick; | |
} | |
string private constant AUTH_TYPE = "Auth(string nick)"; | |
bytes32 public constant AUTH_TYPEHASH =keccak256(abi.encodePacked(AUTH_TYPE)); | |
bytes32 DOMAIN_SEPARATOR; | |
constructor() public { | |
DOMAIN_SEPARATOR = hashDomain( | |
EIP712Domain({name: name, version: version}) | |
); | |
} | |
function hashDomain(EIP712Domain memory eip712Domain) | |
internal | |
pure | |
returns (bytes32) | |
{ | |
return | |
keccak256( | |
abi.encode( | |
EIP712_DOMAIN_TYPEHASH, | |
keccak256(bytes(eip712Domain.name)), | |
keccak256(bytes(eip712Domain.version)) | |
) | |
); | |
} | |
function hash(Auth memory auth) internal pure returns (bytes32) { | |
return keccak256(abi.encode( | |
AUTH_TYPEHASH, | |
keccak256(bytes(auth.nick))) | |
); | |
} | |
function verify(Auth memory auth, uint8 v, bytes32 r, bytes32 s) public view returns (address) { | |
bytes32 digest = keccak256(abi.encodePacked( | |
"\x19\x01", | |
DOMAIN_SEPARATOR, | |
hash(auth) | |
)); | |
return ecrecover(digest, v, r, s); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment