Ethereum Name Service 백서

Ethereum Name Service

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 10쪽

The name to lookup }) return <div>{myResolver}</div> } ``` ```ts [Ethers] const resolver = await provider.getResolver('nick.eth') ``` ```ts [viem] // https://viem.sh/docs/ens/actions/getEnsResolver.html import { normalize } from 'viem/ens' import { publicClient } from './client' const ensResolver = await publicClient.getEnsResolver({ name: normalize('nick.eth'), }) ``` ```py [Web3.py] # https://web3py.readthedocs.io/en/latest/ens_overview.html#working-with-resolvers from ens.auto import ns resolver = ns.resolver('alice.eth') ``` ::: To verify which specifications are implemented by a resolver, you can call the `supportsInterface(bytes4 interfaceID)` on the resolver with the interfaceID you would like to test for. #### 2. Query the Resolver Now you have found the resolver responsible for the name in question, you can query it for the information you are interested in. There are many ways you can query the resolver, `addr()` `text()` `contenthash()` `abi()` etc. If the resolver supports text records, you can call `text()` to get that text record for the name. More about loading information from a resolver can be found [here](/resolvers/interacting). ##### Wildcard Resolution In addition, all of the above functions can be sent to the `resolve()` function, specified in [ENSIP-10](/ensip/10). This allows for not only multicall functionality, but also easier implementation of EIP-3668, and more. Most clients & many resolvers utilize wildcard resolution as their primary form of resolution. ### Reverse Resolution Due to the modular nature of how ENS is designed, it is also possible to lookup the "primary name" of an address. This process actually uses forward resolution under the hood, you read that right - its just forwards resolution. To look up the primary name of a given address, you must do a resolver lookup for `addr.reverse` and then query the `name()` field on the resolver. This name field returns the "preferred" name for the address. You should always follow up a reverse lookup with a forward lookup to verify that the resulting name points back to the original address. If the address doesn't match, display the address rather than the reversed name. ```solidity /// @dev The starting point for all ENS resolution is the Registry ENS ens = 0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e; /// @dev The node hash for "addr.reverse" bytes32 ADDR_REVERSE_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2; /// @dev Returns the node hash for a given account's reverse records, `{address}.addr.reverse` function reverseNode(address addr) public pure returns (bytes32) { return keccak256( abi.encodePacked(ADDR_REVERSE_NODE, sha3HexAddress(addr)) ); } /// @dev Get the reverse record for an address function getReverseRecord(address addr) public view returns (string) { bytes32 reverseNodeHash = reverseNode(addr); // Get the resolver for the reverse node Resolver resolver = ens.resolver(reverseNodeHash); // Get the address's preferred name return resolver.name(reverseNodeHash); } ``` :::info **Important**: The client MUST perform a forward resolution on a user's reverse record to verify the address matches the one you are looking up. The example above does not perform this verification. ::: Please note that many libraries already have functionality to do this. You can read more about it in the [Getting a Primary Name](/web/reverse) section. import { NameProcessing } from '../../components/NameProcessing' import { Card } from '../../components/ui/Card' ## Name Processing \[Normalization and recommendations for how to handle names] When interacting with the ENS smart contracts directly, it is important to note that names are not stored as strings. [Libraries](/web/libraries) handle name encoding for you when implementing basic name resolution, but you may need to handle the encoding yourself when interacting with the protocol directly. Below is an interactive tool that shows all the different formats of names and how to implement them. <Card> <NameProcessing /> </Card> ### Name Normalization Normalization is the process of canonicalizing a name before running it through the [Namehash](#namehash) algorithm. It is important to always normalize all input, because even one little difference (like a capital vs lowercase character) will cause the namehash to be completely different. For example, `NaMe.EtH` normalizes to `name.eth`. This ensures that the correct Registry node is used, no matter how the user types in the name. ENS names are validated and normalized using the [ENSIP-15](/ensip/15) normalization algorithm. Previously, [UTS-46](https://www.unicode.org/reports/tr46/) was used, but that is insufficient for emoji sequences. Correct emoji processing is only possible with [UTS-51](https://www.unicode.org/reports/tr51/). The [ENSIP-15](/ensip/15) normalization algorithm draws from those older Unicode standards, but also adds many other validation rules to prevent common spoofing techniques like inserting zero-width characters, or using confusable (look-alike) characters. See here for additional discussion on this: [Homogylphs](https://support.ens.domains/en/articles/7901658-what-are-homoglyphs-and-lookalike-ens-names) A standard implementation of the algorithm is available at [@adraffy/ens-normalize](https://github.com/adraffy/ens-normalize.js). This library is used under the hood in [viem](https://viem.sh/docs/ens/utilities/normalize), [ENSjs](https://github.com/ensdomains/ensjs/blob/main/packages/ensjs/src/utils/normalise.ts#L27), and others. ```js import { normalize } from 'viem/ens' // Uses @adraffy/ens-normalize under the hood const normalized = normalize('RaFFY🚴‍♂️.eTh') // => "raffy🚴‍♂.eth" ``` If the name was not able to be normalized, then that method will throw an error. A name is valid if it is able to be normalized. ### Namehash :::note You **MUST** [normalize](#normalize) a name before you attempt to create a namehash! If you don't, then the hash you get may be incorrect. Some libraries like [ensjs](https://github.com/ensdomains/ensjs) will automatically do this for you. ::: In the core ENS registry, names are stored as a hash instead of the raw string to optimize for gas, performance, and more. This hashed value is typically referred to as a `node`. The node is a hex-encoded 32-byte value that is derived from the name using the `namehash` algorithm defined in [ENSIP-1](/ensip/1). Namehash is a recursive algorithm that hashes each part of the name, then hashes the results together. Because recursive functions aren't very efficient in Solidity, it's usually best to derive the namehash offchain and pass to it a contract. Luckily, there are libraries that do this for us. :::code-group ```tsx [Viem] // https://viem.sh/docs/ens/utilities/namehash import { namehash, normalize } from 'viem/ens' const normalizedName = normalize('name.eth') const node = namehash(normalizedName) ``` ```ts [Ethers.js] // https://docs.ethers.org/v6/api/hashing/#namehash import { ensNormalize, namehash } from 'ethers/hash' const normalizedName = ensNormalize('name.eth') const node = namehash(normalizedName) ``` ```python [ens-namehash-py] # https://github.com/ConsenSysMesh/ens-namehash-py from namehash import namehash node = namehash('name.eth') ``` ```rust [namehash-rust] // https://github.com/InstateDev/namehash-rust fn main() { let node = &namehash("name.eth"); let s = hex::encode(&node); } ``` ```solidity [Solidity] // SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import "@ensdomains/ens-contracts/contracts/utils/NameEncoder.sol"; contract MyContract { function namehash(string calldata name) public pure returns (bytes32) { (, bytes32 node) = NameEncoder.dnsEncodeName(name); return node; } } ``` ::: #### Algorithm The specification for the namehash algorithm was originally defined in [EIP-137](https://eips.ethereum.org/EIPS/eip-137#namehash-algorithm) (same as [ENSIP-1](/ensip/1)). It's a recursive algorithm that works its way down until you hit the root domain. For `ens.eth`, the algorithm works like so: ``` namehash('ens.eth') = keccak256(namehash('eth') + labelhash('ens')) namehash('eth') = keccak256(namehash('') + labelhash('eth')) namehash('') = 0x0000000000000000000000000000000000000000000000000000000000000000 ``` That last line is a special case: The namehash for an empty string (representing the root domain) is 32 null bytes. If you plug everything in above, you'll end up with the final namehash value: ``` namehash('') = 0x0000000000000000000000000000000000000000000000000000000000000000 labelhash('eth') = keccak256('eth') = 0x4f5b812789fc606be1b3b16908db13fc7a9adf7ca72641f84d75b47069d3d7f0 namehash('eth') = keccak256(namehash('') + labelhash('eth')) = keccak256(0x00000000000000000000000000000000000000000000000000000000000000004f5b812789fc606be1b3b16908db13fc7a9adf7ca72641f84d75b47069d3d7f0) = 0x93cdeb708b7545dc668eb9280176169d1c33cfd8ed6f04690a0bcc88a93fc4ae labelhash('ens') = keccak256('ens') = 0x5cee339e13375638553bdf5a6e36ba80fb9f6a4f0783680884d92b558aa471da namehash('ens.eth') = keccak256(namehash('eth') + labelhash('ens')) = keccak256(0x93cdeb708b7545dc668eb9280176169d1c33cfd8ed6f04690a0bcc88a93fc4ae5cee339e13375638553bdf5a6e36ba80fb9f6a4f0783680884d92b558aa471da) = 0x4e34d3a81dc3a20f71bbdf2160492ddaa17ee7e5523757d47153379c13cb46df ``` This brings us to the final node for ens.eth: `0x4e34d3a81dc3a20f71bbdf2160492ddaa17ee7e5523757d47153379c13cb46df` #### Reverse Nodes The [Reverse Node](/terminology#reverse-node) is a node in the Registry that can be claimed for any Ethereum account. The name this node represents is `[addr].addr.reverse`, where `[addr]` is the Ethereum public address (lowercase, without the "0x"). These reverse nodes are typically used to set a [Primary Name](#primary-name) for an account. To generate the namehash for a reverse node: * Take the input address and: * Remove the "0x" at the beginning * Convert all characters to lowercase * Add `.addr.reverse` to the end * Run this result through the namehash algorithm For example, for address `0x481f50a5BdcCC0bc4322C4dca04301433dED50f0`, the name for the reverse node is: * `481f50a5bdccc0bc4322c4dca04301433ded50f0.addr.reverse` And the resulting namehash for the reverse node is: * `0x58354ffdde6ac279f3a058aafbeeb14059bcb323a248fb338ee41f95fa544c86` ### Labelhash :::note You **MUST** [normalize](#normalize) a name before you attempt to create a labelhash! If you don't, then the hash you get may be incorrect. ::: Labelhash is the Keccak-256 hash of a single label (e.g. `name` in `name.eth`), used in places that don't require the full name. One example of where labelhash is used is in the [BaseRegistar](/registry/eth), since it only supports registering 2LDs (second-level domains, like `name.eth`) and not 3LDs+ (e.g. `sub.name.eth`). The token ID of a second-level .eth name in the BaseRegistar is the uint256 of the labelhash. :::code-group ```tsx [Viem] // https://viem.sh/docs/ens/utilities/labelhash import { labelhash, normalize } from 'viem/ens' const normalizedLabel = normalize('label') const hash = labelhash(normalizedLabel) ``` ```tsx [Ethers] // https://docs.ethers.org/v6/api/crypto/#keccak256 import { keccak256 } from 'ethers/crypto' import { ensNormalize } from 'ethers/hash' import { toUtf8Bytes } from 'ethers/utils' const normalizedLabel = ensNormalize('label') const labelhash = keccak256(toUtf8Bytes(normalizedLabel)) ``` ```solidity [Solidity] string constant label = "label"; bytes32 constant labelhash = keccak256(bytes(label)); ``` ::: ### DNS Encoding :::note You **MUST** [normalize](#normalize) a name before you DNS-encode it! If you don't, then when you pass those DNS-encoded bytes into a contract method, incorrect namehashes/labelhashes may be derived. ::: This is a binary format for domain names, which encodes the length of each label along with the label itself. It is used by some of the ENS contracts, such as when wrapping names in the [Name Wrapper](/wrapper/overview) or resolving data with [ENSIP-10](/ensip/10). :::code-group ```tsx [Viem] import { packetToBytes } from 'viem/ens' import { toHex } from 'viem/utils' const name = 'name.eth' const dnsEncodedName = toHex(packetToBytes(name)) // 0x046e616d650365746800 ``` ```tsx [Ethers] // https://docs.ethers.org/v6/api/hashing/#dnsEncode import { dnsEncode } from 'ethers/lib/utils' const dnsEncodedName = dnsEncode('name.eth') ``` ```solidity [Solidity] // SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import "@ensdomains/ens-contracts/contracts/utils/NameEncoder.sol"; contract MyContract { function dnsEncode(string calldata name) public pure returns (bytes memory) { (bytes memory dnsEncodedName,) = NameEncoder.dnsEncodeName(name); return dnsEncodedName; } } ``` ::: #### Decoding To decode a DNS-encoded name, you can use `bytesToPacket()` from ENSjs. ```tsx import { bytesToPacket } from '@ensdomains/ensjs/utils' import { hexToBytes } from 'viem/utils' const dnsEncodedName = '0x046e616d650365746800' const name = bytesToPacket(hexToBytes(dnsEncodedName)) // name.eth ``` #### Algorithm To DNS-encode a name, first split the name into labels (delimited by `.`). Then for each label from left-to-right: * One byte to denote the length of the label * The UTF-8 encoded bytes for the label * If this is the last label, then one final NUL (`0x00`) byte. For example, to DNS-encode `my.name.eth`: * `0x02` (length of the label "my") * `0x6D79` (UTF-8 encoded bytes of "my") * `0x04` (length of the label "name") * `0x6E616D65` (UTF-8 encoded bytes of "name") * `0x03` (length of the label "eth") * `0x657468` (UTF-8 encoded bytes of "eth") * `0x00` (end of name marker) Final result: `0x026d79046e616d650365746800` :::note Since the length of each label is stored in a single byte, that means that with this DNS-encoding scheme, each label is limited to being 255 UTF-8 encoded bytes in length. Because of this, names with longer labels cannot be wrapped in the [Name Wrapper](/wrapper/overview), as that contract uses the DNS-encoded name. ::: ## DNS Registrar In [DNS on ENS](/learn/dns) we learned how ENS aims to extend the functionality of the DNS. On this page we will explore the implementation of DNSSEC, the DNSRegistrar, and the building blocks for gasless DNSSEC. :::note Not all top level domains support DNSSEC, and some might have custom ENS implementations. Please refer to the [TLD List](/dns/tlds) for TLD-specific information. ::: ### DNSSEC DNSSEC (Domain Name System Security Extensions) is an added layer of security on top of DNS that allows for cryptographic verification of records. It establishes a chain of trust from the root key (which is signed by ICANN) down to each key. All ENS-enabled DNS names are required to use DNSSEC, and the [DNSSECOracle](https://github.com/ensdomains/ens-contracts/tree/master/contracts/dnssec-oracle) is responsible for verifying the signatures. #### Claiming a Name Onchain Since 2021, it has been possible to [import a DNS name](/learn/dns#importing-a-dns-name) and use that as an ENS name. This process involves enabling DNSSEC, setting a specific TXT record, and submitting a proof to the [DNSRegistrar](https://github.com/ensdomains/ens-contracts/tree/master/contracts/dnsregistrar) smart contract. Expect your `TXT` record to look something like this: ``` TXT _ens a=<eth-address>; ``` You can learn more about [how to import a DNS name](/learn/dns#importing-a-dns-name) in the DNS section, or see how to [programmatically complete these steps](#programming-dnssec-proofs). There is no ENS protocol fee to import a DNS name, but it requires a large amount of gas (up to a few million) to submit the proof onchain. Continue reading to learn how this has been mitigated. ### Offchain Verification (Gasless) [EP 5.1](/dao/proposals/5.1) introduced a new DNSSECOracle and DNSRegistrar which makes it possible to perform DNSSEC verification at query time, enabling truly free usage of DNS names in ENS. We call this "gasless DNSSEC". It works by enabling [wildcard resolution](/ensip/10) at the DNS TLD level. During the [name resolution process](/resolution), if a name doesn't already exist onchain but has been configured for usage in ENS, the DNSSEC proof will be fetched offchain via [CCIP Read](https://eips.ethereum.org/EIPS/eip-3668) and then verified onchain with the same DNSSECOracle mentioned above. #### Import a DNS name gaslessly To configure a DNS name for usage in ENS, simply add a `TXT` record with the following format: ``` TXT @ ENS1 &lt;resolver-address&gt; ``` The `resolver-address` implementation is customizable just like any other ENS resolver. To get started quickly, a special ExtendedDNSResolver has been deployed which allows users to specify an ETH address that the name should resolve to within the same `TXT` record. To use this setup, simply add a record with the following format: ``` TXT @ ENS1 &lt;extended-resolver-address&gt; &lt;eth-address&gt; TXT @ ENS1 0x238A8F792dFA6033814B18618aD4100654aeef01 0x225f137127d9067788314bc7fcc1f36746a3c3B5 ``` ### Other #### TLD Ownership You can lookup the `owner` of any TLD by calling the `Registry.owner(bytes32 node)` function. If at least one domain has been imported for this TLD (via the onchain method), the owner will be either the `DNSRegistrar` or a smart contract controlled by the respective registry operator. If a TLD has not yet been activated, the `owner` will return `0x0` and it may require one user to import a name onchain to activate the TLD. See the [supported TLD list](/dns/tlds) for more info. #### Programming DNSSEC Proofs To help you interact with DNSSEC data and the DNSRegistrar, we provide a few libraries. * [DNSProvejs](https://github.com/ensdomains/dnsprovejs) = A library for querying and validating DNSSEC data from DNS * [ENSjs](https://github.com/ensdomains/ensjs) = A library for interacting with ENS smart contracts ##### Retrieving a proof ```ts import { addEnsContracts } from '@ensdomains/ensjs' import { getDnsImportData } from '@ensdomains/ensjs/dns' import { createPublicClient, http } from 'viem' import { mainnet } from 'viem/chains' const client = createPublicClient({ chain: addEnsContracts(mainnet), transport: http(), }) const dnsImportData = await getDnsImportData(client, { name: 'example.com', }) ``` ##### Submitting the proof to the DNSRegistrar ```ts import { addEnsContracts } from '@ensdomains/ensjs' import { getDnsImportData, importDnsName } from '@ensdomains/ensjs/dns' import { createPublicClient, createWalletClient, custom, http } from 'viem' import { mainnet } from 'viem/chains' const mainnetWithEns = addEnsContracts(mainnet) const client = createPublicClient({ chain: mainnetWithEns, transport: http(), }) const wallet = createWalletClient({ chain: mainnetWithEns, transport: custom(window.ethereum), }) const dnsImportData = await getDnsImportData(client, { name: 'example.com', }) await importDnsName(wallet, { name: 'example.com', dnsImportData, }) ``` ### Other functions ```ts // Get the list of suffixes DNSRegistrar.suffixes // Get Oracle DNSRegistrar.oracle ``` ```ts DNSRegistrar.claim(bytes name, bytes proof) DNSRegistrar.proveAndClaim(bytes name, tuple[] input, bytes proof) DNSRegistrar.proveAndClaimWithResolver(bytes name, tuple[] input, bytes proof, address resolver, address addr) ``` ## The Registry \[Root Registry of the Ethereum Name Service] The ENS registry is the core contract that lies at the heart of ENS resolution. All ENS lookups start by querying the registry. The registry maintains a list of domains, recording the owner, resolver, and TTL for each, and allows the owner of a domain to make changes to that data. The ENS registry is specified in [EIP 137](https://eips.ethereum.org/EIPS/eip-137). ### Why Registries? Top-Level Domains (TLDs), like `.eth`, `.com`, and `.test`, are owned by smart
프로젝트로 돌아가기