概要

このコントラクトは、ERC734(キー管理)とERC735(クレーム管理)の標準を実装したオンチェーンID(ONCHAINID)です。 ブロックチェーン上で個人のデジタルな身元を表現し、そのIDに紐づく権限(キー)と資格証明(クレーム)を管理するための中心的な役割を担います。

Identityコントラクトは、ユーザーのデジタルIDの「本体」として機能するスマートコントラクトです。 その設計はUpgradeを考慮しており、変数を保持するStorageコントラクトと、ロジックを実装するIdentityコントラクトに分離されています。

このコントラクトは、大きく分けて2つの機能群を提供します。 1つはERC734に基づくキー管理機能です。 IDの所有者は、addKeyやremoveKeyを通じて、自身のIDを操作できるウォレットアドレス(キー)とその権限(目的:purpose)を細かく設定できます。 これにより、「管理権限」、「アクション実行権限」、「クレーム発行権限」といった役割分担が可能になります。

もう1つはERC735に基づくクレーム管理機能です。 addClaim関数を通じて、ID所有者から許可されたクレーム発行者が、そのIDに対して「本人確認済み」などの資格証明(クレーム)を記録できます。removeClaimでそのクレームを削除することも可能です。

executeとapprove関数により、このIDコントラクトはスマートコントラクトウォレットのように振る舞い、他のコントラクトとの対話や送金を実行することもできます。 これらの機能全体を通じて、ユーザー主権に基づいた、柔軟で安全なデジタルID管理を実現します。

キー

Identityコントラクトにおける「キー」とは、そのオンチェーンIDを操作したり、そのIDに関する情報を証明したりするための権限そのものです。

キーの主な使用目的(purpose)

キーの使用目的は、purposeという番号によって明確に区別されます。 Identity.solのコードで定義されている主な目的は以下の通りです。

管理キー (Management Key / purpose = 1)

IDの最高管理権限で、このIDに関する全ての設定変更を行えます。

  • 新しいキー(管理キー、実行キー、クレーム署名者キー)を追加する (addKey)。
  • 既存のキーを削除する (removeKey)。
  • ID自身に関わる重要な操作(コントラクトのアップグレードなど)を承認する (approve)。

IDの所有者本人のメインウォレットのみがこのキーを持ちます。

実行キー (Action Key / purpose = 2)

IDとして日常的な操作を行うための権限。

  • このIDとして、他のコントラクトを呼び出す(例: DeFiプロトコルでスワップする)。
  • このIDとして、トークンやETHを送金する。
  • これらの操作をexecute関数とapprove関数を通じて行います。

ID所有者が日常的に使用するウォレット(例: スマートフォンのウォレット)や、特定の操作を自動化するボットのコントラクトなどがこのキーを持ちます。 管理キーとは別の、よりリスクの低いキーを割り当てることで、セキュリティを高めます。

クレーム署名者キー (Claim Signer Key / purpose = 3)

このIDに対して新しいクレームを追加することを許可された、外部の機関のための権限。

  • このIDのaddClaim関数を呼び出して、資格証明を記録する。
  • このIDのremoveClaim関数を呼び出して、自身が発行したクレームを取り消す。

KYC業者や証券会社など、ID所有者が信頼しte自身のIDへの情報書き込みを許可したクレーム発行者のアドレスがこのキーとして登録されます。

カスタムのキー

addKey関数の_purpose引数はuint256型であり、ERC-734標準で定義されている 1 (MANAGEMENT), 2 (ACTION), 3 (CLAIM) 以外の任意の番号を指定して、カスタムの目的を持つキーを追加することが技術的に可能です。

例:

solidity
// 目的番号100を「文書閲覧キー」として独自に定義
bytes32 documentViewerKey = keccak256(abi.encode(viewerAddress));
identityContract.addKey(documentViewerKey, 100, 1); 

このように、purposeとして100を指定してキーを追加できます。 ただし、Identity.solの現状の実装だとカスタムキー(purposeが1, 2, 3以外)を直接利用・検証するロジックは存在しません。

現状のコードでpurposeが意味を持つのは、以下の3つの修飾子と1つの関数だけです。

  • onlyManager purposeが1であるかをチェックする。
  • onlyClaimKey purposeが3であるかをチェックする。
  • approve関数 purposeが1または2であるかをチェックする。

機能

  • ERC734準拠のキー管理(追加、削除、権限設定)
  • ERC735準拠のクレーム管理(追加、削除)
  • スマートコントラクトウォレットとしての実行機能(execute, approve)
  • クレームの有効性検証機能
  • アップグレード可能なアーキテクチャ(ロジックとストレージの分離)

フロー

クレームの追加と権限管理

sequenceDiagram
    actor Investor as 投資家 (ID所有者)
    actor Issuer as クレーム発行者
    participant Identity as ONCHAINIDコントラクト

    Investor->>Identity: 1. addKey(Issuerのアドレス, 目的:3)
    activate Identity
    Note over Identity: 発行者にクレーム追加権限を付与
    Identity-->>Investor: 成功
    deactivate Identity

    %% 時間が経過 %%

    Issuer->>Identity: 2. addClaim(topic, signature, data, ...)
    activate Identity
    Identity->>Identity: 3. onlyClaimKey修飾子で<br>呼び出し元が権限を持つか検証
    alt 検証成功
        Note over Identity: クレームをストレージに保存
        Identity-->>Issuer: 4. 成功 (ClaimAddedイベント発行)
    else 検証失敗
        Identity-->>Issuer: 5. 失敗 (トランザクションリバート)
    end
    deactivate Identity

コード

Identity.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.17;

import "./interface/IIdentity.sol";
import "./interface/IClaimIssuer.sol";
import "./version/Version.sol";
import "./storage/Storage.sol";

/**
 * @dev Implementation of the `IERC734` "KeyHolder" and the `IERC735` "ClaimHolder" interfaces
 * into a common Identity Contract.
 * This implementation has a separate contract were it declares all storage,
 * allowing for it to be used as an upgradable logic contract.
 */
contract Identity is Storage, IIdentity, Version {

    /**
     * @notice Prevent any direct calls to the implementation contract (marked by _canInteract = false).
     */
    modifier delegatedOnly() {
        require(_canInteract == true, "Interacting with the library contract is forbidden.");
        _;
    }

    /**
     * @notice requires management key to call this function, or internal call
     */
    modifier onlyManager() {
        require(msg.sender == address(this) || keyHasPurpose(keccak256(abi.encode(msg.sender)), 1)
        , "Permissions: Sender does not have management key");
        _;
    }

    /**
     * @notice requires claim key to call this function, or internal call
     */
    modifier onlyClaimKey() {
        require(msg.sender == address(this) || keyHasPurpose(keccak256(abi.encode(msg.sender)), 3)
        , "Permissions: Sender does not have claim signer key");
        _;
    }

    /**
     * @notice constructor of the Identity contract
     * @param initialManagementKey the address of the management key at deployment
     * @param _isLibrary boolean value stating if the contract is library or not
     * calls __Identity_init if contract is not library
     */
    constructor(address initialManagementKey, bool _isLibrary) {
        require(initialManagementKey != address(0), "invalid argument - zero address");

        if (!_isLibrary) {
            __Identity_init(initialManagementKey);
        } else {
            _initialized = true;
        }
    }

    /**
     * @notice When using this contract as an implementation for a proxy, call this initializer with a delegatecall.
     *
     * @param initialManagementKey The ethereum address to be set as the management key of the ONCHAINID.
     */
    function initialize(address initialManagementKey) external {
        require(initialManagementKey != address(0), "invalid argument - zero address");
        __Identity_init(initialManagementKey);
    }

    /**
     * @dev See {IERC734-execute}.
     * @notice Passes an execution instruction to the keymanager.
     * If the sender is an ACTION key and the destination address is not the identity contract itself, then the
     * execution is immediately approved and performed.
     * If the destination address is the identity itself, then the execution would be performed immediately only if
     * the sender is a MANAGEMENT key.
     * Otherwise the execution request must be approved via the `approve` method.
     * @return executionId to use in the approve function, to approve or reject this execution.
     */
    function execute(address _to, uint256 _value, bytes memory _data)
    external
    delegatedOnly
    override
    payable
    returns (uint256 executionId)
    {
        uint256 _executionId = _executionNonce;
        _executions[_executionId].to = _to;
        _executions[_executionId].value = _value;
        _executions[_executionId].data = _data;
        _executionNonce++;

        emit ExecutionRequested(_executionId, _to, _value, _data);

        if (keyHasPurpose(keccak256(abi.encode(msg.sender)), 1)) {
            approve(_executionId, true);
        }
        else if (_to != address(this) && keyHasPurpose(keccak256(abi.encode(msg.sender)), 2)){
            approve(_executionId, true);
        }

        return _executionId;
    }

    /**
     * @dev See {IERC734-getKey}.
     * @notice Implementation of the getKey function from the ERC-734 standard
     * @param _key The public key.  for non-hex and long keys, its the Keccak256 hash of the key
     * @return purposes Returns the full key data, if present in the identity.
     * @return keyType Returns the full key data, if present in the identity.
     * @return key Returns the full key data, if present in the identity.
     */
    function getKey(bytes32 _key)
    external
    override
    view
    returns(uint256[] memory purposes, uint256 keyType, bytes32 key)
    {
        return (_keys[_key].purposes, _keys[_key].keyType, _keys[_key].key);
    }

    /**
    * @dev See {IERC734-getKeyPurposes}.
    * @notice gets the purposes of a key
    * @param _key The public key.  for non-hex and long keys, its the Keccak256 hash of the key
    * @return _purposes Returns the purposes of the specified key
    */
    function getKeyPurposes(bytes32 _key)
    external
    override
    view
    returns(uint256[] memory _purposes)
    {
        return (_keys[_key].purposes);
    }

    /**
    * @dev See {IERC734-getKeysByPurpose}.
    * @notice gets all the keys with a specific purpose from an identity
    * @param _purpose a uint256[] Array of the key types, like 1 = MANAGEMENT, 2 = ACTION, 3 = CLAIM, 4 = ENCRYPTION
    * @return keys Returns an array of public key bytes32 hold by this identity and having the specified purpose
    */
    function getKeysByPurpose(uint256 _purpose)
    external
    override
    view
    returns(bytes32[] memory keys)
    {
        return _keysByPurpose[_purpose];
    }

    /**
    * @dev See {IERC735-getClaimIdsByTopic}.
    * @notice Implementation of the getClaimIdsByTopic function from the ERC-735 standard.
    * used to get all the claims from the specified topic
    * @param _topic The identity of the claim i.e. keccak256(abi.encode(_issuer, _topic))
    * @return claimIds Returns an array of claim IDs by topic.
    */
    function getClaimIdsByTopic(uint256 _topic)
    external
    override
    view
    returns(bytes32[] memory claimIds)
    {
        return _claimsByTopic[_topic];
    }

    /**
    * @notice implementation of the addKey function of the ERC-734 standard
    * Adds a _key to the identity. The _purpose specifies the purpose of key. Initially we propose four purposes:
    * 1: MANAGEMENT keys, which can manage the identity
    * 2: ACTION keys, which perform actions in this identities name (signing, logins, transactions, etc.)
    * 3: CLAIM signer keys, used to sign claims on other identities which need to be revokable.
    * 4: ENCRYPTION keys, used to encrypt data e.g. hold in claims.
    * MUST only be done by keys of purpose 1, or the identity itself.
    * If its the identity itself, the approval process will determine its approval.
    * @param _key keccak256 representation of an ethereum address
    * @param _type type of key used, which would be a uint256 for different key types. e.g. 1 = ECDSA, 2 = RSA, etc.
    * @param _purpose a uint256 specifying the key type, like 1 = MANAGEMENT, 2 = ACTION, 3 = CLAIM, 4 = ENCRYPTION
    * @return success Returns TRUE if the addition was successful and FALSE if not
    */
    function addKey(bytes32 _key, uint256 _purpose, uint256 _type)
    public
    delegatedOnly
    onlyManager
    override
    returns (bool success)
    {
        if (_keys[_key].key == _key) {
            uint256[] memory _purposes = _keys[_key].purposes;
            for (uint keyPurposeIndex = 0; keyPurposeIndex < _purposes.length; keyPurposeIndex++) {
                uint256 purpose = _purposes[keyPurposeIndex];

                if (purpose == _purpose) {
                    revert("Conflict: Key already has purpose");
                }
            }

            _keys[_key].purposes.push(_purpose);
        } else {
            _keys[_key].key = _key;
            _keys[_key].purposes = [_purpose];
            _keys[_key].keyType = _type;
        }

        _keysByPurpose[_purpose].push(_key);

        emit KeyAdded(_key, _purpose, _type);

        return true;
    }

    /**
     *  @dev See {IERC734-approve}.
     *  @notice Approves an execution.
     *  If the sender is an ACTION key and the destination address is not the identity contract itself, then the
     *  approval is authorized and the operation would be performed.
     *  If the destination address is the identity itself, then the execution would be authorized and performed only
     *  if the sender is a MANAGEMENT key.
     */
    function approve(uint256 _id, bool _approve)
    public
    delegatedOnly
    override
    returns (bool success)
    {
        require(_id < _executionNonce, "Cannot approve a non-existing execution");
        require(!_executions[_id].executed, "Request already executed");

        if(_executions[_id].to == address(this)) {
            require(keyHasPurpose(keccak256(abi.encode(msg.sender)), 1), "Sender does not have management key");
        }
        else {
            require(keyHasPurpose(keccak256(abi.encode(msg.sender)), 2), "Sender does not have action key");
        }

        emit Approved(_id, _approve);

        if (_approve == true) {
            _executions[_id].approved = true;

            // solhint-disable-next-line avoid-low-level-calls
            (success,) = _executions[_id].to.call{value:(_executions[_id].value)}(_executions[_id].data);

            if (success) {
                _executions[_id].executed = true;

                emit Executed(
                    _id,
                    _executions[_id].to,
                    _executions[_id].value,
                    _executions[_id].data
                );

                return true;
            } else {
                emit ExecutionFailed(
                    _id,
                    _executions[_id].to,
                    _executions[_id].value,
                    _executions[_id].data
                );

                return false;
            }
        } else {
            _executions[_id].approved = false;
        }
        return false;
    }

    /**
    * @dev See {IERC734-removeKey}.
    * @notice Remove the purpose from a key.
    */
    function removeKey(bytes32 _key, uint256 _purpose)
    public
    delegatedOnly
    onlyManager
    override
    returns (bool success)
    {
        require(_keys[_key].key == _key, "NonExisting: Key isn't registered");
        uint256[] memory _purposes = _keys[_key].purposes;

        uint purposeIndex = 0;
        while (_purposes[purposeIndex] != _purpose) {
            purposeIndex++;

            if (purposeIndex == _purposes.length) {
                revert("NonExisting: Key doesn't have such purpose");
            }
        }

        _purposes[purposeIndex] = _purposes[_purposes.length - 1];
        _keys[_key].purposes = _purposes;
        _keys[_key].purposes.pop();

        uint keyIndex = 0;
        uint arrayLength = _keysByPurpose[_purpose].length;

        while (_keysByPurpose[_purpose][keyIndex] != _key) {
            keyIndex++;

            if (keyIndex >= arrayLength) {
                break;
            }
        }

        _keysByPurpose[_purpose][keyIndex] = _keysByPurpose[_purpose][arrayLength - 1];
        _keysByPurpose[_purpose].pop();

        uint keyType = _keys[_key].keyType;

        if (_purposes.length - 1 == 0) {
            delete _keys[_key];
        }

        emit KeyRemoved(_key, _purpose, keyType);

        return true;
    }

    /**
    * @dev See {IERC735-addClaim}.
    * @notice Implementation of the addClaim function from the ERC-735 standard
    *  Require that the msg.sender has claim signer key.
    *
    * @param _topic The type of claim
    * @param _scheme The scheme with which this claim SHOULD be verified or how it should be processed.
    * @param _issuer The issuers identity contract address, or the address used to sign the above signature.
    * @param _signature Signature which is the proof that the claim issuer issued a claim of topic for this identity.
    * it MUST be a signed message of the following structure:
    * keccak256(abi.encode(address identityHolder_address, uint256 _ topic, bytes data))
    * @param _data The hash of the claim data, sitting in another
    * location, a bit-mask, call data, or actual data based on the claim scheme.
    * @param _uri The location of the claim, this can be HTTP links, swarm hashes, IPFS hashes, and such.
    *
    * @return claimRequestId Returns claimRequestId: COULD be
    * send to the approve function, to approve or reject this claim.
    * triggers ClaimAdded event.
    */
    function addClaim(
        uint256 _topic,
        uint256 _scheme,
        address _issuer,
        bytes memory _signature,
        bytes memory _data,
        string memory _uri
    )
    public
    delegatedOnly
    onlyClaimKey
    override
    returns (bytes32 claimRequestId)
    {
        if (_issuer != address(this)) {
            require(IClaimIssuer(_issuer).isClaimValid(IIdentity(address(this)), _topic, _signature, _data), "invalid claim");
        }

        bytes32 claimId = keccak256(abi.encode(_issuer, _topic));
        _claims[claimId].topic = _topic;
        _claims[claimId].scheme = _scheme;
        _claims[claimId].signature = _signature;
        _claims[claimId].data = _data;
        _claims[claimId].uri = _uri;

        if (_claims[claimId].issuer != _issuer) {
            _claimsByTopic[_topic].push(claimId);
            _claims[claimId].issuer = _issuer;

            emit ClaimAdded(claimId, _topic, _scheme, _issuer, _signature, _data, _uri);
        }
        else {
            emit ClaimChanged(claimId, _topic, _scheme, _issuer, _signature, _data, _uri);
        }
        return claimId;
    }

    /**
    * @dev See {IERC735-removeClaim}.
    * @notice Implementation of the removeClaim function from the ERC-735 standard
    * Require that the msg.sender has management key.
    * Can only be removed by the claim issuer, or the claim holder itself.
    *
    * @param _claimId The identity of the claim i.e. keccak256(abi.encode(_issuer, _topic))
    *
    * @return success Returns TRUE when the claim was removed.
    * triggers ClaimRemoved event
    */
    function removeClaim(bytes32 _claimId)
    public
    delegatedOnly
    onlyClaimKey
    override
    returns
    (bool success) {
        uint256 _topic = _claims[_claimId].topic;
        if (_topic == 0) {
            revert("NonExisting: There is no claim with this ID");
        }

        uint claimIndex = 0;
        uint arrayLength = _claimsByTopic[_topic].length;
        while (_claimsByTopic[_topic][claimIndex] != _claimId) {
            claimIndex++;

            if (claimIndex >= arrayLength) {
                break;
            }
        }

        _claimsByTopic[_topic][claimIndex] =
        _claimsByTopic[_topic][arrayLength - 1];
        _claimsByTopic[_topic].pop();

        emit ClaimRemoved(
            _claimId,
            _topic,
            _claims[_claimId].scheme,
            _claims[_claimId].issuer,
            _claims[_claimId].signature,
            _claims[_claimId].data,
            _claims[_claimId].uri
        );

        delete _claims[_claimId];

        return true;
    }

    /**
    * @dev See {IERC735-getClaim}.
    * @notice Implementation of the getClaim function from the ERC-735 standard.
    *
    * @param _claimId The identity of the claim i.e. keccak256(abi.encode(_issuer, _topic))
    *
    * @return topic Returns all the parameters of the claim for the
    * specified _claimId (topic, scheme, signature, issuer, data, uri) .
    * @return scheme Returns all the parameters of the claim for the
    * specified _claimId (topic, scheme, signature, issuer, data, uri) .
    * @return issuer Returns all the parameters of the claim for the
    * specified _claimId (topic, scheme, signature, issuer, data, uri) .
    * @return signature Returns all the parameters of the claim for the
    * specified _claimId (topic, scheme, signature, issuer, data, uri) .
    * @return data Returns all the parameters of the claim for the
    * specified _claimId (topic, scheme, signature, issuer, data, uri) .
    * @return uri Returns all the parameters of the claim for the
    * specified _claimId (topic, scheme, signature, issuer, data, uri) .
    */
    function getClaim(bytes32 _claimId)
    public
    override
    view
    returns(
        uint256 topic,
        uint256 scheme,
        address issuer,
        bytes memory signature,
        bytes memory data,
        string memory uri
    )
    {
        return (
        _claims[_claimId].topic,
        _claims[_claimId].scheme,
        _claims[_claimId].issuer,
        _claims[_claimId].signature,
        _claims[_claimId].data,
        _claims[_claimId].uri
        );
    }

    /**
    * @dev See {IERC734-keyHasPurpose}.
    * @notice Returns true if the key has MANAGEMENT purpose or the specified purpose.
    */
    function keyHasPurpose(bytes32 _key, uint256 _purpose)
    public
    override
    view
    returns(bool result)
    {
        Key memory key = _keys[_key];
        if (key.key == 0) return false;

        for (uint keyPurposeIndex = 0; keyPurposeIndex < key.purposes.length; keyPurposeIndex++) {
            uint256 purpose = key.purposes[keyPurposeIndex];

            if (purpose == 1 || purpose == _purpose) return true;
        }

        return false;
    }

    /**
     * @dev Checks if a claim is valid. Claims issued by the identity are self-attested claims. They do not have a
     * built-in revocation mechanism and are considered valid as long as their signature is valid and they are still
     * stored by the identity contract.
     * @param _identity the identity contract related to the claim
     * @param claimTopic the claim topic of the claim
     * @param sig the signature of the claim
     * @param data the data field of the claim
     * @return claimValid true if the claim is valid, false otherwise
     */
    function isClaimValid(
        IIdentity _identity,
        uint256 claimTopic,
        bytes memory sig,
        bytes memory data)
    public override virtual view returns (bool claimValid)
    {
        bytes32 dataHash = keccak256(abi.encode(_identity, claimTopic, data));
        // Use abi.encodePacked to concatenate the message prefix and the message to sign.
        bytes32 prefixedHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", dataHash));

        // Recover address of data signer
        address recovered = getRecoveredAddress(sig, prefixedHash);

        // Take hash of recovered address
        bytes32 hashedAddr = keccak256(abi.encode(recovered));

        // Does the trusted identifier have they key which signed the user's claim?
        //  && (isClaimRevoked(_claimId) == false)
        if (keyHasPurpose(hashedAddr, 3)) {
            return true;
        }

        return false;
    }

    /**
     * @dev returns the address that signed the given data
     * @param sig the signature of the data
     * @param dataHash the data that was signed
     * returns the address that signed dataHash and created the signature sig
     */
    function getRecoveredAddress(bytes memory sig, bytes32 dataHash)
    public
    pure
    returns (address addr)
    {
        bytes32 ra;
        bytes32 sa;
        uint8 va;

        // Check the signature length
        if (sig.length != 65) {
            return address(0);
        }

        // Divide the signature in r, s and v variables
        // solhint-disable-next-line no-inline-assembly
        assembly {
            ra := mload(add(sig, 32))
            sa := mload(add(sig, 64))
            va := byte(0, mload(add(sig, 96)))
        }

        if (va < 27) {
            va += 27;
        }

        address recoveredAddress = ecrecover(dataHash, va, ra, sa);

        return (recoveredAddress);
    }

    /**
     * @notice Initializer internal function for the Identity contract.
     *
     * @param initialManagementKey The ethereum address to be set as the management key of the ONCHAINID.
     */
    // solhint-disable-next-line func-name-mixedcase
    function __Identity_init(address initialManagementKey) internal {
        require(!_initialized || _isConstructor(), "Initial key was already setup.");
        _initialized = true;
        _canInteract = true;

        bytes32 _key = keccak256(abi.encode(initialManagementKey));
        _keys[_key].key = _key;
        _keys[_key].purposes = [1];
        _keys[_key].keyType = 1;
        _keysByPurpose[1].push(_key);
        emit KeyAdded(_key, 1, 1);
    }

    /**
     * @notice Computes if the context in which the function is called is a constructor or not.
     *
     * @return true if the context is a constructor.
     */
    function _isConstructor() private view returns (bool) {
        address self = address(this);
        uint256 cs;
        // solhint-disable-next-line no-inline-assembly
        assembly { cs := extcodesize(self) }
        return cs == 0;
    }
}

構造体

Key

solidity
struct Key {
    uint256[] purposes;
    uint256 keyType;
    bytes32 key;
}

IDに登録されるキーの情報を保持する構造体。 ERC734標準に基づき、キーの役割(目的)、種類、キー本体を定義します。

フィールド

  • purposes
    • このキーが持つ目的(役割)を示す番号の配列。(例: 1 = 管理, 2 = 実行, 3 = クレーム署名)
  • keyType
    • キーの暗号アルゴリズムの種類を示す番号。(例: 1 = ECDSA, 2 = RSA)
  • key
    • キー本体。
    • 通常はウォレットアドレスをkeccak256でハッシュ化したbytes32の値。

Execution

solidity
struct Execution {
    address to;
    uint256 value;
    bytes data;
    bool approved;
    bool executed;
}

execute関数によって要求されたトランザクション実行の情報を保持する構造体。 IDが他のコントラクトを呼び出す時の、トランザクションの詳細と現在のステータス(承認済みか、実行済みか)を管理します。

フィールド

  • to
    • 呼び出し先のコントラクトアドレス。
  • value
    • 送信するETHの数量。
  • data
    • トランザクションのコールデータ。
  • approved
    • この実行要求が承認されたかどうか。
  • executed
    • この実行要求が既に実行されたかどうか。

Claim

solidity
struct Claim {
    uint256 topic;
    uint256 scheme;
    address issuer;
    bytes signature;
    bytes data;
    string uri;
}

IDに記録されるクレーム(資格証明)の情報を保持する構造体。 ERC735標準に基づき、クレームの種類、発行者、署名、データ本体など、資格証明を構成する全ての要素を定義します。

フィールド

  • topic
    • クレームの種類を示す番号。
  • scheme
    • 署名や検証の方式を示す番号。
  • issuer
    • このクレームを発行した機関のアドレス。
  • signature
    • このクレームが本物であることを証明する発行者のデジタル署名。
  • data
    • クレームの具体的な内容(通常はハッシュ値)。
  • uri
    • クレームに関する追加情報が格納されているオフチェーンの場所を示すURI。

変数

_executionNonce

solidity
uint256 internal _executionNonce;

execute関数で生成される実行要求IDをインクリメンタルに採番するためのカウンター。

_keys

solidity
mapping(bytes32 => Key) internal _keys;

キーのハッシュ値(bytes32)をキーとして、そのキーの詳細情報(Key構造体)を記録するmapping。

_keysByPurpose

solidity
mapping(uint256 => bytes32[]) internal _keysByPurpose;

キーの目的(uint256)をキーとして、その目的を持つキーのハッシュ値の配列を記録するmapping。 特定の役割を持つキーを効率的に検索するために使用されます。

_executions

solidity
mapping(uint256 => Execution) internal _executions;

実行要求ID(uint256)をキーとして、その実行要求の詳細情報(Execution構造体)を記録するmapping。

_claims

solidity
mapping(bytes32 => Claim) internal _claims;

クレームID(bytes32)をキーとして、そのクレームの詳細情報(Claim構造体)を記録するmapping。

_claimsByTopic

solidity
mapping(uint256 => bytes32[]) internal _claimsByTopic;

クレームのトピック(uint256)をキーとして、そのトピックに属するクレームIDの配列を記録するmapping。 特定の種類のクレームを効率的に検索するために使用されます。

_initialized

solidity
bool internal _initialized = false;

このIDコントラクトがinitialize関数またはコンストラクタで初期化済みかどうかを示すフラグ。 二重初期化を防ぎます。

_canInteract

solidity
bool internal _canInteract = false;

このコントラクトが実装(ライブラリ)としてではなく、プロキシを通じて正しく呼び出されているかを示すフラグ。 delegatedOnly修飾子で使用され、実装コントラクトへの直接のコールを防ぎます。

Modifier

delegatedOnly

solidity
modifier delegatedOnly() {
    require(_canInteract == true, "Interacting with the library contract is forbidden.");
    _;
}

実装コントラクトへの直接の呼び出しを禁止する修飾子。 この修飾子が付けられた関数は、_canInteractフラグがtrueの場合にのみ実行可能です。 このフラグは初期化時に設定されるため、プロキシ経由でのdelegatecallによって正しく初期化されたインスタンスでのみ関数が実行されることを保証します。

onlyManager

solidity
modifier onlyManager() {
    require(msg.sender == address(this) || keyHasPurpose(keccak256(abi.encode(msg.sender)), 1)
    , "Permissions: Sender does not have management key");
    _;
}

関数の呼び出し元が管理キー(Management Key)を持つことを要求する修飾子。 呼び出し元(msg.sender)が、このIDコントラクト自身であるか、または目的番号1(管理キー)を持つキーとして登録されている場合にのみ、関数の実行を許可します。

onlyClaimKey

solidity
modifier onlyClaimKey() {
    require(msg.sender == address(this) || keyHasPurpose(keccak256(abi.encode(msg.sender)), 3)
    , "Permissions: Sender does not have claim signer key");
    _;
}

関数の呼び出し元がクレーム署名者キー(Claim Signer Key)を持つことを要求する修飾子。 呼び出し元(msg.sender)が、このIDコントラクト自身であるか、または目的番号3(クレーム署名者キー)を持つキーとして登録されている場合にのみ、関数の実行を許可します。

関数

initialize

solidity
function initialize(address initialManagementKey) external {
    require(initialManagementKey != address(0), "invalid argument - zero address");
    __Identity_init(initialManagementKey);
}

プロキシコントラクトの初期設定を行う初期化関数。 このコントラクトがプロキシの実装として使用される時に、delegatecallを通じて一度だけ呼び出されることを想定しています。 内部で__Identity_initを呼び出し、最初の管理キー(Management Key)を設定します。

引数

  • initialManagementKey
    • 最初に管理キーとして設定するウォレットアドレス。

execute

solidity
function execute(address _to, uint256 _value, bytes memory _data)
external
delegatedOnly
override
payable
returns (uint256 executionId)
{
    uint256 _executionId = _executionNonce;
    _executions[_executionId].to = _to;
    _executions[_executionId].value = _value;
    _executions[_executionId].data = _data;
    _executionNonce++;

    emit ExecutionRequested(_executionId, _to, _value, _data);

    if (keyHasPurpose(keccak256(abi.encode(msg.sender)), 1)) {
        approve(_executionId, true);
    }
    else if (_to != address(this) && keyHasPurpose(keccak256(abi.encode(msg.sender)), 2)){
        approve(_executionId, true);
    }

    return _executionId;
}

このIDとして、他のコントラクトの呼び出しや送金といったトランザクション実行を要求する関数。 delegatedOnly修飾子により、プロキシ経由でのみ呼び出し可能です。 まず、実行要求を作成し、_executionsマッピングに保存します。 その後、呼び出し元が管理キー(purpose 1)を持つ場合、または、呼び出し先がIDコントラクト自身でなく、かつ呼び出し元が実行キー(purpose 2)を持つ場合は、即座にその実行要求を自動承認(approve)します。 それ以外の場合は、別途approve関数による承認が必要です。

引数

  • _to
    • トランザクションの宛先コントラクトアドレス。
  • _value
    • 送信するETHの数量。
  • _data
    • 他のコントラクトを呼び出す際のコールデータ。

戻り値

  • executionId
    • 生成された実行要求のID (uint256)。

getKey

solidity
function getKey(bytes32 _key)
external
override
view
returns(uint256[] memory purposes, uint256 keyType, bytes32 key)
{
    return (_keys[_key].purposes, _keys[_key].keyType, _keys[_key].key);
}

指定されたキーの詳細情報を取得する関数。 _keysマッピングから、指定されたキー(_key)に紐づくKey構造体の全フィールド(目的、キータイプ、キー本体)を返します。

引数

  • _key
    • 情報を取得したいキーのハッシュ値 (bytes32)。

戻り値

  • purposes
    • キーに紐づく目的の配列 (uint256[])。
  • keyType
    • キーの種類 (uint256)。
  • key
    • キー本体のハッシュ値 (bytes32)。

getKeyPurposes

solidity
function getKeyPurposes(bytes32 _key)
external
override
view
returns(uint256[] memory _purposes)
{
    return (_keys[_key].purposes);
}

指定されたキーが持つ全ての目的(役割)のリストを取得する関数。 _keysマッピングから、指定されたキー(_key)に紐づくpurposes配列を返します。

引数

  • _key
    • 目的のリストを取得したいキーのハッシュ値 (bytes32)。

戻り値

  • _purposes
    • キーに紐づく目的の配列 (uint256[])。

getKeysByPurpose

solidity
function getKeysByPurpose(uint256 _purpose)
external
override
view
returns(bytes32[] memory keys)
{
    return _keysByPurpose[_purpose];
}

特定の目的に紐づく全てのキーのリストを取得する関数。 _keysByPurposeマッピングから、指定された目的(_purpose)に紐づくキーのハッシュ値の配列を返します。

引数

  • _purpose
    • 検索したい目的の番号 (uint256)。

戻り値

  • keys
    • 指定された目的を持つキーのハッシュ値の配列 (bytes32[])。

getClaimIdsByTopic

solidity
function getClaimIdsByTopic(uint256 _topic)
external
override
view
returns(bytes32[] memory claimIds)
{
    return _claimsByTopic[_topic];
}

特定のトピックに紐づく全てのクレームIDのリストを取得する関数。 _claimsByTopicマッピングから、指定されたトピック(_topic)に紐づくクレームIDの配列を返します。

引数

  • _topic
    • 検索したいクレームのトピック番号 (uint256)。

戻り値

  • claimIds
    • 指定されたトピックを持つクレームIDの配列 (bytes32[])。

addKey

solidity
function addKey(bytes32 _key, uint256 _purpose, uint256 _type)
public
delegatedOnly
onlyManager
override
returns (bool success)
{
    if (_keys[_key].key == _key) {
        uint256[] memory _purposes = _keys[_key].purposes;
        for (uint keyPurposeIndex = 0; keyPurposeIndex < _purposes.length; keyPurposeIndex++) {
            uint256 purpose = _purposes[keyPurposeIndex];

            if (purpose == _purpose) {
                revert("Conflict: Key already has purpose");
            }
        }

        _keys[_key].purposes.push(_purpose);
    } else {
        _keys[_key].key = _key;
        _keys[_key].purposes = [_purpose];
        _keys[_key].keyType = _type;
    }

    _keysByPurpose[_purpose].push(_key);

    emit KeyAdded(_key, _purpose, _type);

    return true;
}

IDに新しいキー(操作権限)を追加する関数。 onlyManager修飾子により、管理キーを持つアドレスのみが呼び出し可能です。 指定されたキーが既に存在する場合は、新しい目的を追加します。 キーがまだ存在しない場合は、新しいキーとして情報を登録します。 同じキーに同じ目的を重複して追加することはできません。

引数

  • _key
    • 追加するキーのハッシュ値 (bytes32)。
  • _purpose
    • キーに割り当てる目的の番号 (uint256)。
  • _type
    • キーの種類を示す番号 (uint256)。

戻り値

  • success
    • キーの追加が成功したことを示すtrue (bool)。

approve

solidity
function approve(uint256 _id, bool _approve)
public
delegatedOnly
override
returns (bool success)
{
    require(_id < _executionNonce, "Cannot approve a non-existing execution");
    require(!_executions[_id].executed, "Request already executed");

    if(_executions[_id].to == address(this)) {
        require(keyHasPurpose(keccak256(abi.encode(msg.sender)), 1), "Sender does not have management key");
    }
    else {
        require(keyHasPurpose(keccak256(abi.encode(msg.sender)), 2), "Sender does not have action key");
    }

    emit Approved(_id, _approve);

    if (_approve == true) {
        _executions[_id].approved = true;

        // solhint-disable-next-line avoid-low-level-calls
        (success,) = _executions[_id].to.call{value:(_executions[_id].value)}(_executions[_id].data);

        if (success) {
            _executions[_id].executed = true;

            emit Executed(
                _id,
                _executions[_id].to,
                _executions[_id].value,
                _executions[_id].data
            );

            return true;
        } else {
            emit ExecutionFailed(
                _id,
                _executions[_id].to,
                _executions[_id].value,
                _executions[_id].data
            );

            return false;
        }
    } else {
        _executions[_id].approved = false;
    }
    return false;
}

execute関数によって作成された実行要求を承認または拒否し、承認した場合は即座に実行する関数。 delegatedOnly修飾子により、プロキシ経由でのみ呼び出し可能です。 まず、対象の実行要求が存在し、まだ実行されていないことを確認します。 次に、呼び出し元の権限をチェックします。要求の宛先がID自身の場合は管理キー(purpose 1)が、それ以外の場合は実行キー(purpose 2)が必要です。 _approveがtrueの場合、トランザクションをcallで実行し、成功すればExecutedイベントを、失敗すればExecutionFailedイベントを発行します。

引数

  • _id
    • 承認対象の実行要求ID (uint256)。
  • _approve
    • 承認する場合はtrue、拒否する場合はfalse (bool)。

戻り値

  • success
    • トランザクションの実行が成功したかどうかを示すtrueまたはfalse (bool)。

removeKey

solidity
function removeKey(bytes32 _key, uint256 _purpose)
public
delegatedOnly
onlyManager
override
returns (bool success)
{
    require(_keys[_key].key == _key, "NonExisting: Key isn't registered");
    uint256[] memory _purposes = _keys[_key].purposes;

    uint purposeIndex = 0;
    while (_purposes[purposeIndex] != _purpose) {
        purposeIndex++;

        if (purposeIndex == _purposes.length) {
            revert("NonExisting: Key doesn't have such purpose");
        }
    }

    _purposes[purposeIndex] = _purposes[_purposes.length - 1];
    _keys[_key].purposes = _purposes;
    _keys[_key].purposes.pop();

    uint keyIndex = 0;
    uint arrayLength = _keysByPurpose[_purpose].length;

    while (_keysByPurpose[_purpose][keyIndex] != _key) {
        keyIndex++;

        if (keyIndex >= arrayLength) {
            break;
        }
    }

    _keysByPurpose[_purpose][keyIndex] = _keysByPurpose[_purpose][arrayLength - 1];
    _keysByPurpose[_purpose].pop();

    uint keyType = _keys[_key].keyType;

    if (_purposes.length - 1 == 0) {
        delete _keys[_key];
    }

    emit KeyRemoved(_key, _purpose, keyType);

    return true;
}

IDに登録されているキーから、特定の目的(役割)を削除する関数。 onlyManager修飾子により、管理キーを持つアドレスのみが呼び出し可能です。 まず、指定されたキーが存在し、かつそのキーが指定された目的を持っていることを確認します。 その後、_keysと_keysByPurposeの両方から該当する情報を削除します。 もしそのキーに紐づく目的がなくなった場合は、キー情報自体を_keysから完全に削除します。

引数

  • _key
    • 削除対象のキーのハッシュ値 (bytes32)。
  • _purpose
    • 削除するキーの目的の番号 (uint256)。

戻り値

  • success
    • キーの目的削除が成功したことを示すtrue (bool)。

addClaim

solidity
function addClaim(
    uint256 _topic,
    uint256 _scheme,
    address _issuer,
    bytes memory _signature,
    bytes memory _data,
    string memory _uri
)
public
delegatedOnly
onlyClaimKey
override
returns (bytes32 claimRequestId)
{
    if (_issuer != address(this)) {
        require(IClaimIssuer(_issuer).isClaimValid(IIdentity(address(this)), _topic, _signature, _data), "invalid claim");
    }

    bytes32 claimId = keccak256(abi.encode(_issuer, _topic));
    _claims[claimId].topic = _topic;
    _claims[claimId].scheme = _scheme;
    _claims[claimId].signature = _signature;
    _claims[claimId].data = _data;
    _claims[claimId].uri = _uri;

    if (_claims[claimId].issuer != _issuer) {
        _claimsByTopic[_topic].push(claimId);
        _claims[claimId].issuer = _issuer;

        emit ClaimAdded(claimId, _topic, _scheme, _issuer, _signature, _data, _uri);
    }
    else {
        emit ClaimChanged(claimId, _topic, _scheme, _issuer, _signature, _data, _uri);
    }
    return claimId;
}

IDに新しいクレーム(資格証明)を追加または更新する関数。 onlyClaimKey修飾子により、ID所有者から事前に許可されたクレーム発行者のみが呼び出し可能です。 発行者がID自身でない場合、発行者のコントラクトが持つisClaimValidを呼び出して、署名の有効性を検証します。 クレームIDは発行者アドレスとトピックから計算され、そのIDをキーとしてクレーム情報を_claimsマッピングに保存します。 新しいクレームの場合はClaimAddedイベントを、既存のクレームの更新の場合はClaimChangedイベントを発行します。

引数

  • _topic
    • クレームの種類を示す番号 (uint256)。
  • _scheme
    • 署名や検証の方式を示す番号 (uint256)。
  • _issuer
    • クレーム発行者のアドレス (address)。
  • _signature
    • 発行者のデジタル署名 (bytes)。
  • _data
    • クレームの具体的な内容 (bytes)。
  • _uri
    • オフチェーンの情報へのURI (string)。

戻り値

  • claimRequestId
    • 生成または更新されたクレームのID (bytes32)。

removeClaim

solidity
function removeClaim(bytes32 _claimId)
public
delegatedOnly
onlyClaimKey
override
returns
(bool success) {
    uint256 _topic = _claims[_claimId].topic;
    if (_topic == 0) {
        revert("NonExisting: There is no claim with this ID");
    }

    uint claimIndex = 0;
    uint arrayLength = _claimsByTopic[_topic].length;
    while (_claimsByTopic[_topic][claimIndex] != _claimId) {
        claimIndex++;

        if (claimIndex >= arrayLength) {
            break;
        }
    }

    _claimsByTopic[_topic][claimIndex] =
    _claimsByTopic[_topic][arrayLength - 1];
    _claimsByTopic[_topic].pop();

    emit ClaimRemoved(
        _claimId,
        _topic,
        _claims[_claimId].scheme,
        _claims[_claimId].issuer,
        _claims[_claimId].signature,
        _claims[_claimId].data,
        _claims[_claimId].uri
    );

    delete _claims[_claimId];

    return true;
}

IDからクレームを削除する関数。 onlyClaimKey修飾子により、クレーム発行者や管理キーを持つアドレスなど、許可されたアドレスのみが呼び出し可能です。 指定されたクレームIDが存在することを確認後、_claimsByTopicと_claimsの両方のマッピングから該当する情報を削除します。

引数

  • _claimId
    • 削除したいクレームのID (bytes32)。

戻り値

  • success
    • クレームの削除が成功したことを示すtrue (bool)。

getClaim

solidity
function getClaim(bytes32 _claimId)
public
override
view
returns(
    uint256 topic,
    uint256 scheme,
    address issuer,
    bytes memory signature,
    bytes memory data,
    string memory uri
)
{
    return (
    _claims[_claimId].topic,
    _claims[_claimId].scheme,
    _claims[_claimId].issuer,
    _claims[_claimId].signature,
    _claims[_claimId].data,
    _claims[_claimId].uri
    );
}

指定されたクレームIDの詳細情報を取得する関数。 _claimsマッピングから、指定されたクレームID(_claimId)に紐づくClaim構造体の全フィールドを返します。

引数

  • _claimId
    • 情報を取得したいクレームのID (bytes32)。

戻り値

  • topic, scheme, issuer, signature, data, uri
    • クレームを構成する全てのデータ。

keyHasPurpose

solidity
function keyHasPurpose(bytes32 _key, uint256 _purpose)
public
override
view
returns(bool result)
{
    Key memory key = _keys[_key];
    if (key.key == 0) return false;

    for (uint keyPurposeIndex = 0; keyPurposeIndex < key.purposes.length; keyPurposeIndex++) {
        uint256 purpose = key.purposes[keyPurposeIndex];

        if (purpose == 1 || purpose == _purpose) return true;
    }

    return false;
}

特定のキーが特定の目的(役割)を持っているかを確認する関数。 指定されたキー(_key)が存在するかを確認し、そのキーのpurposes配列に、指定された目的(_purpose)または管理キーの目的(purpose 1)が含まれているかをチェックします。 管理キーは全ての権限を持つため、常にtrueを返します。

引数

  • _key
    • 確認したいキーのハッシュ値 (bytes32)。
  • _purpose
    • 確認したい目的の番号 (uint256)。

戻り値

  • result
    • 目的を持っている場合はtrue、持っていない場合はfalse (bool)。

isClaimValid

solidity
function isClaimValid(
    IIdentity _identity,
    uint256 claimTopic,
    bytes memory sig,
    bytes memory data)
public override virtual view returns (bool claimValid)
{
    bytes32 dataHash = keccak256(abi.encode(_identity, claimTopic, data));
    // Use abi.encodePacked to concatenate the message prefix and the message to sign.
    bytes32 prefixedHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", dataHash));

    // Recover address of data signer
    address recovered = getRecoveredAddress(sig, prefixedHash);

    // Take hash of recovered address
    bytes32 hashedAddr = keccak256(abi.encode(recovered));

    // Does the trusted identifier have they key which signed the user's claim?
    //  && (isClaimRevoked(_claimId) == false)
    if (keyHasPurpose(hashedAddr, 3)) {
        return true;
    }

    return false;
}

与えられた署名が、このIDにとって有効なクレーム署名であるかを検証する関数。 この関数は、主にクレーム発行者のコントラクトから呼び出されることを想定しています。 まず、署名対象となるメッセージのハッシュ値を、イーサリアムの標準的な署名検証フォーマット(\x19Ethereum Signed Message...)に従って再計算します。 次に、ecrecoverを用いて署名から署名者のアドレスを復元し、そのアドレスがこのIDコントラクトにクレーム署名者キー(purpose 3)として登録されているかをkeyHasPurposeで確認します。

引数

  • _identity
    • クレームの対象となるIDのコントラクトアドレス (IIdentity)。
  • claimTopic
    • クレームのトピック番号 (uint256)。
  • sig
    • 検証対象のデジタル署名 (bytes)。
  • data
    • 署名された元のデータ (bytes)。

戻り値

  • claimValid
    • 署名が有効な場合はtrue、無効な場合はfalse (bool)。

getRecoveredAddress

solidity
function getRecoveredAddress(bytes memory sig, bytes32 dataHash)
public
pure
returns (address addr)
{
    bytes32 ra;
    bytes32 sa;
    uint8 va;

    // Check the signature length
    if (sig.length != 65) {
        return address(0);
    }

    // Divide the signature in r, s and v variables
    // solhint-disable-next-line no-inline-assembly
    assembly {
        ra := mload(add(sig, 32))
        sa := mload(add(sig, 64))
        va := byte(0, mload(add(sig, 96)))
    }

    if (va < 27) {
        va += 27;
    }

    address recoveredAddress = ecrecover(dataHash, va, ra, sa);

    return (recoveredAddress);
}

与えられた署名とハッシュ値から、署名を行ったアドレスを復元するヘルパー関数。 標準的なecrecoverのプリコンパイルコントラクトを呼び出すためのラッパー関数です。65バイトの署名データをr, s, vの3つの要素に分解し、ecrecoverに渡して署名者のアドレスを計算し、返します。

引数

  • sig
    • 65バイトのECDSA署名 (bytes)。
  • dataHash
    • 署名対象となったデータのハッシュ値 (bytes32)。

戻り値

  • addr
    • 復元された署名者のアドレス (address)。