Ethereum Name Service 백서

Ethereum Name Service

원문

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

oyProxy( address implementation, uint256 salt, bytes memory data ) external returns (address proxy); ``` `deployProxy` uses CREATE2 to deploy a proxy, with the salt derived from the caller: ```solidity outerSalt = keccak256(abi.encode(msg.sender, salt)) ``` After construction, the factory calls `proxy.initialize(implementation, data)`, which stores the implementation and forwards `data` as initialisation calldata. Because `outerSalt` mixes in `msg.sender`, the same `salt` value submitted by two different deployers produces two different proxy addresses. There is no contention between callers and no need for global salt coordination. ```mermaid sequenceDiagram participant Caller participant Factory as VerifiableFactory participant Proxy participant Impl as Implementation Caller->>Factory: deployProxy(impl, salt, data) Factory->>Factory: outerSalt = keccak256(sender, salt) Factory->>Proxy: CREATE2 with outerSalt Note over Proxy: bytecode embeds proxy logic & outerSalt Factory->>Proxy: initialize(impl, data) Proxy->>Proxy: store impl in ERC-1967 slot Proxy->>Impl: delegatecall(data) Factory-->>Caller: proxy address ``` ### The Proxy Each deployed proxy is a [minimal proxy (EIP-1167)](https://eips.ethereum.org/EIPS/eip-1167) that delegates all calls to a single shared `UUPSProxyLogic` contract, deployed once in the factory's constructor and readable via `proxyLogic()`. The proxy's runtime bytecode is 77 bytes: the standard 45-byte minimal proxy pointing at `UUPSProxyLogic`, followed by the CREATE2 `outerSalt` as the last 32 bytes. The appended salt is what makes the proxy verifiable later. Every call to the proxy first lands in `UUPSProxyLogic`, which handles the proxy functions itself and forwards everything else to the implementation stored in the proxy's [ERC-1967](https://eips.ethereum.org/EIPS/eip-1967) implementation slot: * `initialize(implementation, data)` runs once (it reverts `AlreadyInitialized` afterwards). It stores the implementation in the ERC-1967 slot and delegate-calls the implementation with `data` so it can run its own initializer. * `getVerifiableProxyData()` returns the salt (read from the proxy's own bytecode) and the current implementation address. * `verifiableProxyFactory()` returns the factory address. * `upgradeToAndCall(newImplementation, data)` performs upgrades (see [Upgrade Authorization](#upgrade-authorization)). ### On-chain Verification ```solidity function verifyContract(address proxy) external view returns (address implementation); ``` `verifyContract` proves that `proxy` was deployed by this factory and returns the proxy's current implementation. It retrieves the proxy's stored salt via `getVerifiableProxyData()`, reconstructs the expected CREATE2 address from `(proxy creation code, factory, salt)`, and reverts with `VerificationFailed(proxy)` on any mismatch, including when `proxy` has no code or does not respond to `getVerifiableProxyData()`. A caller that requires a specific implementation compares the returned address itself. This is the property that makes the factory **verifiable**: a smart contract can prove that an arbitrary address really is a proxy deployed by this factory, and learn which implementation it currently runs, without trusting metadata or off-chain data. ### Available Implementations Three implementation contracts are deployed once and then proxied through the factory. Their addresses are listed in the [Deployments](/learn/deployments#sepolia-ensv2) table, and you need them to deploy your own instance: `deployProxy` takes the implementation address as its first argument. | Implementation | Salt scheme | Where it's deployed | | -------------------------- | ----------------------------------------------------------------------------- | ------------------------------------------------------------- | | `PermissionedResolverImpl` | `keccak256("OwnedResolver", owner, version)`, one resolver per owner | On demand by users | | `UserRegistryImpl` | `keccak256("UserRegistry", namehash, version)`, one subname registry per name | On demand by name owners | | `WrapperRegistryImpl` | per-name | Inside migration controllers when a locked v1 name is wrapped | ### Upgrade Authorization Each proxy's implementation can be upgraded individually via `upgradeToAndCall(newImplementation, data)` on that proxy. The factory itself is not upgradeable. Who may upgrade is decided by the current implementation's `_authorizeUpgrade` override. In ENSv2 the check is uniform: only an account holding `ROLE_UPGRADE` on the proxy's `ROOT_RESOURCE` can upgrade the implementation: ```solidity function _authorizeUpgrade(address newImplementation) internal override onlyRootRoles(ROLE_UPGRADE) {} ``` Upgrades target a single proxy, not the shared implementation. An upgrade to one user's resolver or subname registry does not affect anyone else's. ### Computing Addresses Off-chain Because the proxy address is fully determined by `(factory, proxy logic address, deployer, salt)`, clients can compute it before any transaction is sent. The proxy creation code is the EIP-1167 template with the shared logic address in the implementation slot and the salt appended, so it can be assembled directly (`proxyLogic` is read once from the factory's `proxyLogic()` getter): ```ts import { concat, encodeAbiParameters, getCreate2Address, keccak256 } from 'viem' function predictProxyAddress({ factoryAddress, proxyLogic, deployer, salt, }: { factoryAddress: `0x${string}` proxyLogic: `0x${string}` deployer: `0x${string}` salt: bigint }) { const outerSalt = keccak256( encodeAbiParameters( [{ type: 'address' }, { type: 'uint256' }], [deployer, salt] ) ) const initCode = concat([ '0x3d604d80600a3d3981f3363d3d373d3d3d363d73', proxyLogic, '0x5af43d82803e903d91602b57fd5bf3', outerSalt, ]) return getCreate2Address({ from: factoryAddress, salt: outerSalt, bytecodeHash: keccak256(initCode), }) } ``` This is useful whenever you need a name's resolver or subname-registry address before the user actually creates it. ### Code Examples Every proxy deployment follows the same steps: compute a salt, encode the implementation's `initialize` call as the `data` argument, and call `deployProxy` on the factory. The salt and initializer differ per implementation. <FrenCallout fren="bittu" variant="tip"> The contract addresses used below (`VERIFIABLE_FACTORY`, `PERMISSIONED_RESOLVER_IMPL`, `USER_REGISTRY_IMPL`) are protocol-deployed contracts. Find them in the [Deployments](/learn/deployments#sepolia-ensv2) table. </FrenCallout> Both examples below share this setup: ```ts [Viem] import { createPublicClient, createWalletClient, encodeAbiParameters, encodeFunctionData, http, keccak256, namehash, parseAbi, parseEventLogs, stringToHex, } from 'viem' import { mainnet } from 'viem/chains' const client = createPublicClient({ chain: mainnet, transport: http() }) const wallet = createWalletClient({ account, chain: mainnet, transport: http(), }) const verifiableFactoryAbi = parseAbi([ 'function deployProxy(address implementation, uint256 salt, bytes data)', 'event ProxyDeployed(address indexed sender, address indexed proxyAddress, uint256 salt, address implementation)', ]) // Grant all roles and their admin counterparts const ALL_ROLES = 0x1111111111111111111111111111111111111111111111111111111111111111n ``` #### Deploying a Resolver Proxy Deploy a per-account [Permissioned Resolver](/ensv2/permissioned-resolver). The salt is derived from the owner's address so that any client can predict the resolver address before it exists. ```ts [Viem] const resolverInitAbi = parseAbi([ 'function initialize((address account, uint256 roleBitmap)[] grants, bytes[] calls)', ]) // Salt scheme: keccak256("OwnedResolver", owner, version) const version = 0n const resolverSalt = BigInt( keccak256( encodeAbiParameters( [{ type: 'bytes32' }, { type: 'address' }, { type: 'uint256' }], [keccak256(stringToHex('OwnedResolver')), account.address, version] ) ) ) const resolverInitData = encodeFunctionData({ abi: resolverInitAbi, functionName: 'initialize', args: [[{ account: account.address, roleBitmap: ALL_ROLES }], []], }) const resolverTx = await wallet.writeContract({ address: VERIFIABLE_FACTORY, abi: verifiableFactoryAbi, functionName: 'deployProxy', args: [PERMISSIONED_RESOLVER_IMPL, resolverSalt, resolverInitData], }) const resolverReceipt = await client.waitForTransactionReceipt({ hash: resolverTx, }) const [resolverLog] = parseEventLogs({ abi: verifiableFactoryAbi, eventName: 'ProxyDeployed', logs: resolverReceipt.logs, }) const resolverAddress = resolverLog.args.proxyAddress ``` The `resolverAddress` is now a fully initialized Permissioned Resolver proxy. Point a name to it via `setResolver` on the registry, then use it to [set records and delegate access](/ensv2/permissioned-resolver#code-examples). #### Deploying a Registry Proxy Deploy a per-name [User Registry](/ensv2/permissioned-registry) for managing subnames. The salt is derived from the name's namehash. ```ts [Viem] const registryInitAbi = parseAbi([ 'function initialize((address account, uint256 roleBitmap)[] grants)', ]) // Salt scheme: keccak256("UserRegistry", namehash, version) const version = 0n const registrySalt = BigInt( keccak256( encodeAbiParameters( [{ type: 'bytes32' }, { type: 'bytes32' }, { type: 'uint256' }], [keccak256(stringToHex('UserRegistry')), namehash('alice.eth'), version] ) ) ) const registryInitData = encodeFunctionData({ abi: registryInitAbi, functionName: 'initialize', args: [[{ account: account.address, roleBitmap: ALL_ROLES }]], }) const registryTx = await wallet.writeContract({ address: VERIFIABLE_FACTORY, abi: verifiableFactoryAbi, functionName: 'deployProxy', args: [USER_REGISTRY_IMPL, registrySalt, registryInitData], }) const registryReceipt = await client.waitForTransactionReceipt({ hash: registryTx, }) const [registryLog] = parseEventLogs({ abi: verifiableFactoryAbi, eventName: 'ProxyDeployed', logs: registryReceipt.logs, }) const registryAddress = registryLog.args.proxyAddress ``` The `registryAddress` is now a User Registry proxy. Set it as the subregistry for a name via `setSubregistry` on the parent registry, then use it to [manage subnames and roles](/ensv2/permissioned-registry#code-examples). import { EnsipHeader } from "../../components/EnsipHeader"; ## ENSIP-1: ENS <EnsipHeader authors={["nick.eth"]} created="April 4, 2016" status="final" /> ### Abstract This ENSIP describes the details of the Ethereum Name Service, a proposed protocol and ABI definition that provides flexible resolution of short, human-readable names to service and resource identifiers. This permits users and developers to refer to human-readable and easy to remember names, and permits those names to be updated as necessary when the underlying resource (contract, content-addressed data, etc) changes. The goal of domain names is to provide stable, human-readable identifiers that can be used to specify network resources. In this way, users can enter a memorable string, such as 'vitalik.wallet' or '[www.mysite.swarm](http://www.mysite.swarm)', and be directed to the appropriate resource. The mapping between names and resources may change over time, so a user may change wallets, a website may change hosts, or a swarm document may be updated to a new version, without the domain name changing. Further, a domain need not specify a single resource; different record types allow the same domain to reference different resources. For instance, a browser may resolve 'mysite.swarm' to the IP address of its server by fetching its A (address) record, while a mail client may resolve the same address to a mail server by fetching its MX (mail exchanger) record. ### Motivation Existing [specifications](https://github.com/ethereum/wiki/wiki/Registrar-ABI) and [implementations](https://ethereum.gitbooks.io/frontier-guide/content/registrar_services.html) for name resolution in Ethereum provide basic functionality, but suffer several shortcomings that will significantly limit their long-term usefulness: * A single global namespace for all names with a single 'centralised' resolver. * Limited or no support for delegation and sub-names/sub-domains. * Only one record type, and no support for associating multiple copies of a record with a domain. * Due to a single global implementation, no support for multiple different name allocation systems. * Conflation of responsibilities: Name resolution, registration, and whois information. Use-cases that these features would permit include: * Support for subnames/sub-domains - eg, live.mysite.tld and forum.mysite.tld. * Multiple services under a single name, such as a DApp hosted in Swarm, a Whisper address, and a mail server. * Support for DNS record types, allowing blockchain hosting of 'legacy' names. This would permit an Ethereum client such as Mist to resolve the address of a traditional website, or the mail server for an email address, from a blockchain name. * DNS gateways, exposing ENS domains via the Domain Name Service, providing easier means for legacy clients to resolve and connect to blockchain services. The first two use-cases, in particular, can be observed everywhere on the present-day internet under DNS, and we believe them to be fundamental features of a name service that will continue to be useful as the Ethereum platform develops and matures. The normative parts of this document does not specify an implementation of the proposed system; its purpose is to document a protocol that different resolver implementations can adhere to in order to facilitate consistent name resolution. An appendix provides sample implementations of resolver contracts and libraries, which should be treated as illustrative examples only. Likewise, this document does not attempt to specify how domains should be registered or updated, or how systems can find the owner responsible for a given domain. Registration is the responsibility of registrars, and is a governance matter that will necessarily vary between top-level domains. Updating of domain records can also be handled separately from resolution. Some systems, such as swarm, may require a well defined interface for updating domains, in which event we anticipate the development of a standard for this. ### Specification #### Overview The ENS system comprises three main parts: * The ENS registry * Resolvers * Registrars The registry is a single contract that provides a mapping from any registered name to the resolver responsible for it, and permits the owner of a name to set the resolver address, and to create subdomains, potentially with different owners to the parent domain. Resolvers are responsible for performing resource lookups for a name - for instance, returning a contract address, a content hash, or IP address(es) as appropriate. The resolver specification, defined here and extended in other ENSIPs, defines what methods a resolver may implement to support resolving different types of records. Registrars are responsible for allocating domain names to users of the system, and are the only entities capable of updating the ENS; the owner of a node in the ENS registry is its registrar. Registrars may be contracts or externally owned accounts, though it is expected that the root and top-level registrars, at a minimum, will be implemented as contracts. Resolving a name in ENS is a two-step process. First, the ENS registry is called with the name to resolve, after hashing it using the procedure described below. If the record exists, the registry returns the address of its resolver. Then, the resolver is called, using the method appropriate to the resource being requested. The resolver then returns the desired result. For example, suppose you wish to find the address of the token contract associated with 'beercoin.eth'. First, get the resolver: ```javascript var node = namehash("beercoin.eth"); var resolver = ens.resolver(node); ``` Then, ask the resolver for the address for the contract: ```javascript var address = resolver.addr(node); ``` Because the `namehash` procedure depends only on the name itself, this can be precomputed and inserted into a contract, removing the need for string manipulation, and permitting O(1) lookup of ENS records regardless of the number of components in the raw name. #### Name Syntax ENS names must conform to the following syntax: ```go <domain> ::= <label> | <domain> "." <label> <label> ::= any valid string label per [UTS46](https://unicode.org/reports/tr46/) ``` In short, names consist of a series of dot-separated labels. Each label must be a valid normalised label as described in [UTS46](https://unicode.org/reports/tr46/) with the options `transitional=false` and `useSTD3AsciiRules=true`. For Javascript implementations, a [library](https://www.npmjs.com/package/idna-uts46) is available that normalises and checks names. Note that while upper and lower case letters are allowed in names, the UTS46 normalisation process case-folds labels before hashing them, so two names with different case but identical spelling will produce the same namehash. Labels and domains may be of any length, but for compatibility with legacy DNS, it is recommended that labels be restricted to no more than 64 characters each, and complete ENS names to no more than 255 characters. For the same reason, it is recommended that labels do not start or end with hyphens, or start with digits. #### namehash algorithm Before being used in ENS, names are hashed using the 'namehash' algorithm. This algorithm recursively hashes components of the name, producing a unique, fixed-length string for any valid input domain. The output of namehash is referred to as a 'node'. Pseudocode for the namehash algorithm is as follows: ```go def namehash(name): if name == '': return '\0' * 32 else: label, _, remainder = name.partition('.') return sha3(namehash(remainder) + sha3(label)) ``` Informally, the name is split into labels, each label is hashed. Then, starting with the last component, the previous output is concatenated with the label hash and hashed again. The first component is concatenated with 32 '0' bytes. Thus, 'mysite.swarm' is processed as follows: ```javascript node = '\0' * 32 node = sha3(node + sha3('swarm')) node = sha3(node + sha3('mysite')) ``` Implementations should conform to the following test vectors for namehash: ```javascript namehash('') = 0x0000000000000000000000000000000000000000000000000000000000000000 namehash('eth') = 0x93cdeb708b7545dc668eb9280176169d1c33cfd8ed6f04690a0bcc88a93fc4ae namehash('foo.eth') = 0xde9b09fd7c5f901e23a3f19fecc54828e9c848539801e86591bd9801b019f84f ``` #### Registry specification The ENS registry contract exposes the following functions: ```solidity function owner(bytes32 node) constant returns (address); ``` Returns the owner (registrar) of the specified node. ```solidity function resolver(bytes32 node) constant returns (address); ``` Returns the resolver for the specified node. ```solidity function ttl(bytes32 node) constant returns (uint64); ``` Returns the time-to-live (TTL) of the node; that is, the maximum duration for which a node's information may be cached. ```solidity function setOwner(bytes32 node, address owner); ``` Transfers ownership of a node to another registrar. This function may only be called by the current owner of `node`. A successful call to this function logs the event `Transfer(bytes32 indexed, address)`. ```solidity function setSubnodeOwner(bytes32 node, bytes32 label, address owner); ``` Creates a new node, `sha3(node, label)` and sets its owner to `owner`, or updates the node with a new owner if it already exists. This function may only be called by the current owner of `node`. A successful call to this function logs the event `NewOwner(bytes32 indexed, bytes32 indexed, address)`.
프로젝트로 돌아가기