Skip to main content

Pseudo-introspection Registry Contract

Status: Final
Requires: CIP-165

A universal registry smart contract where any address (contract or regular account) can register which interface it supports and which smart contract is responsible for its implementation. This standard keeps backward compatibility with CBC-165.

Abstract

This standard defines a registry where smart contracts and regular accounts can publish which functionality they implement---either directly or through a proxy contract.

Anyone can query this registry to ask if a specific address implements a given interface and which smart contract handles its implementation.

This registry MAY be deployed on any Core network. Its network-specific ICAN address MUST be published for every deployment.

Interfaces with zeroes (0) as the last 28 bytes are considered CBC-165 interfaces, and this registry SHALL forward the call to the contract to see if it implements the interface.

This contract also acts as an CBC-165 cache to reduce energy consumption.

Motivation

Earlier pseudo-introspection approaches include CBC-165, which cannot be used by regular accounts, and reverse-name registries, which add complexity and depend on registry governance.

This standard provides a simpler common lookup mechanism for contracts and regular accounts. Clients resolve the registry through its published network-specific Core address.

Specification

CBC-1820 Registry Smart Contract

This is the normative reference implementation of the CBC-1820 registry smart contract.

/* CBC1820 Pseudo-introspection Registry Contract
* This standard defines a universal registry smart contract where any address (contract or regular account) can
* register which interface it supports and which smart contract is responsible for its implementation.
*
* Written in 2019 by Jordi Baylina and Jacques Dafflon
*
* To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to
* this software to the public domain worldwide. This software is distributed without any warranty.
*
* You should have received a copy of the CC0 Public Domain Dedication along with this software.
*/
pragma solidity ^1.1.2;

/// @dev The interface a contract MUST implement if it is the implementer of
/// some (other) interface for any address other than itself.
interface CBC1820ImplementerInterface {
/// @notice Indicates whether the contract implements the interface 'interfaceHash' for the address 'addr' or not.
/// @param interfaceHash keccak256 hash of the name of the interface
/// @param addr Address for which the contract will implement the interface
/// @return CBC1820_ACCEPT_MAGIC only if the contract implements 'interfaceHash' for the address 'addr'.
function canImplementInterfaceForAddress(bytes32 interfaceHash, address addr) external view returns(bytes32);
}


/// @title CBC1820 Pseudo-introspection Registry Contract
/// @author Jordi Baylina and Jacques Dafflon
/// @notice This contract is the official implementation of the CBC1820 Registry.
contract CBC1820Registry {
/// @notice CBC165 Invalid ID.
bytes4 constant internal INVALID_ID = 0xffffffff;
/// @notice Method ID for the CBC165 supportsInterface method (= `bytes4(keccak256('supportsInterface(bytes4)'))`).
bytes4 constant internal CBC165ID = 0x80ada41b;
/// @notice Magic value which is returned if a contract implements an interface on behalf of some other address.
bytes32 constant internal CBC1820_ACCEPT_MAGIC = keccak256(abi.encodePacked("CBC1820_ACCEPT_MAGIC"));

/// @notice mapping from addresses and interface hashes to their implementers.
mapping(address => mapping(bytes32 => address)) internal interfaces;
/// @notice mapping from addresses to their manager.
mapping(address => address) internal managers;
/// @notice flag for each address and CBC165 interface to indicate if it is cached.
mapping(address => mapping(bytes4 => bool)) internal cbc165Cached;

/// @notice Indicates a contract is the 'implementer' of 'interfaceHash' for 'addr'.
event InterfaceImplementerSet(address indexed addr, bytes32 indexed interfaceHash, address indexed implementer);
/// @notice Indicates 'newManager' is the address of the new manager for 'addr'.
event ManagerChanged(address indexed addr, address indexed newManager);

/// @notice Query if an address implements an interface and through which contract.
/// @param _addr Address being queried for the implementer of an interface.
/// (If '_addr' is the zero address then 'msg.sender' is assumed.)
/// @param _interfaceHash Core SHA3-256 hash of the name of the interface as a string.
/// E.g., 'web3.utils.keccak256("CBC777TokensRecipient")' for the 'CBC777TokensRecipient' interface.
/// @return The address of the contract which implements the interface '_interfaceHash' for '_addr'
/// or '0' if '_addr' did not register an implementer for this interface.
function getInterfaceImplementer(address _addr, bytes32 _interfaceHash) external view returns (address) {
address addr = _addr == address(0) ? msg.sender : _addr;
if (isCBC165Interface(_interfaceHash)) {
bytes4 cbc165InterfaceHash = bytes4(_interfaceHash);
return implementsCBC165Interface(addr, cbc165InterfaceHash) ? addr : address(0);
}
return interfaces[addr][_interfaceHash];
}

/// @notice Sets the contract which implements a specific interface for an address.
/// Only the manager defined for that address can set it.
/// (Each address is the manager for itself until it sets a new manager.)
/// @param _addr Address for which to set the interface.
/// (If '_addr' is the zero address then 'msg.sender' is assumed.)
/// @param _interfaceHash Core SHA3-256 hash of the name of the interface as a string.
/// E.g., 'web3.utils.keccak256("CBC777TokensRecipient")' for the 'CBC777TokensRecipient' interface.
/// @param _implementer Contract address implementing '_interfaceHash' for '_addr'.
function setInterfaceImplementer(address _addr, bytes32 _interfaceHash, address _implementer) external {
address addr = _addr == address(0) ? msg.sender : _addr;
require(getManager(addr) == msg.sender, "Not the manager");

require(!isCBC165Interface(_interfaceHash), "Must not be an CBC165 hash");
if (_implementer != address(0) && _implementer != msg.sender) {
require(
CBC1820ImplementerInterface(_implementer)
.canImplementInterfaceForAddress(_interfaceHash, addr) == CBC1820_ACCEPT_MAGIC,
"Does not implement the interface"
);
}
interfaces[addr][_interfaceHash] = _implementer;
emit InterfaceImplementerSet(addr, _interfaceHash, _implementer);
}

/// @notice Sets '_newManager' as manager for '_addr'.
/// The new manager will be able to call 'setInterfaceImplementer' for '_addr'.
/// @param _addr Address for which to set the new manager.
/// @param _newManager Address of the new manager for 'addr'. (Pass '0x0' to reset the manager to '_addr'.)
function setManager(address _addr, address _newManager) external {
require(getManager(_addr) == msg.sender, "Not the manager");
managers[_addr] = _newManager == _addr ? address(0) : _newManager;
emit ManagerChanged(_addr, _newManager);
}

/// @notice Get the manager of an address.
/// @param _addr Address for which to return the manager.
/// @return Address of the manager for a given address.
function getManager(address _addr) public view returns(address) {
// By default the manager of an address is the same address
if (managers[_addr] == address(0)) {
return _addr;
} else {
return managers[_addr];
}
}

/// @notice Compute the keccak256 hash of an interface given its name.
/// @param _interfaceName Name of the interface.
/// @return The keccak256 hash of an interface name.
function interfaceHash(string calldata _interfaceName) external pure returns(bytes32) {
return keccak256(abi.encodePacked(_interfaceName));
}

/* --- CBC165 Related Functions --- */
/* --- Developed in collaboration with William Entriken. --- */

/// @notice Updates the cache with whether the contract implements an CBC165 interface or not.
/// @param _contract Address of the contract for which to update the cache.
/// @param _interfaceId CBC165 interface for which to update the cache.
function updateCBC165Cache(address _contract, bytes4 _interfaceId) external {
interfaces[_contract][_interfaceId] = implementsCBC165InterfaceNoCache(
_contract, _interfaceId) ? _contract : address(0);
cbc165Cached[_contract][_interfaceId] = true;
}

/// @notice Checks whether a contract implements an CBC165 interface or not.
// If the result is not cached a direct lookup on the contract address is performed.
// If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling
// 'updateCBC165Cache' with the contract address.
/// @param _contract Address of the contract to check.
/// @param _interfaceId CBC165 interface to check.
/// @return True if '_contract' implements '_interfaceId', false otherwise.
function implementsCBC165Interface(address _contract, bytes4 _interfaceId) public view returns (bool) {
if (!cbc165Cached[_contract][_interfaceId]) {
return implementsCBC165InterfaceNoCache(_contract, _interfaceId);
}
return interfaces[_contract][_interfaceId] == _contract;
}

/// @notice Checks whether a contract implements an CBC165 interface or not without using nor updating the cache.
/// @param _contract Address of the contract to check.
/// @param _interfaceId CBC165 interface to check.
/// @return True if '_contract' implements '_interfaceId', false otherwise.
function implementsCBC165InterfaceNoCache(address _contract, bytes4 _interfaceId) public view returns (bool) {
uint256 success;
uint256 result;

(success, result) = noThrowCall(_contract, CBC165ID);
if (success == 0 || result == 0) {
return false;
}

(success, result) = noThrowCall(_contract, INVALID_ID);
if (success == 0 || result != 0) {
return false;
}

(success, result) = noThrowCall(_contract, _interfaceId);
if (success == 1 && result == 1) {
return true;
}
return false;
}

/// @notice Checks whether the hash is a CBC165 interface (ending with 28 zeroes) or not.
/// @param _interfaceHash The hash to check.
/// @return True if '_interfaceHash' is an CBC165 interface (ending with 28 zeroes), false otherwise.
function isCBC165Interface(bytes32 _interfaceHash) internal pure returns (bool) {
return _interfaceHash & 0x00000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0;
}

/// @dev Make a call on a contract without throwing if the function does not exist.
function noThrowCall(address _contract, bytes4 _interfaceId)
internal view returns (uint256 success, uint256 result)
{
bytes4 cbc165ID = CBC165ID;

assembly {
let x := mload(0x40) // Find empty storage location using "free memory pointer"
mstore(x, cbc165ID) // Place signature at beginning of empty storage
mstore(add(x, 0x04), _interfaceId) // Place first argument directly next to signature

success := staticcall(
30000, // 30k energy
_contract, // To addr
x, // Inputs are stored at location x
0x24, // Inputs are 36 (4 + 32) bytes long
x, // Store output over input (saves space)
0x20 // Outputs are 32 bytes long
)

result := mload(x) // Load the result
}
}
}

Deployment Method

The Ethereum ERC-1820 deployment transaction and Nick's method based on recoverable ECDSA signatures cannot be reused on Core Blockchain. Core transactions use a 171-byte Ed448 signature blob that includes the public key, so the original sender-recovery construction does not apply.

The CBC-1820 registry MUST be deployed separately on each Core network from the Ylem source in this specification. A canonical deployment MUST:

  1. Compile the registry with Ylem ^1.1.2.
  2. Use the Core transaction format, the target networkId, and an address with the matching network prefix.
  3. Fund the deployment account with enough XCB to cover the current energyPrice and deployment energyLimit; this standard does not prescribe a fixed amount.
  4. Publish the verified runtime bytecode, deployment transaction hash, and registry ICAN address for that network.

Until canonical deployments are published, clients MUST treat the registry address as network configuration and MUST NOT assume that one address is valid across all Core networks.

Registry Contract Address

No canonical CBC-1820 registry address or Core deployment transaction is currently specified by this document. These values MUST be added for each supported Core network before the registry can be relied upon as shared infrastructure.

Compiler metadata and deployment bytecode are not embedded in this document. Canonical artifacts MUST be generated from the Ylem source above and published with each network deployment.

Interface Name

Any interface name is hashed using keccak256 and sent to getInterfaceImplementer().

If the interface is part of a standard, it is best practice to explicitly state the interface name and link to this published CBC-1820 such that other people don't have to come here to look up these rules.

For convenience, the registry provides a function to compute the hash on-chain:

function interfaceHash(string _interfaceName) public pure returns(bytes32)

Compute the keccak256 hash of an interface given its name.

identifier: 408aa674 parameters _interfaceName: Name of the interface. returns: The keccak256 hash of an interface name.

Approved CBCs

If the interface is part of an approved CBC, it MUST be named CBC###XXXXX where ### is the number of the CBC and XXXXX should be the name of the interface in CamelCase. The meaning of this interface SHOULD be defined in the specified CBC.

Examples:

  • keccak256("CBC20Token")
  • keccak256("CBC777Token")
  • keccak256("CBC777TokensSender")
  • keccak256("CBC777TokensRecipient")

CBC-165 Compatible Interfaces

The compatibility with CBC-165, including the CBC-165 Cache, has been designed and developed with William Entriken.

Any interface where the last 28 bytes are zeroes (0) SHALL be considered an CBC-165 interface.

CBC-165 Lookup

Anyone can explicitly check if a contract implements an CBC-165 interface using the registry by calling one of the two functions below:

function implementsCBC165Interface(address _contract, bytes4 _interfaceId) public view returns (bool)

Checks whether a contract implements an CBC-165 interface or not.

If the result is not cached a direct lookup on the contract address is performed.

NOTE: If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling updateCBC165Cache with the contract address. (See CBC-165 Cache for more details.)

identifier: 6d99e76a parameters _contract: Address of the contract to check. _interfaceId: CBC-165 interface to check. returns: true if _contract implements _interfaceId, false otherwise.

function implementsCBC165InterfaceNoCache(address _contract, bytes4 _interfaceId) public view returns (bool)

Checks whether a contract implements an CBC-165 interface or not without using nor updating the cache.

identifier: ee399005 parameters _contract: Address of the contract to check. _interfaceId: CBC-165 interface to check. returns: true if _contract implements _interfaceId, false otherwise.

CBC-165 Cache

Whether a contract implements an CBC-165 interface or not can be cached manually to save energy.

If a contract dynamically changes its interface and relies on the CBC-165 cache of the CBC-1820 registry, the cache MUST be updated manually - there is no automatic cache invalidation or cache update. Ideally the contract SHOULD automatically update the cache when changing its interface. However anyone MAY update the cache on the contract's behalf.

The cache update MUST be done using the updateCBC165Cache function:

function updateCBC165Cache(address _contract, bytes4 _interfaceId) external

identifier: d3d23aa5 parameters _contract: Address of the contract for which to update the cache. _interfaceId: CBC-165 interface for which to update the cache.

Private User-defined Interfaces

This scheme is extensible. You MAY make up your own interface name and raise awareness to get other people to implement it and then check for those implementations. Have fun but please, you MUST not conflict with the reserved designations above.

Set An Interface For An Address

For any address to set a contract as the interface implementation, it must call the following function of the CBC-1820 registry:

function setInterfaceImplementer(address _addr, bytes32 _interfaceHash, address _implementer) external

Sets the contract which implements a specific interface for an address.

Only the manager defined for that address can set it. (Each address is the manager for itself, see the manager section for more details.)

NOTE: If _addr and _implementer are two different addresses, then:

  • The _implementer MUST implement the CBC1820ImplementerInterface (detailed below).
  • Calling canImplementInterfaceForAddress on _implementer with the given _addr and _interfaceHash MUST return the CBC1820_ACCEPT_MAGIC value.

NOTE: The _interfaceHash MUST NOT be an CBC-165 interface - it MUST NOT end with 28 zeroes (0).

NOTE: The _addr MAY be 0, then msg.sender is assumed. This default value simplifies interactions via multisigs where the data of the transaction to sign is constant regardless of the address of the multisig instance.

identifier: d40731a8 parameters _addr: Address for which to set the interface. (If _addr is the zero address then msg.sender is assumed.) _interfaceHash: Core SHA3-256 hash of the name of the interface as a string, for example web3.utils.keccak256('CBC777TokensRecipient') for the CBC777TokensRecipient interface. _implementer: Contract implementing _interfaceHash for _addr.

Get An Implementation Of An Interface For An Address

Anyone MAY query the CBC-1820 Registry to obtain the address of a contract implementing an interface on behalf of some address using the getInterfaceImplementer function.

function getInterfaceImplementer(address _addr, bytes32 _interfaceHash) external view returns (address)

Query if an address implements an interface and through which contract.

NOTE: If the last 28 bytes of the _interfaceHash are zeroes (0), then the first 4 bytes are considered an CBC-165 interface and the registry SHALL forward the call to the contract at _addr to see if it implements the CBC-165 interface (the first 4 bytes of _interfaceHash). The registry SHALL also cache CBC-165 queries to reduce energy consumption. Anyone MAY call the updateCBC165Cache function to update whether a contract implements an interface or not.

NOTE: The _addr MAY be 0, then msg.sender is assumed. This default value is consistent with the behavior of the setInterfaceImplementer function and simplifies interactions via multisigs where the data of the transaction to sign is constant regardless of the address of the multisig instance.

identifier: 94da2ef8 parameters _addr: Address being queried for the implementer of an interface. (If _addr is the zero address then msg.sender is assumed.) _interfaceHash: keccak256 hash of the name of the interface as a string. E.g. web3.utils.keccak256('CBC777Token') returns: The address of the contract which implements the interface _interfaceHash for _addr or 0 if _addr did not register an implementer for this interface.

Interface Implementation (CBC1820ImplementerInterface)

interface CBC1820ImplementerInterface {
/// @notice Indicates whether the contract implements the interface `interfaceHash` for the address `addr` or not.
/// @param interfaceHash keccak256 hash of the name of the interface
/// @param addr Address for which the contract will implement the interface
/// @return CBC1820_ACCEPT_MAGIC only if the contract implements `interfaceHash` for the address `addr`.
function canImplementInterfaceForAddress(bytes32 interfaceHash, address addr) external view returns(bytes32);
}

Any contract being registered as the implementation of an interface for a given address MUST implement said interface. In addition if it implements an interface on behalf of a different address, the contract MUST implement the CBC1820ImplementerInterface shown above.

function canImplementInterfaceForAddress(bytes32 interfaceHash, address addr) external view returns(bytes32)

Indicates whether a contract implements an interface (interfaceHash) for a given address (addr).

If a contract implements the interface (interfaceHash) for a given address (addr), it MUST return CBC1820_ACCEPT_MAGIC when called with the addr and the interfaceHash. If it does not implement the interfaceHash for a given address (addr), it MUST NOT return CBC1820_ACCEPT_MAGIC.

identifier: dab359c1 parameters interfaceHash: Hash of the interface which is implemented addr: Address for which the interface is implemented returns: CBC1820_ACCEPT_MAGIC only if the contract implements ìnterfaceHash for the address addr.

The special value CBC1820_ACCEPT_MAGIC is defined as the keccak256 hash of the string "CBC1820_ACCEPT_MAGIC".

bytes32 constant internal CBC1820_ACCEPT_MAGIC = keccak256(abi.encodePacked("CBC1820_ACCEPT_MAGIC"));

The reason to return CBC1820_ACCEPT_MAGIC instead of a boolean is to prevent cases where a contract fails to implement the canImplementInterfaceForAddress but implements a fallback function which does not throw. In this case, since canImplementInterfaceForAddress does not exist, the fallback function is called instead, executed without throwing and returns 1. Thus making it appear as if canImplementInterfaceForAddress returned true.

Rationale

This standards offers a way for any type of address (externally owned and contracts) to implement an interface and potentially delegate the implementation of the interface to a proxy contract. This delegation to a proxy contract is necessary for externally owned accounts and useful to avoid redeploying existing contracts such as multisigs and DAOs.

The registry can also act as a CBC-165 cache in order to save energy when looking up if a contract implements a specific CBC-165 interface. This cache is intentionally kept simple, without automatic cache update or invalidation. Anyone can easily and safely update the cache for any interface and any contract by calling the updateCBC165Cache function.

Canonical registry deployments MUST publish verified bytecode and network-specific addresses so clients can verify that each deployment matches this specification.

Backward Compatibility

This standard is backward compatible with CBC-165, as both methods MAY be implemented without conflicting with each other.

Copyright and related rights waived via CC0.

Tags:CBC