---
eip: 8016
label: EIP-8016
title: SSZ CompatibleUnion
status: Draft
type: Standards Track
category: Core
created: 2025-08-28
requires: 7495, 7916
official: https://eips.ethereum.org/EIPS/eip-8016
source: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-8016.md
canonical: https://eips.huatuo.xyz/zh/eip-8016/
lang: zh
tldr: 定义 CompatibleUnion，一种 SSZ 带标签联合类型，其各变体必须以兼容的方式 Merkleize，这样无论使用哪个变体，字段都保持相同的 generalized index（及证明路径）。
tags: [ssz, serialization, merkle, consensus, core]
---

# EIP-8016: SSZ CompatibleUnion

> SSZ type for forward-compatible unions

**TL;DR:** 定义 CompatibleUnion，一种 SSZ 带标签联合类型，其各变体必须以兼容的方式 Merkleize，这样无论使用哪个变体，字段都保持相同的 generalized index（及证明路径）。

## 它解决什么问题？

以太坊的一些对象有多个变体，且大部分字段相同；交易类型就是最明显的例子。如果每个变体都是单独的 SSZ 容器，同一个字段（比如 `to` 或 `value`）在不同变体的 Merkle 树中可能处于不同位置。这样，验证 Merkle proof 的轻客户端或合约就需要一张按变体划分的字段位置表，每出现一个新变体都要更新这张表。

EIP-8016 增加了一种联合类型，只接受树结构对齐的变体，使公共字段在所有变体中始终具有相同的 **generalized index（gindex）**。

## 它如何运作

- **记法：** `CompatibleUnion({selector: type})`，例如 `CompatibleUnion({1: Square, 2: Circle})`。selector 必须在 `1..127` 范围内；`0` 和大于 `127` 的值被保留。
- **兼容性规则：** 各变体必须以相同方式 Merkleize。相同的类型互相兼容；列表、向量和位域需要相同的容量；`Container` 需要相同顺序的相同字段名。[ProgressiveContainer](/eip-7495/) 变体在其共有的活动字段具有相同名称和兼容类型、且不共享其他字段名时互相兼容。[ProgressiveList](/eip-7916/) 需要兼容的元素类型。
- **序列化：** 一个 selector 字节，后接序列化后的值。该类型始终是可变大小，且没有默认值。
- **Merkleization：** `hash(hash_tree_root(data), selector)`，即把 selector 混入其中。这保证树形相同的两个变体仍会得到不同的根。
- **JSON：** `{ "selector": "<n>", "data": ... }`。

## 示例代码

采用共识规范风格的示意 Python 代码：

```python
class Square(ProgressiveContainer(active_fields=[1, 0, 1])):
    side: uint16
    color: uint8

class Circle(ProgressiveContainer(active_fields=[0, 1, 1])):
    radius: uint16
    color: uint8

Shape = CompatibleUnion({1: Square, 2: Circle})

def serialize_union(value) -> bytes:
    return value.selector.to_bytes(1, "little") + serialize(value.data)

def hash_tree_root_union(value) -> Root:
    return hash(hash_tree_root(value.data), value.selector.to_bytes(1, "little"))

# `color` sits at the same gindex in both Square and Circle,
# so one Merkle proof path works for every Shape.
```

## 需要注意

- 状态为 **Draft**。它是把以太坊数据结构迁移到 SSZ 这一更大工作的一部分，与 [EIP-7495](/eip-7495/) 和 [EIP-7916](/eip-7916/)（均处于 Review）并列。
- 用 `CompatibleUnion` 包装现有字段**不是**向后兼容的，因此规范建议在预期会有更多变体的地方尽早引入，哪怕目前只有一个选项。此后，可以增减选项而不破坏验证方。
- 它取代了早先只在已弃用规范中使用的 SSZ 联合类型设计。
- 参考实现：`ethereum/remerkleable`。


---

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