---
eip: 196
label: EIP-196
title: Precompiled contracts for addition and scalar multiplication on the elliptic curve alt_bn128
status: Final
type: Standards Track
category: Core
created: 2017-02-02
official: https://eips.ethereum.org/EIPS/eip-196
source: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-196.md
canonical: https://eips.huatuo.xyz/zh/eip-196/
lang: zh
tldr: 在 0x06 和 0x07 添加预编译合约，用于 alt_bn128 曲线上的点加法和标量乘法，使以太坊上验证 zkSNARK 的成本变得可承受。
tags: [precompile, cryptography, zk, core, byzantium]
---

# EIP-196: Precompiled contracts for addition and scalar multiplication on the elliptic curve alt_bn128

> Precompiled contracts for elliptic curve operations are required in order to perform zkSNARK verification within the block gas limit.

**TL;DR:** 在 0x06 和 0x07 添加预编译合约，用于 alt_bn128 曲线上的点加法和标量乘法，使以太坊上验证 zkSNARK 的成本变得可承受。

## 它解决什么问题？

zkSNARK 让人可以在不透露原因的情况下证明某个陈述为真。在以太坊上，这意味着隐私（隐藏输入）和扩容（用一个很小的证明代表大量计算）。验证证明需要椭圆曲线运算。用 EVM 字节码来写，这些运算的成本高得无法放进一个区块。

EIP-196 把两个最基本的曲线运算作为预编译合约内置到协议中。与 [EIP-197](/eip-197/) 中的配对检查一起，它们让链上 SNARK 验证变得可行。两者都随 Byzantium 升级（[EIP-609](/eip-609/)）上线。

## 它如何运作

所用曲线是 `alt_bn128`（也称 BN254），即在素数域上的 `y² = x³ + 3`，素数模 `p` 在规范中给出。选择它是因为它适合配对运算，并且与 Zcash 共用工具。

| 地址 | 运算 | 输入（字节） | 输出（字节） |
| --- | --- | --- | --- |
| `0x06` | ECADD: `P + Q` | `x1, y1, x2, y2`（128） | `x, y`（64） |
| `0x07` | ECMUL: `s · P` | `x, y, s`（96） | `x, y`（64） |

编码规则：

- 每个域元素和标量都是 32 字节的大端整数。点表示为 `(x, y)`，无穷远点为 `(0, 0)`。
- 输入过短时，在右侧用零补齐。多余的输入会被忽略。
- 如果某个点不在曲线上，或某个坐标 `>= p`，调用会**失败并消耗其获得的全部 gas**。标量可以是任意 256 位的值。

最初的 gas 费用是 ECADD 为 500，ECMUL 为 40,000。

## 示例代码

在 Solidity 中调用这些预编译合约：

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

library BN254 {
    struct G1 { uint256 x; uint256 y; }

    function add(G1 memory p, G1 memory q) internal view returns (G1 memory r) {
        (bool ok, bytes memory out) = address(0x06).staticcall(abi.encode(p.x, p.y, q.x, q.y));
        require(ok, "ecAdd failed");
        (r.x, r.y) = abi.decode(out, (uint256, uint256));
    }

    function mul(G1 memory p, uint256 s) internal view returns (G1 memory r) {
        (bool ok, bytes memory out) = address(0x07).staticcall(abi.encode(p.x, p.y, s));
        require(ok, "ecMul failed");
        (r.x, r.y) = abi.decode(out, (uint256, uint256));
    }
}

// Generator of G1 is (1, 2); mul(G1(1, 2), 2) returns 2·G
```

## 需要注意

- 在 Istanbul 升级中，[EIP-1108](/eip-1108/) 把 gas 价格降低到 150（ECADD）和 6,000（ECMUL）。不要硬编码最初的数字。
- 无效输入会烧掉转发的全部 gas。如果你的合约要处理不可信的点，只转发有限数量的 gas。
- 这些预编译合约只覆盖 G1 群。使用 G2 点的配对检查在 [EIP-197](/eip-197/) 中。
- 据估计，BN254 的安全强度略低于最初设想的 128 位。较新的设计通常更倾向于 BLS12-381，但 BN254 仍被以太坊上已部署的 SNARK 验证器广泛使用。


---

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