EIP-1108 · Final(最终) · Core(核心) · 2018-05-21
EIP-1108: Reduce alt_bn128 precompile gas costs
把 alt_bn128 椭圆曲线预编译(加法、乘法、配对)的 gas 价格大致降低了 3 到 7 倍,使链上 zk-SNARK 验证和隐私协议便宜得多。
它解决什么问题?
EIP-196 和 EIP-197 添加了用于 alt_bn128(BN254)曲线运算的预编译合约。它们是在智能合约内验证 zk-SNARK 证明(例如 Groth16)的基础构件。它们的 gas 价格是 2017 年根据当时的客户端代码设定的。
在 2018 至 2019 年间,Geth(改用了 Cloudflare 的 bn256 库)和 Parity(优化后的 bn crate)执行这些运算都变得快得多,Geth 大约快了一个数量级。gas 价格不再与真实成本相符,因此隐私工具、rollup 和其他基于 SNARK 的系统支付的费用远高于这些计算应有的水平。EIP-1108 让价格重新回到合理水平。它随 Istanbul 升级上线。
它如何运作
只有 gas 价目表发生变化;预编译合约的输入、输出和行为完全保持不变。
| 预编译 | 地址 | 之前 | 之后 |
|---|---|---|---|
ECADD |
0x06 |
500 | 150 |
ECMUL |
0x07 |
40,000 | 6,000 |
| 配对检查 | 0x08 |
80,000·k + 100,000 | 34,000·k + 45,000 |
k 是传给配对检查的点对数量。
新的数字来自对较慢客户端(Parity)的基准测试。作者以 ecrecover(3,000 gas,约 116 µs)作为"公平"的参照,得到约每微秒 25.86 gas,然后把测得的配对时间拆分为固定部分和每个配对的部分。
一次典型的 Groth16 验证使用 4 次配对,因此仅配对这一步就从 420,000 gas 降到 181,000 gas,另外用于构造公共输入点的 ECMUL/ECADD 调用也便宜得多。
示例代码
直接从 Solidity 调用 ECADD。大多数项目使用封装这些调用的生成式验证器(snarkjs、gnark 等),但它们最终都会编译成这样的 staticcall:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
library BN254 {
struct G1 { uint256 x; uint256 y; }
/// Point addition via the 0x06 precompile (150 gas since EIP-1108).
function add(G1 memory p, G1 memory q) internal view returns (G1 memory r) {
uint256[4] memory input = [p.x, p.y, q.x, q.y];
bool ok;
assembly {
ok := staticcall(gas(), 0x06, input, 0x80, r, 0x40)
}
require(ok, "ecAdd failed");
}
/// Scalar multiplication via the 0x07 precompile (6,000 gas since EIP-1108).
function mul(G1 memory p, uint256 s) internal view returns (G1 memory r) {
uint256[3] memory input = [p.x, p.y, s];
bool ok;
assembly {
ok := staticcall(gas(), 0x07, input, 0x60, r, 0x40)
}
require(ok, "ecMul failed");
}
}
估算改动前后的配对成本:
const pairingGas = (k: number, istanbul = true) =>
istanbul ? 34_000 * k + 45_000 : 80_000 * k + 100_000;
console.log(pairingGas(4)); // 181000
console.log(pairingGas(4, false)); // 420000