Introduction

Hi, I'm cardene, a software engineer and technical writer focused on blockchain and AI.

I've also authored Japanese technical books on specification-driven development with LLMs and decentralized application (DApp) development.

I also build and publish a variety of tools, libraries, and open-source projects.

This article examines ERC137, the protocol behind ENS, a service that associates addresses with memorable, human-readable names.

The following material is translated, summarized, and supplemented with explanations, with assistance from ChatGPT.

Overview

ERC137 describes the Ethereum Name Service (ENS). It proposes a protocol and application binary interface (ABI) for mapping the addresses of services and resources to human-readable names. Users and developers can remember and understand contract addresses and similar identifiers more easily, and update the associated names as necessary when addresses change.

Domain names provide stable, human-readable identifiers for network resources.

In this context, network resources or resources refer to addresses.

Users can enter memorable strings such as vitalik.wallet or www.mysite.swarm to access the appropriate resources.

Swarm is a decentralized storage and content distribution protocol operating on the Ethereum platform.

The mapping between a name and its resources may change over time. A user might switch wallets, a website might move to another host, or a Swarm document might be updated, without requiring a change to the domain name. A domain does not have to identify just one resource. Different record types let the same domain refer to different resources. For example, a browser can retrieve an A (address) record and resolve mysite.swarm to a server's IP address, while a mail client can resolve the same name to a mail server.

In simpler terms, as of July 2023, the idea is as follows. Contract and wallet addresses are difficult to read as-is. Why not associate them with human-readable strings such as vitalik.eth?

ERC and EIP illustration

Motivation

Limitations and the Proposal

Existing Ethereum name resolution specifications and implementations provide basic functionality, but the following limitations constrain long-term use.

  1. A single global namespace with one centralized resolver for all names.
  2. Limited or nonexistent support for delegation and subnames or subdomains.
  3. Only one record type, with no support for associating multiple records with a domain.
  4. A single global implementation, without support for multiple name allocation systems.
  5. Conflation of responsibilities: name resolution, registration, and WHOIS information.

These issues also involve conventional Web2 naming systems. Put simply, the limitations are as follows.

  1. A single organization manages domain names, making name resolution reliability and security dependent on that organization.
  2. Subdomains cannot be delegated to other users or services.
  3. A domain name can be associated with only one address, rather than multiple addresses.
  4. A central organization allocates and manages names, preventing users and services from managing names independently.
  5. The same organization handles resolution, registration, and domain ownership information such as WHOIS, conflating roles and creating security concerns.

ERC137 enables use cases such as the following.

The following descriptions have been rewritten for clarity. For the original wording, see the source below.

Hierarchical Domain Names

Domain names can be organized hierarchically. Different subdomains can be associated with different addresses or services.

Example: Create subdomains such as live.mysite.tld and forum.mysite.tld under mysite.tld.

Multiple Services Under One Domain Name

Multiple addresses can be associated with one domain. This allows different services and protocols to be offered under the same domain name.

Example: Associate mysite.tld with a Swarm address hosting a DApp, a Whisper address, and a mail server address.

DNS Record Type Support

Various DNS record types can be supported. Domain names traditionally used with DNS can therefore be hosted on the blockchain. Associating records with ETH addresses, IPFS hashes, and similar identifiers enables resolution of blockchain resources corresponding to conventional domain names.

Legacy Client Support Through DNS Gateways

ENS domains exist on the blockchain, but some clients still use conventional DNS. A DNS gateway exposes ENS domains to traditional DNS services. Existing legacy clients can then resolve ENS domains and access blockchain resources. The gateway bridges the conventional Internet and the blockchain.

Additional Motivation

Use Cases

The first two use cases (hierarchical domain names and multiple services under one domain name) are widespread on the modern Internet using conventional DNS. ENS aims to reproduce and extend these capabilities on the Ethereum platform. These capabilities are expected to remain important as Ethereum develops and grows.

Protocol Documentation

ERC137 does not prescribe a particular implementation of the proposed system. Instead, it proposes a protocol that enables different resolver implementations to perform name resolution consistently. The latter sections provide example implementations of resolver contracts and libraries. These are examples rather than mandatory implementations, and developers can build their own implementations based on them.

Domain Registration and Updates

ERC137 does not prescribe how domains must be registered or updated, or how a system should identify the owner of a particular domain. Domain registration is the responsibility of registrars, and different top-level domains are expected to adopt different governance mechanisms.

Domain Record Updates

Domain record updates can be handled independently of name resolution. Some systems, such as Swarm, may require a well-defined interface for updating domains. The proposal anticipates that such interfaces may be standardized where necessary.

Specification

Overview

ENS consists of three components.

  • ENS registry
  • Resolver
  • Registrar

ENS Registry

The ENS registry is a single smart contract that provides the resolver responsible for resolving any registered domain name. Domain owners can also set resolver addresses and create subdomains. A subdomain may have an owner different from that of its parent domain.

Resolver

A resolver looks up the resources associated with a domain name. For example, it returns a contract address, content hash, or IP address. The resolver specification is defined here and may be extended by other EIPs. Resolvers implement methods for resolving different record types.

Registrar

A registrar assigns domain names to users. Registrars own nodes (domains) in the ENS registry. A registrar may be implemented as a smart contract or an externally owned account (EOA), although at least the root and top-level registrars are expected to be smart contracts.

Additional Details

ENS name resolution involves two steps.

  1. Hash the name to be resolved and query the ENS registry. If a record exists, the registry returns the corresponding resolver address.
  2. Call the corresponding resolver using the method appropriate for the requested resource and return the result.

This mechanism provides flexible name resolution and domain management, associating human-readable names with different resources.

Suppose you want to find the token contract address associated with beercoin.eth.

First, retrieve the resolver.

javascript
var node = namehash("beercoin.eth");
var resolver = ens.resolver(node);

Then ask the resolver for the contract address.

javascript
var address = resolver.addr(node);

The computation of a namehash depends only on the name itself, so a previously calculated namehash can be reused. Precomputing it and embedding it in a contract eliminates string manipulation and allows fast O(1) lookup of ENS records regardless of the number of components in the original name.

Name Syntax

ENS names must follow the syntax below.

javascript
<domain> ::= <label> | <domain> "." <label>
<label> ::= any valid string label per [UTS46](https://unicode.org/reports/tr46/)

An ENS name consists of a sequence of dot-separated labels. Each label must be a valid normalised label as described in UTS46.

UTS46 is a standard for internationalized domain names (IDNs). It is used to represent domain names containing non-ASCII characters, such as Japanese or Chinese characters.

A valid normalised label is the format for a domain name label defined by UTS46 for IDNs. This ensures that domain names satisfy specific conditions, preserving consistency and correctness in IDNs.

JavaScript libraries are available to normalize and validate names.

Uppercase and lowercase letters are allowed, but UTS46 normalization standardizes letter case before hashing the labels. Names with identical spelling but different letter case therefore produce the same namehash.

Labels and domain names may be of arbitrary length, but for compatibility with traditional DNS, labels of no more than 64 characters and complete ENS names of no more than 255 characters are recommended. For the same reason, labels should not begin or end with a hyphen or begin with a digit.

The namehash Algorithm

The namehash algorithm hashes names before they are used in ENS. It recursively hashes the name components, producing a unique fixed-length value (a node) for any valid input domain.

The pseudocode for the namehash algorithm is as follows.

python
def namehash(name):
  if name == '':
    return '\0' * 32
  else:
    label, _, remainder = name.partition('.')
    return sha3(namehash(remainder) + sha3(label))

The process is explained in detail below.

  1. First, split the domain name into dot-separated labels.
    • For example, mysite.swarm consists of two labels, mysite and swarm.
  2. Hash each label independently.
    • Hashing converts a label into a unique fixed-length value.
    • Suppose the hash of mysite is A and that of swarm is B.
  3. Start processing from the last label.
    • Retrieve the hash B of the final label, swarm.
  4. Concatenate the previous hash (here, B) with the hash of the current label (here, A).
    • This produces new data (B + A).
  5. Hash the new data (B + A) again.
    • This produces a new hash, which we will call C.
  6. Repeat the process until no labels remain.
    • Concatenate hash A of mysite with the previous hash (here, C) and hash the result again.
    • This produces another hash (D).
  7. Finally, concatenate hash A of the first label, mysite, with the previous hash (D).
python
node = '\0' * 32
node = sha3(node + sha3('swarm'))
node = sha3(node + sha3('mysite'))
  1. Also concatenate 32 zero bytes before the hash of the first label.
python
namehash('') = 0x0000000000000000000000000000000000000000000000000000000000000000
namehash('eth') = 0x93cdeb708b7545dc668eb9280176169d1c33cfd8ed6f04690a0bcc88a93fc4ae
namehash('foo.eth') = 0xde9b09fd7c5f901e23a3f19fecc54828e9c848539801e86591bd9801b019f84f
  1. Finally, hash this data (32 zero bytes + A + D).
    • The resulting hash is the namehash of mysite.swarm.

In this way, recursive hashing converts mysite.swarm into a unique hash value. This allows a domain name to be stored as a short, unique value for fast name resolution.

Registry Specification

The following functions let users operate the ENS registry contract to transfer domain ownership, configure resolvers, and perform other operations. Successful changes and transactions are recorded in event logs, making it possible to inspect the operation history.

javascript
function owner(bytes32 node) constant returns (address);

Returns the owner (registrant) of the specified node (domain name).

javascript
function resolver(bytes32 node) constant returns (address);

Returns the resolver for the specified node. The resolver identifies the address of a contract or service used for name resolution.

javascript
function ttl(bytes32 node) constant returns (uint64);

Returns the Time-to-Live (TTL) for the specified node.

TTL indicates the maximum duration for which information about the node may be cached.

javascript
function setOwner(bytes32 node, address owner);

Transfers ownership of a node to another registrant. Only the current node owner may call this function. On success, it emits a Transfer(bytes32 indexed, address) event.

javascript
function setSubnodeOwner(bytes32 node, bytes32 label, address owner);

Creates a new node (subnode) and sets its owner. If the subnode already exists, its owner is updated. Only the current node owner may call this function. On success, it emits a NewOwner(bytes32 indexed, bytes32 indexed, address) event.

javascript
function setResolver(bytes32 node, address resolver);

Sets the resolver address for a node. Only the node owner may call this function. On success, it emits a NewResolver(bytes32 indexed, address) event.

javascript
function setTTL(bytes32 node, uint64 ttl);

Sets the node's TTL. The TTL applies to the registry's owner and resolver records, as well as information returned by the associated resolver.

Resolver Specification

A resolver may implement a subset of the specified record types. If a particular record type requires several functions, however, the resolver must implement either all of them or none of them. The resolver must also implement a fallback function that throws an exception.

A resolver has one mandatory function.

javascript
function supportsInterface(bytes4 interfaceID) constant returns (bool)

The supportsInterface function, proposed by ERC165, returns true if the resolver implements the interface corresponding to the specified four-byte identifier.

For more on ERC165, see the following article.

[ERC165] Checking Whether a Contract Supports a Particular Interface

An interface identifier is the XOR of the function signature hashes of the functions provided by that interface. For a single-function interface, it equals that function's signature hash. If a resolver returns true from supportsInterface(), it must implement the functions specified by the interface.

supportsInterface must always return true for 0x01ffc9a7. This is the interface ID of supportsInterface itself.

The resolver interfaces standardized at the time of writing are listed below.

Interface name Interface hash Specification
addr 0x3b3b57de Contract address
name 0x691f3431 #181
ABI 0x2203ab56 #205
pubkey 0xc8690233 #619

EIPs can also define new interfaces to add to this registry.

Resolvers can implement one or more of these interfaces, creating different types of resolvers. This supports resolvers for different record types and enables flexible name resolution.

Contract Address Interface

To support the contract address interface, a resolver must implement the following function.

javascript
function addr(bytes32 node) constant returns (address);

If a resolver supports addr lookup but the requested node (domain name) has no addr record, the resolver must return the zero address.

An ENS addr record associates a domain name (node) with the corresponding contract address. A domain name with an addr record can be used to look up its associated contract address.

Clients resolving address records must check whether the resolver returns a zero value and treat it as if no resolver were specified for the name. In other words, they must refuse to send funds to or interact with that address. Failing to do so could cause a user to send funds to the zero address accidentally.

When an address changes, the resolver must emit the following event.

text
event AddrChanged(bytes32 indexed node, address a);

This event is used to monitor address changes. When a resolver updates an addr record, the event is logged so that other applications and smart contracts can take the necessary action.

Registry Implementation

The following contract implements the ENS registry.

javascript
contract ENS {
    struct Record {
        address owner;
        address resolver;
        uint64 ttl;
    }

    mapping(bytes32=>Record) records;

    event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner);
    event Transfer(bytes32 indexed node, address owner);
    event NewResolver(bytes32 indexed node, address resolver);

    modifier only_owner(bytes32 node) {
        if(records[node].owner != msg.sender) throw;
        _
    }

    function ENS(address owner) {
        records[0].owner = owner;
    }

    function owner(bytes32 node) constant returns (address) {
        return records[node].owner;
    }

    function resolver(bytes32 node) constant returns (address) {
        return records[node].resolver;
    }

    function ttl(bytes32 node) constant returns (uint64) {
        return records[node].ttl;
    }

    function setOwner(bytes32 node, address owner) only_owner(node) {
        Transfer(node, owner);
        records[node].owner = owner;
    }

    function setSubnodeOwner(bytes32 node, bytes32 label, address owner) only_owner(node) {
        var subnode = sha3(node, label);
        NewOwner(node, label, owner);
        records[subnode].owner = owner;
    }

    function setResolver(bytes32 node, address resolver) only_owner(node) {
        NewResolver(node, resolver);
        records[node].resolver = resolver;
    }

    function setTTL(bytes32 node, uint64 ttl) only_owner(node) {
        NewTTL(node, ttl);
        records[node].ttl = ttl;
    }
}

Here is a brief explanation of the contract.

Record

A struct storing information associated with a domain name (node). The information includes the owner (owner), resolver (resolver), and TTL (cache duration).

records

A mapping from domain names (nodes) to their corresponding information (Record). It is used to retrieve information for a given domain name.

Additional Details

This contract implements the ENS registry and manages information associated with domain names. Users can set or change domain owners and resolvers through the contract. Events also notify other applications and contracts of changes associated with domain names. This allows ENS to operate flexibly and securely.

Resolver Implementation

Built-in resolver

This resolver implements the contract address resource profile, with the contract itself handling name resolution. It is suitable for simple use cases and can be incorporated directly into the ENS registry. However, it throws an error for unknown function calls, which may interfere with the operation of some contracts.

javascript
contract DoSomethingUseful {
    // Other code

    function addr(bytes32 node) constant returns (address) {
        return this;
    }

    function supportsInterface(bytes4 interfaceID) constant returns (bool) {
        return interfaceID == 0x3b3b57de || interfaceID == 0x01ffc9a7;
    }

    function() {
        throw;
    }
}

addr

Returns the contract address associated with the specified node.

supportsInterface

Returns whether the specified interface ID is supported.

Standalone resolver

This basic resolver implements the contract address profile and allows only the owner to update records. After deploying the resolver, it can be used by updating the ENS registry to point to it.

javascript
contract Resolver {
    event AddrChanged(bytes32 indexed node, address a);

    address owner;
    mapping(bytes32=>address) addresses;

    modifier only_owner() {
        if(msg.sender != owner) throw;
        _
    }

    function Resolver() {
        owner = msg.sender;
    }

    function addr(bytes32 node) constant returns(address) {
        return addresses[node];    
    }

    function setAddr(bytes32 node, address addr) only_owner {
        addresses[node] = addr;
        AddrChanged(node, addr);
    }

    function supportsInterface(bytes4 interfaceID) constant returns (bool) {
        return interfaceID == 0x3b3b57de || interfaceID == 0x01ffc9a7;
    }

    function() {
        throw;
    }
}

addr

Returns the contract address associated with the specified node.

setAddr

Sets the contract address. Only the owner may call this function.

Public resolver

This resolver also implements the contract address profile and allows only owners to update records. It uses the registry to determine who may update each entry. This resolver can also be deployed and used with the ENS registry.

javascript
contract PublicResolver {
    event AddrChanged(bytes32 indexed node, address a);
    event ContentChanged(bytes32 indexed node, bytes32 hash);

    ENS ens;
    mapping(bytes32=>address) addresses;

    modifier only_owner(bytes32 node) {
        if(ens.owner(node) != msg.sender) throw;
        _
    }

    function PublicResolver(address ensAddr) {
        ens = ENS(ensAddr);
    }

    function addr(bytes32 node) constant returns (address ret) {
        ret = addresses[node];
    }

    function setAddr(bytes32 node, address addr) only_owner(node) {
        addresses[node] = addr;
        AddrChanged(node, addr);
    }

    function supportsInterface(bytes4 interfaceID) constant returns (bool) {
        return interfaceID == 0x3b3b57de || interfaceID == 0x01ffc9a7;
    }

    function() {
        throw;
    }
}

addr

Returns the contract address associated with the specified node.

setAddr

Sets the contract address. Only the owner may call this function.

Registrar Implementation

This registrar allows the first user requesting a name to register it free of charge. The contract is used to register subnodes under a particular root node (rootNode).

javascript
contract FIFSRegistrar {
    ENS ens;
    bytes32 rootNode;

    function FIFSRegistrar(address ensAddr, bytes32 node) {
        ens = ENS(ensAddr);
        rootNode = node;
    }

    function register(bytes32 subnode, address owner) {
        var node = sha3(rootNode, subnode);
        var currentOwner = ens.owner(node);
        if(currentOwner != 0 && currentOwner != msg.sender)
            throw;

        ens.setSubnodeOwner(rootNode, subnode, owner);
    }
}

When deploying the contract, initialize it with the ENS address (ensAddr) and the root node (node). Call register to register a new name. The name is uniquely identified by the combination of the root node and specified subnode (sha3(rootNode, subnode)). A name cannot be registered if another user already owns it or its owner is someone other than the caller. Users cannot take names owned by others. The first user to request a particular name can register it free of charge. The contract rejects attempts by other users to register the same name. The FIFS registrar provides a fair, first-come-first-served mechanism for free name registration. This is a simple way to register a custom domain name.

Conclusion

This article covered ERC137, the proposal underlying ENS, which associates addresses with memorable, human-readable names. I hope you found it useful.

I plan to add further implementation details in the future.

If you have questions, feel free to contact me by direct message on Twitter.

Twitter @cardene777