[openzeppelin]:v4.8.3,[forge-std]:v1.5.6
Github: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.8.3/contracts/utils/cryptography/EIP712.sol
EIP-712是一个专门用于对结构化数据求hash值以及签名的标准,主要解决了数据“链下签名+链上验证”并提高了链上消息签名的可用性。EIP712合约提供了EIP 712 domain separator的定义与获取——是结构化数据完整编码的一部分。
EIP712中对domain separator的实现支持动态更新链chain id,这样可防止由链硬分叉而引起的重放攻击。并且本库实现的整体编码规则为v4版本,匹配Metamask中的JSON RPC方法 ——eth_signTypedDataV4
。细节参见:https://docs.metamask.io/guide/signing-data.html
注:EIP-712细节参见:https://eips.ethereum.org/EIPS/eip-712
继承EIP712合约成为一个可调用合约:
Github: https://github.com/RevelationOfTuring/foundry-openzeppelin-contracts/blob/master/src/utils/cryptography/MockEIP712.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import "openzeppelin-contracts/contracts/utils/cryptography/EIP712.sol";
import "openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol";
contract MockEIP712 is EIP712 {
using ECDSA for bytes32;
constructor(string memory name, string memory version) EIP712(name, version) {}
function verify(
string memory name,
uint salary,
address personalAddress,
address signer,
bytes memory signature
) external view {
// hashing the typed data
bytes32 structHash = keccak256(
abi.encode(
keccak256("NameCard(string name,uint256 salary,address personalAddress)"),
keccak256(bytes(name)),
salary,
personalAddress
)
);
// build fully encoded EIP712 message for this domain
bytes32 digest = _hashTypedDataV4(structHash);
// signature verification
require(signer == digest.recover(signature), "invalid signature");
}
function getDomainSeparator() external view returns (bytes32) {
return _domainSeparatorV4();
}
}
全部foundry测试合约:
Github: https://github.com/RevelationOfTuring/foundry-openzeppelin-contracts/blob/master/test/utils/cryptography/EIP712.t.sol
测试数据:
Github: https://github.com/RevelationOfTuring/foundry-openzeppelin-contracts/blob/master/test/utils/cryptography/data/EIP712_test.json
测试数据的生成脚本:
Github: https://github.com/RevelationOfTuring/foundry-openzeppelin-contracts/blob/master/test/utils/cryptography/EIP712_test.ts
import {ethers} from 'ethers'
import type {TypedDataDomain} from 'ethers'
import {writeFileSync} from 'fs'
const domain: TypedDataDomain = {
name: 'mock name',
version: '1',
chainId: 1024,
verifyingContract: '0xfc1a36B3eF056c2eC89FdeB4251e90F7935F1b51'
}
const types = {
'NameCard': [
{'name': 'name', 'type': 'string'},
{'name': 'salary', 'type': 'uint256'},
{'name': 'personalAddress', 'type': 'address'},
]
}
// typed data
const value = {
name: 'Michael.W',
salary: 1024,
personalAddress: '0x0000000000000000000000000000000000000400',
}
async function main() {
const domainSeparator = ethers.TypedDataEncoder.hashDomain(domain)
const wallet = new ethers.Wallet(ethers.toBeHex(1024, 32))
const signature = await wallet.signTypedData(domain, types, value)
// generate domain separator with chain id changed
domain.chainId = 2048
const domainSeparatorWithChainIdChanged = ethers.TypedDataEncoder.hashDomain(domain)
const output = {
domain_separator: domainSeparator,
domain_separator_with_chain_id_changed: domainSeparatorWithChainIdChanged,
value,
signature,
signer_address: wallet.address
}
writeFileSync('test/utils/cryptography/data/EIP712_test.json', JSON.stringify(output))
}
main().catch((error) => {
console.error(error)
process.exitCode = 1
})
constructor函数中初始化了domain separator以及将一些相关的参数cached到immutable常量中。
传参:
name:签名域EIP712Domain中的一个成员变量,为用户可读的name。通常传入DApp或协议的名字;
version:签名域EIP712Domain中的一个成员变量,为当前签名域EIP712Domain的主版本号。
签名域EIP712Domain的具体说明参见:https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator
注:constructor中将参数初始化到immutable常量,后续无法修改,除非依靠合约升级。
// 将domain separator cache到一个immutable常量中,这样会减少每次使用domain separator的gas消耗
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
// 将当前的chain id也cache到一个immutable常量中,这样做的目的是:以后一旦该链的chain id改变,_CACHED_DOMAIN_SEPARATOR理应作废。而_CACHED_CHAIN_ID则用于判断chain id是否改变
uint256 private immutable _CACHED_CHAIN_ID;
// 将本合约地址cache到一个immutable常量中
address private immutable _CACHED_THIS;
// 将name的hash值cache到一个immutable常量中
bytes32 private immutable _HASHED_NAME;
// 将version的hash值cache到一个immutable常量中
bytes32 private immutable _HASHED_VERSION;
// 将EIP712Domain的hash值cache到一个immutable常量中
bytes32 private immutable _TYPE_HASH;
constructor(string memory name, string memory version) {
// 计算name的hash值
bytes32 hashedName = keccak256(bytes(name));
// 计算version的hash值
bytes32 hashedVersion = keccak256(bytes(version));
// 计算签名域EIP712Domain的type hash
bytes32 typeHash = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
// 将name的hash值cache到_HASHED_NAME中
_HASHED_NAME = hashedName;
// 将version的hash值cache到_HASHED_VERSION中
_HASHED_VERSION = hashedVersion;
// 将当前的链chain id cache到_CACHED_CHAIN_ID
_CACHED_CHAIN_ID = block.chainid;
// 计算domain separator并cache到_CACHED_DOMAIN_SEPARATOR
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
// 将本合约地址cache到_CACHED_THIS
_CACHED_THIS = address(this);
// 将签名域EIP712Domain的type hash cache到_TYPE_HASH
_TYPE_HASH = typeHash;
}
// 计算domain separator
// 输入参数为:
// typeHash:签名域EIP712Domain的type hash;
// nameHash:签名域EIP712Domain中成员变量name的hash值;
// versionHash:签名域EIP712Domain中成员变量version的hash值
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
// 连接type hash + name hash + version hash + 当前链的chain id + 本合约地址,并取hash值返回
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
获取针对于当前链的domain separator
function _domainSeparatorV4() internal view returns (bytes32) {
if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) {
// 如果当前合约地址和当前链chain id都与之前cached的值一样,直接返回cached的domain separator值
return _CACHED_DOMAIN_SEPARATOR;
} else {
// 否则表明domain separator照比原来cached已经发生改变(chain id或verifying contract地址变了),利用_TYPE_HASH、 _HASHED_NAME和_HASHED_VERSION重新计算domain separator并返回
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
foundry代码验证
contract EIP712Test is Test {
using stdJson for string;
// fix the contract address with salt 'Michael.W'
MockEIP712 me = new MockEIP712{salt : 'Michael.W'}("mock name", "1");
string jsonTestData = vm.readFile("test/utils/cryptography/data/EIP712_test.json");
function setUp() external {
// fix chain id to 1024
vm.chainId(1024);
}
function test_DomainSeparator() external {
// case 1: right domain separator
bytes32 expectedDomainSeparator = jsonTestData.readBytes32(".domain_separator");
assertEq(expectedDomainSeparator, me.getDomainSeparator());
// case 2: domain separator changed with the chain id
vm.chainId(2048);
expectedDomainSeparator = jsonTestData.readBytes32(".domain_separator_with_chain_id_changed");
assertEq(expectedDomainSeparator, me.getDomainSeparator());
}
}
返回基于本domain的结构化数据的完整EIP712的编码信息。该编码信息往往用作对结构化数据签名的摘要。
structHash为具体的结构化数据的hash值,具体说明参见:https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
// 使用ECDSA库中的toTypedDataHash方法,传入本domain separator以及结构化数据的hash计算整个摘要并返回
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
foundry代码验证
contract EIP712Test is Test {
using stdJson for string;
// fix the contract address with salt 'Michael.W'
MockEIP712 me = new MockEIP712{salt : 'Michael.W'}("mock name", "1");
string jsonTestData = vm.readFile("test/utils/cryptography/data/EIP712_test.json");
function setUp() external {
// fix chain id to 1024
vm.chainId(1024);
}
// typed data
struct NameCard {
string name;
uint salary;
address personAddress;
}
function test_Verify() external {
// case 1: pass verify
bytes memory signature = jsonTestData.readBytes(".signature");
address signerAddress = jsonTestData.readAddress(".signer_address");
bytes memory encodedBytes = jsonTestData.parseRaw(".value");
NameCard memory nameCard = abi.decode(encodedBytes, (NameCard));
me.verify(
nameCard.name,
nameCard.salary,
nameCard.personAddress,
signerAddress,
signature
);
// case 2: fail to pass verify with value changed
vm.expectRevert("invalid signature");
me.verify(
nameCard.name,
nameCard.salary + 1,
nameCard.personAddress,
signerAddress,
signature
);
}
}
ps:
本人热爱图灵,热爱中本聪,热爱V神。
以下是我个人的公众号,如果有技术问题可以关注我的公众号来跟我交流。
同时我也会在这个公众号上每周更新我的原创文章,喜欢的小伙伴或者老伙计可以支持一下!
如果需要转发,麻烦注明作者。十分感谢!
公众号名称:后现代泼痞浪漫主义奠基人