---
eip: 6617
label: ERC-6617
title: Bit Based Permission
status: Review
type: Standards Track
category: ERC
created: 2023-02-27
official: https://eips.ethereum.org/EIPS/eip-6617
source: https://github.com/ethereum/ERCs/blob/master/ERCS/erc-6617.md
canonical: https://eips.huatuo.xyz/zh/eip-6617/
lang: zh
tldr: 一种极简的访问控制标准：每个权限是 uint256 中的一个比特位，角色就是位掩码，权限检查只需一次 AND 运算。
tags: [access-control, permissions, roles, solidity]
---

# ERC-6617: Bit Based Permission

> A permission and role system based on bits

**TL;DR:** 一种极简的访问控制标准：每个权限是 uint256 中的一个比特位，角色就是位掩码，权限检查只需一次 AND 运算。

## 它解决什么问题？

大多数合约使用单一所有者（[ERC-173](/eip-173/)）或具名的 `bytes32` 角色（[ERC-5982](/eip-5982/)）来做访问控制。单一所有者粒度太粗，而角色映射每检查一个角色就需要一次存储读取。

ERC-6617 把权限打包进比特位。用户的全部权限集合就是一个 `uint256`，因此检查"该用户是否同时拥有权限 A 和 B？"只需对一个存储值做按位 `AND`。

## 它如何运作

- 每个**权限**是 2 的幂（恰好只有一位被置位）。每个权限都是唯一的，`0` 表示"无权限"。这最多可以有 256 个权限。
- **角色**是权限的任意 OR 组合，因此最多有 2^256 种可能的角色，且无需预先定义。
- 比特位的位置可以表示重要程度：把最重要的权限放在最高位，权限就可以按整数比较。
- 必需接口 `IEIP6617`：
  - 如果用户的比特位是 `required` 的超集，`hasPermission(user, required)` 返回 true。
  - `grantPermission(user, perm)` 和 `revokePermission(user, perm)` 返回 `bool`。
  - 必须触发 `PermissionGranted` 和 `PermissionRevoked` 事件。
- 可选（推荐）的 `IEIP6617Meta` 为基础权限和主要组合附加名称和描述，因为仅凭比特位无法自我说明。

谁可以授予或撤销权限由具体实现决定。

## 示例代码

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

contract BitPermissions {
    uint256 public constant MINT   = 1 << 0;
    uint256 public constant PAUSE  = 1 << 1;
    uint256 public constant ADMIN  = 1 << 255;      // most important = highest bit
    uint256 public constant MINTER_PAUSER = MINT | PAUSE; // a role

    mapping(address => uint256) private _perm;

    event PermissionGranted(address indexed _grantor, uint256 indexed _permission, address indexed _user);
    event PermissionRevoked(address indexed _revoker, uint256 indexed _permission, address indexed _user);

    constructor() { _perm[msg.sender] = ADMIN; }

    modifier only(uint256 required) {
        require(hasPermission(msg.sender, required), "forbidden");
        _;
    }

    function hasPermission(address user, uint256 required) public view returns (bool) {
        return _perm[user] & required == required;
    }

    function grantPermission(address user, uint256 p) external only(ADMIN) returns (bool) {
        _perm[user] |= p;
        emit PermissionGranted(msg.sender, p, user);
        return true;
    }

    function revokePermission(address user, uint256 p) external only(ADMIN) returns (bool) {
        _perm[user] &= ~p;
        emit PermissionRevoked(msg.sender, p, user);
        return true;
    }
}
```

## 需要注意

- 状态为 **Review**；在最终确定之前细节仍可能变化。
- 每个合约 256 个权限是硬性上限，且比特位的含义固定在代码中。日后更改第 3 位的含义实际上等同于一次迁移。
- 位掩码对人类和区块浏览器来说都不透明。元数据扩展有所帮助，但相比 OpenZeppelin 风格的 `AccessControl` 角色，工具支持要少得多。
- 注意 `hasPermission(user, 0)`：按照超集规则它永远为 true，因此绝不要用未设置的常量作为守卫条件。


---

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