ERC-2098 · Final(最终) · ERC · 2019-03-14
ERC-2098: Compact Signature Representation
把 yParity 这 1 个比特存放在 s 恒为零的最高位中,将以太坊签名打包成 64 字节,从而在所有传递签名的场景中节省 calldata 和 gas。
它解决什么问题?
secp256k1 签名由三部分组成:r(32 字节)、s(32 字节)以及 v/yParity。yParity 只需要 1 个比特,但通常会以一个完整字节(27 或 28)发送。这样总共是 65 字节,按 32 字节字做 ABI 编码时会变成尴尬的 96 字节。
接收签名的合约(例如元交易、permit 和多签)要为 calldata 中的每一个字节付费。ERC-2098 定义了一种 64 字节的"紧凑"格式,正好是两个字。
它如何运作
这个技巧依赖两点观察:
yParity始终是 0 或 1(27/28 只是历史遗留的偏移量)。- 自 Homestead(EIP-2)起,规范签名使用"低位"
s,即不超过曲线阶的一半,因此s的最高位始终为 0。
于是把奇偶位存放在这个最高位中:
[ 256-bit r ][ 1-bit yParity | 255-bit s ] → (r, yParityAndS), often called (r, vs)
解码只需一次掩码和一次移位:s = vs & (2²⁵⁵ − 1),yParity = vs >> 255。由于紧凑格式是包含两个字段的 64 字节,不会与包含三个字段的 65 字节格式混淆。
示例代码
在 Solidity 中从紧凑签名恢复签名者:
function recoverCompact(bytes32 digest, bytes32 r, bytes32 vs) internal pure returns (address) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
address signer = ecrecover(digest, v, r, s);
require(signer != address(0), "bad signature");
return signer;
}
OpenZeppelin 的 ECDSA 库以 ECDSA.recover(hash, r, vs) 提供了同样的功能。
用 ethers v6 生成一个紧凑签名:
import { Wallet, Signature } from "ethers";
const wallet = Wallet.createRandom();
const sigHex = await wallet.signMessage("Hello World"); // 65 bytes
const sig = Signature.from(sigHex);
console.log(sig.r, sig.yParityAndS); // the two 32-byte words
console.log(sig.compactSerialized); // 64-byte hex string
// Round-trip: Signature.from also accepts the 64-byte form
const back = Signature.from(sig.compactSerialized);
console.log(back.v === sig.v && back.s === sig.s); // true