# Registrar.sol

> Encrypted ERC システムにおけるユーザー登録を管理するコントラクト。各ユーザーの Ethereum アドレスと楕円曲線公開鍵の対応付け、およびゼロ知識証明による登録手続きの検証を担います。

- URL: https://cardene.dev/books/encrypted-erc/2f410d
- 本: Encrypted ERC (https://cardene.dev/books/encrypted-erc.md)
- 章: 16 / 32
- 前の章: https://cardene.dev/books/encrypted-erc/2c2be3.md
- 次の章: https://cardene.dev/books/encrypted-erc/e6d243.md
- 公開日: 2025-07-07
- 更新日: 2025-07-07
- トピック: Blockchain
- タグ: ブロックチェーン, solidity, smartcontract, avalanch

## 概要

Encrypted ERC システムにおけるユーザー登録を管理するコントラクト。
各ユーザーの Ethereum アドレスと楕円曲線公開鍵の対応付け、およびゼロ知識証明による登録手続きの検証を担います。これにより、Encrypted ERC の各操作（Mint、Transfer、Burnなど）でユーザーの公開鍵を安全に参照できるようになります。

## コントラクト

https://github.com/ava-labs/EncryptedERC/blob/main/contracts/Registrar.sol

```solidity
// (c) 2025, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.

// SPDX-License-Identifier: Ecosystem

pragma solidity 0.8.27;

import {Point, RegisterProof} from "./types/Types.sol";
import {IRegistrationVerifier} from "./interfaces/verifiers/IRegistrationVerifier.sol";
import {UserAlreadyRegistered, InvalidChainId, InvalidSender, InvalidRegistrationHash, InvalidProof} from "./errors/Errors.sol";

// libraries
import {BabyJubJub} from "./libraries/BabyJubJub.sol";

/**
 * @title Registrar
 * @notice Contract for managing user registration in the privacy-preserving ERC system
 * @dev This contract handles:
 *      1. User registration with public keys
 *      2. Verification of registration proofs
 *
 * The Registrar is a critical component that:
 * - Associates Ethereum addresses with public keys for encrypted operations
 */
contract Registrar {
    ///////////////////////////////////////////////////
    ///                   State Variables           ///
    ///////////////////////////////////////////////////

    /// @notice The verifier contract used to validate registration proofs
    IRegistrationVerifier public registrationVerifier;

    /// @notice Mapping of user addresses to their public keys
    mapping(address userAddress => Point userPublicKey) public userPublicKeys;

    /// @notice Mapping of registration hashes to registration status
    /// @dev Used to prevent duplicate registrations
    mapping(uint256 registrationHash => bool isRegistered) public isRegistered;

    ///////////////////////////////////////////////////
    ///                    Events                   ///
    ///////////////////////////////////////////////////

    /// @notice Emitted when a user is registered
    /// @param user Address of the user
    /// @param publicKey Public key of the user
    event Register(address indexed user, Point publicKey);

    ///////////////////////////////////////////////////
    ///                   Constructor               ///
    ///////////////////////////////////////////////////

    /**
     * @notice Initializes the Registrar contract
     * @param registrationVerifier_ Address of the registration verifier contract
     */
    constructor(address registrationVerifier_) {
        registrationVerifier = IRegistrationVerifier(registrationVerifier_);
    }

    ///////////////////////////////////////////////////
    ///                   External                  ///
    ///////////////////////////////////////////////////

    /**
     * @notice Registers a user with their public key
     * @param proof The zero-knowledge proof proving the validity of the registration
     * @dev This function:
     *      1. Verifies the sender matches the account in the proof
     *      2. Checks the chain ID matches
     *      3. Validates the registration hash
     *      4. Verifies the zero-knowledge proof
     *      5. Registers the user with their public key
     *
     * Requirements:
     * - Sender must match the account in the proof
     * - Chain ID must match
     * - Registration hash must be valid
     * - User must not be already registered
     * - Proof must be valid
     */
    function register(RegisterProof calldata proof) external {
        // extract public inputs
        uint256[5] memory input = proof.publicSignals;

        address account = address(uint160(input[2]));

        // check if the sender matches the account in the proof
        if (msg.sender != account) {
            revert InvalidSender();
        }

        // check if the chain ID matches
        if (block.chainid != input[3]) {
            revert InvalidChainId();
        }

        // check if the registration hash is valid
        uint256 registrationHash = input[4];
        if (registrationHash >= BabyJubJub.Q) {
            revert InvalidRegistrationHash();
        }

        // check if the user is already registered
        if (isRegistered[registrationHash] && isUserRegistered(account)) {
            revert UserAlreadyRegistered();
        }

        // Verify the proof
        _verifyProof(proof);

        _register(account, Point({x: input[0], y: input[1]}), registrationHash);
    }

    /**
     * @notice Checks if a user is registered
     * @param user The address of the user to check
     * @return bool True if the user is registered, false otherwise
     * @dev A user is considered registered if their public key is not the zero point (0,0)
     */
    function isUserRegistered(address user) public view returns (bool) {
        return userPublicKeys[user].x != 0 && userPublicKeys[user].y != 0;
    }

    /**
     * @notice Gets the public key of a user
     * @param user The address of the user
     * @return publicKey The public key of the user as a uint256 array
     * @dev Returns the x and y coordinates of the user's public key
     */
    function getUserPublicKey(
        address user
    ) public view returns (uint256[2] memory publicKey) {
        return [userPublicKeys[user].x, userPublicKeys[user].y];
    }

    ///////////////////////////////////////////////////
    ///                   Internal                  ///
    ///////////////////////////////////////////////////

    /**
     * @notice Registers a user with their public key
     * @param user The address of the user
     * @param publicKey The public key of the user
     * @param registrationHash The registration hash
     * @dev This function:
     *      1. Sets the user's public key
     *      2. Marks the registration hash as used
     *      3. Emits a Register event
     */
    function _register(
        address user,
        Point memory publicKey,
        uint256 registrationHash
    ) internal {
        userPublicKeys[user] = publicKey;
        isRegistered[registrationHash] = true;
        emit Register(user, publicKey);
    }

    /**
     * @notice Verifies a registration proof
     * @param proof_ The proof to verify
     * @dev This function:
     *      1. Extracts the proof points and public inputs
     *      2. Calls the verifier contract to verify the proof
     *      3. Reverts if the proof is invalid
     */
    function _verifyProof(RegisterProof calldata proof_) internal view {
        uint256[2] memory pointA_ = proof_.proofPoints.a;
        uint256[2][2] memory pointB_ = proof_.proofPoints.b;
        uint256[2] memory pointC_ = proof_.proofPoints.c;
        uint256[5] memory input = proof_.publicSignals;

        // Verify the proof
        bool verified_ = registrationVerifier.verifyProof(
            pointA_,
            pointB_,
            pointC_,
            input
        );

        if (!verified_) {
            revert InvalidProof();
        }
    }
}
```

## State

```solidity
IRegistrationVerifier public registrationVerifier;
mapping(address => Point) public userPublicKeys;
mapping(uint256 => bool) public isRegistered;
```

* `registrationVerifier`
    * 登録証明用のVerifierコントラクト。
    * ユーザーの登録手続きで提出されたゼロ知識証明を検証。
* `userPublicKeys`
    ユーザーのEthereumアドレスをキーに、そのユーザーのBabyJubJub曲線上の公開鍵 (`Point`) を管理。
* `isRegistered`
    * 登録申請時に計算されるハッシュ値をキーに、その登録手続きがすでに完了しているかを追跡する。
    * 二重登録を防止するために使用される。

## Events

### `Register`

```solidity
event Register(address indexed user, Point publicKey);
```

ユーザーの公開鍵の登録が完了したときに発行されるイベント。
`user` は登録された Ethereum アドレス、`publicKey` はそのユーザーのBabyJubJub曲線公開鍵を表す。

## External Functions

### `register`

```solidity
function register(RegisterProof calldata proof) external {
    // extract public inputs
    uint256[5] memory input = proof.publicSignals;

    address account = address(uint160(input[2]));

    // check if the sender matches the account in the proof
    if (msg.sender != account) {
        revert InvalidSender();
    }

    // check if the chain ID matches
    if (block.chainid != input[3]) {
        revert InvalidChainId();
    }

    // check if the registration hash is valid
    uint256 registrationHash = input[4];
    if (registrationHash >= BabyJubJub.Q) {
        revert InvalidRegistrationHash();
    }

    // check if the user is already registered
    if (isRegistered[registrationHash] && isUserRegistered(account)) {
        revert UserAlreadyRegistered();
    }

    // Verify the proof
    _verifyProof(proof);

    _register(account, Point({x: input[0], y: input[1]}), registrationHash);
}
```

ユーザーが自分の公開鍵を登録する関数。
以下の確認をしています。
- 呼び出し元アドレスと証明内に含まれるアカウントが一致しているか。
- チェーンIDが正しいか。
- 登録ハッシュが楕円曲線の有限体内で有効な値か。
- 同じユーザー／ハッシュでの二重登録が行われていないか。

上記のチェックが完了したのち、最後にVerifierコントラクトを呼び出してゼロ知識証明を検証します。
検証に成功すると、`userPublicKeys` と `isRegistered` を更新し、`Register` イベントを発行します。

**引数**

* `proof` (`RegisterProof calldata`)
    * ユーザーの登録手続きに必要なゼロ知識証明。
    * `proof.publicSignals` は `[pk_x, pk_y, account, chainId, registrationHash]` の5要素配列。
  * `proof.proofPoints` はSNARKの A, B, C 点のタプル。

### `isUserRegistered`

```solidity
function isUserRegistered(address user) public view returns (bool) {
    return userPublicKeys[user].x != 0 && userPublicKeys[user].y != 0;
}
```

特定のアドレスがすでに登録済みかを返す関数。
`userPublicKeys[user]` の x, y 座標のいずれかが非ゼロであれば登録済みと判断します。

**引数**

* `user` (`address`)
    * 登録状況を確認するユーザーのアドレス。

### `getUserPublicKey`

```solidity
function getUserPublicKey(
    address user
) public view returns (uint256[2] memory publicKey) {
    return [userPublicKeys[user].x, userPublicKeys[user].y];
}
```

ユーザーの公開鍵を取得する関数。
戻り値は `[x, y]` の形式でBabyJubJub曲線上の座標を `uint256` 配列として返します。

**引数**

* `user` (`address`)
    * 公開鍵を取得するユーザーのアドレス。

## Internal Functions

### `_register`

```solidity
function _register(
    address user,
    Point memory publicKey,
    uint256 registrationHash
) internal {
    userPublicKeys[user] = publicKey;
    isRegistered[registrationHash] = true;
    emit Register(user, publicKey);
}
```

ユーザー登録情報を保存する内部関数。
`userPublicKeys` に公開鍵を書き込み、対応する `registrationHash` を `isRegistered` マップに登録済みとしてフラグを立てて `Register` イベントを発行します。

**引数**

* `user` (`address`)
    * 登録対象のユーザーアドレス。
* `publicKey` (`Point memory`)
    * BabyJubJub曲線上の公開鍵。
* `registrationHash` (`uint256`)
    * 登録申請時に証明から得られるハッシュ値。

### `_verifyProof`

```solidity
function _verifyProof(RegisterProof calldata proof_) internal view {
    uint256[2] memory pointA_ = proof_.proofPoints.a;
    uint256[2][2] memory pointB_ = proof_.proofPoints.b;
    uint256[2] memory pointC_ = proof_.proofPoints.c;
    uint256[5] memory input = proof_.publicSignals;

    // Verify the proof
    bool verified_ = registrationVerifier.verifyProof(
        pointA_,
        pointB_,
        pointC_,
        input
    );

    if (!verified_) {
        revert InvalidProof();
    }
}
```

`registrationVerifier` コントラクトを呼び出して、渡された `RegisterProof` を検証する関数。
内部で SNARK の A, B, C 点および公開入力を取り出し、`verifyProof` を実行。
検証に失敗すると `InvalidProof` エラーを返します。

**引数**

* `proof_` (`RegisterProof calldata`)
    * 検証対象の登録証明データ一式。
