---
eip: 152
label: EIP-152
title: Add BLAKE2 compression function `F` precompile
status: Final
type: Standards Track
category: Core
created: 2016-10-04
official: https://eips.ethereum.org/EIPS/eip-152
source: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-152.md
canonical: https://eips.huatuo.xyz/zh/eip-152/
lang: zh
tldr: 在地址 0x09 新增一个运行 BLAKE2b 压缩函数 F 的预编译，使合约能以较低成本验证 Zcash 区块头等基于 BLAKE2 的数据。
tags: [precompile, cryptography, hashing, blake2, istanbul]
---

# EIP-152: Add BLAKE2 compression function `F` precompile

> This EIP will enable the BLAKE2b hash function and other higher-round 64-bit BLAKE2 variants to run cheaply on the EVM, allowing easier interoperability between Ethereum and Zcash as well as other Equihash-based PoW coins.

**TL;DR:** 在地址 0x09 新增一个运行 BLAKE2b 压缩函数 F 的预编译，使合约能以较低成本验证 Zcash 区块头等基于 BLAKE2 的数据。

## 它解决什么问题？

BLAKE2 是一种快速且应用广泛的哈希函数。Zcash 的 Equihash 工作量证明依赖 BLAKE2b，Filecoin、Handshake 等其他项目也是如此。要在以太坊合约中验证 Zcash 区块头（用于 BTC-Relay 式的轻客户端，或无需信任的跨链兑换），每个区块头都需要多次运行 BLAKE2b。

BLAKE2b 是为 64 位、小端序的 CPU 设计的。而 EVM 使用 256 位、大端序的字，因此纯 Solidity 实现的 gas 开销非常高。预编译让客户端可以改用原生代码来运行。

## 它如何运作

作者没有选择完整的"BLAKE2b 哈希"预编译，而是只公开 RFC 7693 中的核心**压缩函数 `F`**。不同项目需要 BLAKE2 的不同特性（个性化、盐、带密钥哈希、树哈希、不同的输出长度）。有了 `F`，合约就可以自己构建这些功能。

该预编译位于地址 `0x09`。输入必须**恰好为 213 字节**：

| 字节数 | 字段 | 编码 |
| --- | --- | --- |
| 4 | `rounds` | 大端序 uint32 |
| 64 | `h` 状态向量 | 8 × 小端序 uint64 |
| 128 | `m` 消息块 | 16 × 小端序 uint64 |
| 8 + 8 | `t_0`、`t_1` 偏移计数器 | 小端序 uint64 |
| 1 | `f` 最终块标志 | 必须为 `0` 或 `1` |

任何其他长度，或 `f` 取 0 和 1 以外的值，都会报错。输出是更新后的 64 字节状态 `h`，同样是小端序。gas 成本很简单：**每轮 1 gas**。标准 BLAKE2b 使用 12 轮，但调用者可以要求更多。

## 示例代码

一个简单的 Solidity 封装（改编自规范中的写法）：

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

library Blake2F {
    function compress(
        uint32 rounds,
        bytes32[2] memory h,   // 64-byte state
        bytes32[4] memory m,   // 128-byte message block
        bytes8[2] memory t,    // offset counters
        bool f                 // final block?
    ) internal view returns (bytes32[2] memory out) {
        bytes memory input = abi.encodePacked(rounds, h[0], h[1], m[0], m[1], m[2], m[3], t[0], t[1], f);
        // input.length == 213
        assembly {
            if iszero(staticcall(gas(), 0x09, add(input, 32), 213, out, 64)) {
                revert(0, 0)
            }
        }
    }
}
```

`abi.encodePacked` 会把 `bool` 编码为单个字节 `0x00` 或 `0x01`，这正是预编译所期望的。

## 需要注意

- 该提案状态为 Final。它在 2019 年的 Istanbul 升级（[EIP-1679](/eip-1679/)）中上线。
- 注意字节序。`rounds` 是大端序，其余所有字段都是小端序。调用 `F` 时最常见的错误就是搞错这一点。
- 预编译只提供压缩这一步。填充、计数器和最终块标志需要由你的代码处理，具体见 RFC 7693。
- 与其他预编译一样，它的地址是固定的，因此调用它的合约只能在启用了 Istanbul 时代预编译的链上运行。


---

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