---
eip: 2098
label: ERC-2098
title: Compact Signature Representation
status: Final
type: Standards Track
category: ERC
created: 2019-03-14
requires: 2
official: https://eips.ethereum.org/EIPS/eip-2098
source: https://github.com/ethereum/ERCs/blob/master/ERCS/erc-2098.md
canonical: https://eips.huatuo.xyz/zh/eip-2098/
lang: zh
tldr: 把 yParity 这 1 个比特存放在 s 恒为零的最高位中，将以太坊签名打包成 64 字节，从而在所有传递签名的场景中节省 calldata 和 gas。
tags: [signature, ecdsa, secp256k1, gas, encoding]
---

# ERC-2098: Compact Signature Representation

> A compact representation of an Ethereum Signature.

**TL;DR:** 把 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 字节的"紧凑"格式，正好是两个字。

## 它如何运作

这个技巧依赖两点观察：

1. `yParity` 始终是 0 或 1（27/28 只是历史遗留的偏移量）。
2. 自 Homestead（[EIP-2](/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 中从紧凑签名恢复签名者：

```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 生成一个紧凑签名：

```ts
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
```

## 需要注意

- **状态：Final。** 它是一种编码约定，而不是协议变更；合约必须显式接受 `(r, vs)`。
- 它只适用于低位 `s` 的签名。`ecrecover` 本身也接受高位 `s`，因此在压缩来源不明的签名之前，请先规范化 `s`（并翻转 `yParity`）。
- 同时接受 65 字节和 64 字节两种格式的合约，必须确保在需要唯一性的场合，同一个签名不能以两种编码被重放；请记录已使用的 nonce，而不是已使用的签名字节。
- 它与 [EIP-712](/eip-712/) 和 [ERC-2612](/eip-2612/) 等签名消息标准天然契合。智能合约签名者（[ERC-1271](/eip-1271/)）不使用 ECDSA，因此紧凑格式不适用于它们。


---

This is an unofficial plain-language summary. Read the full specification: https://eips.ethereum.org/EIPS/eip-2098
