---
eip: 2027
label: EIP-2027
title: State Rent C - Net contract size accounting
status: Stagnant
type: Standards Track
category: Core
created: 2019-05-14
official: https://eips.ethereum.org/EIPS/eip-2027
source: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2027.md
canonical: https://eips.huatuo.xyz/zh/eip-2027/
lang: zh
tldr: 一个 State Rent 的构件：让每个合约记录其非空存储槽数量的净变化，为按大小定价的 gas 成本和租金奠定基础。
tags: [state-rent, storage, accounting, core]
---

# EIP-2027: State Rent C - Net contract size accounting

> Ethereum starts counting the number of storage slots filled and emptied in the contracts. Since the number of pre-existing slots is not currently accounted in the state, effectively, only net change in the number of slots is tracked.

**TL;DR:** 一个 State Rent 的构件：让每个合约记录其非空存储槽数量的净变化，为按大小定价的 gas 成本和租金奠定基础。

## 它解决什么问题？

以太坊并不记录合约使用了多少个存储槽。仅凭状态，想知道这个数字只能遍历合约的整个存储 trie，而这并非常数时间操作。然而这个数字对 2019 年讨论的几个想法很重要：

- 根据合约大小为 `SLOAD`/`SSTORE` 定价，以覆盖区块证明的带宽开销；
- 让快照同步协议知道并证明每个合约的存储有多大；
- 最终收取状态租金。

EIP-2027（"State Rent C"）是第一步：从分叉区块起开始统计变化。

## 它如何运作

每个合约（代码哈希不是空代码哈希的账户）都会新增一个 `uint64` 字段 `storagesize`。在分叉区块 `C` 之后，`SSTORE` 会更新它：

- 存储槽从**零变为非零**：加一；
- 存储槽从**非零变为零**：减一；
- 与其他状态变更一样，这些变化会随调用帧一起回滚。

由于在分叉时没人知道现有合约的真实大小，该字段从一个偏移量开始。建议 `HUGE_NUMBER` 取 2^63：

```python
HUGE_NUMBER = 2**63

def increment(acct):
    acct.storagesize = (acct.storagesize + 1) if acct.has_storagesize else HUGE_NUMBER + 1

def decrement(acct):
    acct.storagesize = (acct.storagesize - 1) if acct.has_storagesize else HUGE_NUMBER - 1
```

因此 `storagesize - HUGE_NUMBER` 就是自分叉以来的**净**变化。由于不可能有合约拥有 2^62 个存储槽，后续的"总量统计"升级就可以判断某个值仍是净值（约 2^63），还是已经被转换为真实总数（小得多）。合约无法读取这个字段。

## 示例代码

追踪一个在分叉后写入三个新存储槽、并清除一个已有存储槽的合约：

```python
HUGE = 2**63
size = None                     # field absent before first touch

def sstore(old, new):
    global size
    if old == 0 and new != 0:
        size = HUGE + 1 if size is None else size + 1
    elif old != 0 and new == 0:
        size = HUGE - 1 if size is None else size - 1

sstore(0, 5); sstore(0, 7); sstore(0, 9)   # three new slots
sstore(42, 0)                              # one pre-existing slot cleared
print(size - HUGE)                         # 2  (net change since fork)
```

## 需要注意

- **状态：Stagnant。** 它从未在主网激活。
- 它属于同一作者的"State Rent"提案系列，与 [EIP-2029](/eip-2029/)（状态计数器合约）、[EIP-2031](/eip-2031/)（净交易计数器）和 [EIP-2026](/eip-2026/)（固定账户预付）并列。预期的后续方案，即合约大小的总量统计，将追踪完整的总数。
- 它需要一次硬分叉，并为账户增加一个字段，但由于该值在 EVM 中不可观察，现有合约的行为不会改变。
- 关于更早的一步到位的租金设计，请参见 [EIP-1418](/eip-1418/)。


---

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