diff --git a/plans/2026-11-20-names-dispute-period.md b/plans/2026-11-20-names-dispute-period.md new file mode 100644 index 000000000..f36d1e0b1 --- /dev/null +++ b/plans/2026-11-20-names-dispute-period.md @@ -0,0 +1,152 @@ +# Names: a registration in its dispute period + +To be merged together with simplex-network/ens-contracts#51, the dispute period for sponsored registrations. + +## Problems + +1. After #51, a controller of the `.simplex` registrar, such as the controller contract on the request of its owner or guardian, can end a registration in its dispute period, and the registrar sets the name's expiry to 0. On its v1 route, the resolver answers every name with expiry 0 with the message "this name has never been registered". In the resolver's README, `unregistered` is described as never registered and `registered` as held until `expires`, and in the protocol a registered name is described as held until `expires`. +2. Clients do not learn until when a registration can be ended. Until then, the registration can be ended also after the name was moved to a recipient by a claim, and its renewal is refused. By decision D8 of the [contract plan](https://github.com/brenzi/simplex-namespace-contract/blob/main/docs/plans/dispute-period.md#L20), clients show the dispute end before a claim. + +## Decisions + +| # | Decision | +|---|---| +| 1 | `status` and `error` stay `unregistered` | +| 2 | message of a v1 404 `unregistered`: "this name is not registered" | +| 3 | price quotes of a name with expiry 0 unchanged | +| 4 | the registrar's `disputeUntil(uint256)` read for the 2LD's token, in the round of `nameExpires` | +| 5 | `disputeUntil`: the registrar's value while later than `lastBlockTs`, otherwise 0; unknown when the node answers the read with another error, or with an empty answer: null in v2 and v1, absent in RNAME | +| 6 | a revert of the `disputeUntil` call read as 0: a JSON-RPC error with code 3, or with code -32000 and the message "execution reverted", or a failed call in a multicall; another JSON-RPC error and an empty answer read as unknown; a failed request to the node answered 502 | +| 7 | a subname reported with its 2LD's `disputeUntil` | +| 8 | `NRRegistered.disputeUntil :: Maybe SystemSeconds`, after `graceUntil`, JSON derived as for the other fields; its Haddock states a date, 0 and absent | +| 9 | SMP version unchanged; a client does not read the absence of `disputeUntil` as 0 | + +## What the resolver answers + +``` +name_status(name): + token = labelhash of the 2LD + expires = registrar.nameExpires(token) + now = timestamp of the latest block + disputeUntil = case registrar.disputeUntil(token) of + a value > now -> the value + another value -> 0 + a revert -> 0 + another JSON-RPC error, or empty -> unknown + a failed request to the node -> the lookup answered 502 +``` + +```mermaid +stateDiagram-v2 + [*] --> disputable: sponsored registration, 14 to 120 days + [*] --> final: registration without a dispute period + disputable --> final: at disputeUntil + disputable --> unregistered: ended by a controller of the registrar + final --> lapsed: expiry and grace passed + unregistered --> [*]: available to any registration + lapsed --> [*]: available to any registration +``` + +For a 2LD, with `disputeUntil` a field of `registered` alone (– in the other types): + +| State | v2 `type` | v2 `disputeUntil` | RNAME `disputeUntil` | v1 `status` | v1 `disputeUntil` | +|---|---|---|---|---|---| +| disputable | `registered` | its end | its end | `registered` | its end | +| final | `registered` | 0 | 0 | `registered` or `grace` | 0 | +| lapsed | `available` or `reserved` | – | – | `expired` (410) | 0 | +| unregistered | `available` or `reserved` | – | – | `unregistered` (404), "this name is not registered" | 0 | + +A `disputeUntil` read answered with another JSON-RPC error, or with an empty answer: null in v2 and v1, absent in RNAME. + +```mermaid +sequenceDiagram + participant C as Client + participant P as Proxy + participant R as Names router + participant S as Resolver + participant N as Node + C->>P: PFWD with RSLV + P->>R: RFWD + R->>S: GET /v2/resolve/query + S->>N: one multicall: nameExpires, disputeUntil (added), GRACE_PERIOD and the other reads of the round + N-->>S: disputeUntil reverted by a registrar before #51 + S-->>R: registered, with disputeUntil: its end, or 0; null after another JSON-RPC error (added) + R->>R: decoded into NRRegistered with disputeUntil, null decoded as Nothing (added) + R-->>P: RRES with RNAME, encoded at the forwarded version, at most 23 + P-->>C: PRES +``` + +## Threat model + +- A router or its resolver can omit `disputeUntil` or state a false one, as it can `expires`; a client verifies it only by reading the registrar. +- `disputeUntil` is public on chain ([contract plan, D9](https://github.com/brenzi/simplex-namespace-contract/blob/main/docs/plans/dispute-period.md#L21)), and with it the dispute days of the payment: 0, 14 or 120. In the answer, it is disclosed to the router and the client as on chain. +- After a JSON-RPC error of the `disputeUntil` call alone, other than a revert, the dispute end is unknown: null from the resolver, left out of RNAME. +- A revert answered by the node is read as 0, so the resolver relies on its node for 0 as for every other read. +- A label the registrar recorded stays recorded after the registration expired or was ended, so whoever runs the resolver matches a hashed query of such a name to its label. + +## Changes + +`scripts/resolver/service/snrc-resolve.py`: + +- the message of decision 2 +- the docstring of `read_oracle_prices`: a quote is safe for a name with expiry 0 +- `dispute_until_call`, read in `lookup_reads` +- `CallReverted`: a JSON-RPC error with code 3, or with code -32000 and the message "execution reverted", and a call failed in a multicall +- `dispute_end`: the registrar's `disputeUntil` when later than the block, 0 otherwise and on a revert, None on another error or an empty answer +- `name_status`: `disputeUntil`, also in v1 answers +- `registration`: `disputeUntil` in `registered`, null when unknown +- the comment on the reads keyed on the labelhash: `disputeUntil` +- the docstring of `expiry_status`: any name with a zero expiry + +`scripts/resolver/README.md`: + +- `expires` and `registered`: unless the registration is ended in its dispute period +- `unregistered`: also an ended registration +- the zero-expiry paragraph, with the dispute period defined +- the error example +- what a hashed query hides +- the premium paragraph +- `disputeUntil` in the v1 example, in `registered` and in the definition of the dispute period +- a subname's dispute end in v2 +- `disputeUntil` in the lists of status fields and of the registrar's reads +- the source of each status field, and when it is null or 0, also in the error example +- a name never registered looked up by its hash alone +- `lastBlockTs` in the v1 example, the price keys of the error example, and `disputeUntil` beside `nameRecord` in v2 +- a lookup answered 502 when a request to the node fails + +`protocol/simplex-messaging.md`: + +- a hashed query of a name nobody holds: `available` or `reserved` +- `registered`: unless ended before `disputeUntil`, and renewable not before it +- the dispute period, defined by a `disputeUntil` after `lastBlockTs` +- `disputeUntil` in the fields of `registered`: a date, 0, or absent when unknown +- `disputeUntil`, the one field left out when it could not be read, in the conditions of `ERR NAME RESOLVER` +- `disputeUntil` unverified by a client, as `expires` +- an answer below v22: no dispute end + +`src/Simplex/Messaging/Names/Record.hs`: `NRRegistered.disputeUntil`, with the Haddock of decision 8. + +`src/Simplex/Messaging/Protocol.hs`: `disputeUntil = Nothing` in the answer of a router before v22. + +## Tests + +Each test of changed behavior is committed before its change, and fails in CI on the commit before that change. + +`scripts/resolver/service/test_snrc_resolve.py`: + +- `ErrorCodeTests`: a name with expiry 0 answered 404 with "this name is not registered" +- three test names that equate expiry 0 with never registered +- `NameStatusTests`: a `disputeUntil` later than the block reported; one at the block, one before it and 0 reported as 0; a revert, the node's error with code 3 or with code -32000 and "execution reverted", read as 0; a subname read with its 2LD's token; `disputeUntil` in the keys of every branch +- `RegistrationV2Tests`: v2 `registered` with `disputeUntil`, with 0, and with null when the node answers the read with another error; 0 in the pinned keys of `registered`; v1 with it, with 0 and with null +- `BatchedReadsTests`: `disputeUntil` read in the round of `nameExpires`, in two round trips; a revert read as 0 in a multicall and in a batch +- the fakes of the registrar answer `disputeUntil` + +Regression tests, passing in CI on the commit before their change as well: + +- `RegistrationV2Tests`: a subname under a 2LD with expiry 0, whose node has no owner while the subnode keeps a former holder: v2 `available`, v1 404 +- `NameStatusTests`: another JSON-RPC error and an empty answer read as unknown +- `tests/SMPNamesTests.hs`: a dispute end of 0, as the resolver serves it, decoded into `NRRegistered`, and its JSON round trip; a null dispute end decoded as `Nothing`, and left out of RNAME + +`tests/SMPNamesTests.hs`: the router's answer to a registration with `disputeUntil`, as the resolver serves it, decoded into `NRRegistered`; the JSON round trip of that value. + +`tests/RSLVTests.hs`: RNAME of that registration, direct and forwarded through a proxy. diff --git a/protocol/simplex-messaging.md b/protocol/simplex-messaging.md index 989884e3f..82d9ff1f9 100644 --- a/protocol/simplex-messaging.md +++ b/protocol/simplex-messaging.md @@ -1501,8 +1501,9 @@ look up what the hash stands for without ever being told. The router is not trusted for it: a client MUST check that the record names the name it asked about, and reject the answer otherwise. A registry that does not record the label cannot answer a hashed query at all, and the router answers `ERR NAME -RESOLVER` rather than a record it knows the client will reject. An unregistered -name has no recorded label, so it cannot be looked up either. +RESOLVER` rather than a record it knows the client will reject. A name nobody +holds is answered `available` or `reserved`; in both, the name is omitted, so a +hashed query of it is answered from the hash alone. **Server-side validation.** The names router parses `domain` as a fully-qualified name (TLD required — bare labels are rejected) and forwards it @@ -1518,7 +1519,7 @@ several configured servers can act on distinctly: | `RNAME` | the router read the registry | use it | | `ERR NAME NOT_FOUND` | below v22 only: every name that does not resolve. From v22 a router never sends it | stop, and do not read it as registrable | | `ERR NAME NO_RESOLVER` | this router has no resolver (names role not enabled) | skip this server, try the next | -| `ERR NAME RESOLVER ` | the router cannot state an answer completely: no registrar or price oracle for the TLD, an unreachable chain, a transport failure, a timeout, a registration it could not date or resolve | surface ``; retry only if it reads as transient | +| `ERR NAME RESOLVER ` | the router cannot state an answer completely: no registrar or price oracle for the TLD, an unreachable chain, a transport failure, a timeout, a registration it could not date or resolve; a `disputeUntil` that could not be read is left out instead | surface ``; retry only if it reads as transient | A client SHOULD NOT broadcast a `name` to further servers after a name-capable router has answered (`NOT_FOUND` or `RESOLVER`), since that router has already @@ -1551,14 +1552,23 @@ MUST NOT treat an answer as current without checking it. | `type` | Meaning | |---|---| -| `registered` | held by someone until `expires`, renewable by its owner alone until `graceUntil`. It always carries `nameRecord`: where the owner set none, every field is unset and the resolver address is zero | +| `registered` | held by someone until `expires`, unless the registration is ended before `disputeUntil`; renewable by its owner alone until `graceUntil`, and not before `disputeUntil`. It always carries `nameRecord`: where the owner set none, every field is unset and the resolver address is zero | | `available` | held by nobody and registrable now, at `pricing` | | `reserved` | held back by the registry and not registered. It carries no price, and a router MUST NOT quote one | +A registration answered with a `disputeUntil` after `lastBlockTs` is in its +dispute period: until then, its renewal is refused, and a controller of the +registry's registrar can end it; a router then answers for the name as for a +name never registered. On `.simplex`, a registration made with the controller's +`registerSponsored` has a dispute period of 14 to 120 days from its +registration. As with `expires`, a client does not verify `disputeUntil`: a +router can omit or misstate it. + | Field | On | JSON type | Constraints | |---|---|---|---| | `expires` | `registered` | number | absent only from a v20/v21 router, which sent the record alone | | `graceUntil` | `registered` | number | after `expires`; until here only the owner may renew. Absent on the same condition as `expires` | +| `disputeUntil` | `registered` | number | after `lastBlockTs`: the end of the dispute period; 0: the registration cannot be ended. A client compares a time with `lastBlockTs`, and reads one not after it as 0. Absent when unknown: when it could not be read, and from a router or resolver that predates it; a client MUST NOT read its absence as 0 | | `reservedReason_` | `registered` | string | a reason word, present only when the name is held back as well | | `nameRecord` | `registered` | object | the record, schema below | | `pricing` | `available` | object | `registrationPrices`, `basePrice` and `minLabelLength`, below | @@ -1589,7 +1599,7 @@ refuses: a hashed query carries no length, so only the client can check it. Below v22, `RNAME` carries the bare record and nothing else, and every answer without one is `ERR NAME NOT_FOUND`. A v22 client reads such an answer as -`registered` with no expiry, grace or reservation. +`registered` with no expiry, grace, dispute end or reservation. From v22 a client MUST NOT read `ERR NAME NOT_FOUND` as "registrable": only `available` says that. @@ -1597,7 +1607,8 @@ From v22 a client MUST NOT read `ERR NAME NOT_FOUND` as "registrable": only A router that cannot state an answer completely MUST send `ERR NAME RESOLVER ` rather than answer partially or guess. That covers a TLD with no registrar or price oracle, an unreachable chain, a timeout, a registration it -could not date or resolve, and any status word it does not recognise. +could not date or resolve, and any status word it does not recognise. The one +exception is `disputeUntil`, which is left out when it could not be read. `nameRecord` MUST be a UTF-8 JSON object with the following schema: diff --git a/scripts/resolver/README.md b/scripts/resolver/README.md index adc0745d8..6d7f23205 100644 --- a/scripts/resolver/README.md +++ b/scripts/resolver/README.md @@ -80,7 +80,7 @@ curl -s http://127.0.0.1:8000/resolve/foobar.testing | jq **4. the route your router will call** (check 3 passes on an older resolver too): ```sh curl -s http://127.0.0.1:8000/v2/resolve/foobar.testing | jq -# → {"type":"registered","expires":1780000000,"graceUntil":…,"nameRecord":{…}} +# → {"lastBlockTs":1779990000,"registration":{"type":"registered","expires":1780000000,"graceUntil":…,"disputeUntil":0,"reservedReason_":null,"nameRecord":{…}}} ``` **Wire your smp-server:** in its `[NAMES]` section set @@ -153,11 +153,12 @@ carries are specified once, in the **Name response** section of [`protocol/simplex-messaging.md`](../../protocol/simplex-messaging.md). It is the wire format, so it is documented with the wire. -Two things follow from that and are worth stating here. Expiry and grace belong -to the registration, not to the record: `expires` and `graceUntil` sit beside -`nameRecord`, not inside it. And a name nobody holds is not an error: it -answers 200 with `type: available` and its price, so no status code from this -route means "not registered". +Two things follow from that and are worth stating here. Expiry, grace and the +dispute end belong to the registration, not to the record: `expires`, +`graceUntil` and `disputeUntil` are fields beside `nameRecord`, not inside it. +And a name nobody holds is not an error: it is answered 200 with +`type: available` and its price, so no status code from this route means +"not registered". | Status | Meaning | |---|---| @@ -172,17 +173,17 @@ Error bodies carry `name` and a fixed `error` code to branch on. Only label, so a hashed query cannot be answered with a name. See [Querying by labelhash](#querying-by-labelhash). -A subname reports the expiry and grace of the 2LD above it, since that is what -bounds its lifetime. A subname is answered only while it is held: owned in the -registry by the 2LD's holder, or by the subname registrar that the registrar's -`subnameHook()` names, while its `ownerOf` names a holder. Any other subname, -created or not, reports as not registered. +A subname is answered with the expiry, grace and dispute end of its 2LD, on +which its lifetime depends. A subname is answered only while it is held: owned +in the registry by the 2LD's holder, or by the subname registrar that the +registrar's `subnameHook()` names, while its `ownerOf` names a holder. Any other +subname, created or not, is answered as not registered. ### v1: `/resolve/` What routers before SMP v22 call. Its shape is unrelated to v2's: the record is -flat, and `status`, `expires`, `graceEnds`, `reasonCode` and `reason` sit -alongside its fields. +flat, and `status`, `expires`, `graceEnds`, `disputeUntil`, `reasonCode` and +`reason` are keys beside its fields. #### v1 response shape @@ -195,8 +196,10 @@ alongside its fields. "eth": null, "btc": "bc1q…", "xmr": "4ANz…", "dot": "139G…", "owner": "0xd83b…", "resolver": "0x80fa…", "status": "registered", // registered | grace | expired | unregistered | unknown - "expires": 1780000000, // Unix seconds; when the registration ends + "lastBlockTs": 1779990000, // Unix seconds; the block the status was read at + "expires": 1780000000, // Unix seconds; when the registration ends, unless it is ended in its dispute period "graceEnds": 1787776000, // expires + GRACE_PERIOD; last moment the owner can renew + "disputeUntil": 0, // Unix seconds; until then the registration can be ended and cannot be renewed; 0 when it cannot be ended, null when unknown "reasonCode": null, // set when the name is held back as well "reason": null // set when the name is held back as well } @@ -210,17 +213,20 @@ identically (`bar.foobar.testing`). #### v1 registration status and expiry -A response carries `status`, `expires` and `graceEnds` whenever the resolver -read them, a successful resolve included, so a client that has just resolved a -name already knows when it expires. Both timestamps are Unix seconds, and -`null` when they could not be read. +A response contains `status`, `expires`, `graceEnds` and `disputeUntil` +whenever the resolver read them, a successful resolve included, so a client that +has just resolved a name already knows when it expires. The timestamps are Unix +seconds. All are `null` when no registrar is configured, `expires` and +`graceEnds` also for a zero expiry, and `disputeUntil` also when the node +answered its read with an error other than a revert, or with an empty answer; +`disputeUntil` is 0 when the registration cannot be ended. | `status` | Meaning | |---|---| -| `registered` | live; `expires` is when that ends | +| `registered` | live; `expires` is when that ends, unless the registration is ended before `disputeUntil` | | `grace` | lapsed, but only the previous owner may renew it, until `graceEnds` | | `expired` | lapsed and past grace; anyone may register it | -| `unregistered` | never registered, and free to take | +| `unregistered` | never registered, or its registration was ended in its dispute period; free to take | | `unknown` | no `SNRC_REGISTRAR_` configured, so status could not be read | A reservation is orthogonal to the status: a name held back by the registry @@ -231,9 +237,20 @@ rule, `expires + GRACE_PERIOD < now`. `GRACE_PERIOD` is read from the contract rather than assumed, and `now` is the latest block's timestamp rather than the host clock, which the registrar compares against too, so a machine with a wrong clock cannot misreport a registration. That rule alone is not enough: it also -holds for a name nobody ever registered (`0 + GRACE_PERIOD < now`), so a zero -expiry is what separates *never registered* from *registered and since -released*. +holds for a name nobody ever registered (`0 + GRACE_PERIOD < now`), so the +resolver tells `unregistered` from `expired` by a zero expiry. On `.simplex`, a +registration made through the controller's `registerSponsored` has a dispute +period of 14 to 120 days, and the registrar stores its end as `disputeUntil`. +Within it, a renewal is refused, and a registrar controller can end the +registration, such as the controller on the request of its owner or guardian +(`beneficiary`); the registrar then sets a zero expiry. +The resolver reports that end as `disputeUntil` while it is later than `now`, +and 0 otherwise. The call to a registrar from before dispute periods, such as +`.testing`'s, reverts, and is read as 0: a revert is a JSON-RPC error with code +3, or with code -32000 and the message "execution reverted", or a failed call in +a multicall. With any other JSON-RPC error, or an empty answer, `disputeUntil` +is unknown and null, also on v2; when a request to the node fails, the lookup is +answered 502. A subname reports the status of the 2LD above it, which is only as good as the name it sits under. A subname that is not held, as v2 defines it, answers 404 @@ -247,8 +264,10 @@ which is free to change. ```jsonc {"name": "nope.testing", "error": "unregistered", - "message": "this name has never been registered", - "status": "unregistered", "expires": null, "graceEnds": null} + "message": "this name is not registered", + "status": "unregistered", "lastBlockTs": 1780000000, "expires": null, + "graceEnds": null, "disputeUntil": 0, "reasonCode": null, "reason": null} +// with a price oracle configured, also registrationPrices, basePrice and minLabelLength ``` The codes are `tldNotConfigured`, `notFullyQualified`, `unregistered`, @@ -284,16 +303,16 @@ curl -s "http://127.0.0.1:8000/resolve/[$(printf acme | keccak-256sum | cut -d' ``` namehash is `keccak(parent || keccak(label))`, so this reaches the same node and -returns the same record. The registrar keys `nameExpires` and `reservedNames` on -the labelhash too, so the status fields do not need the label either. The -resolver learns the name only by guessing the label and hashing it. +returns the same record. The registrar keys `nameExpires` and `disputeUntil`, +and the name policy or the controller keys `reservedNames`, on the labelhash +too, so the status fields are read without the label as well. Only the second-level label is a registry key, and `status` decodes a bracket there at any depth. The record does not: a bracket is decoded only in a two-label name, so `sub.[].testing` is not a supported query. Subname labels stay text; a bracket label left of the 2LD is an ordinary label. Routers -from v22 send every 2LD this way, so a registrable name normally never reaches -this service. +from v22 send every 2LD this way, so a name never registered is normally looked +up here by its hash alone. On v2, read `type`: only `available` means the name is free. On v1, read `status`: a name is free on `unregistered` (404) and on `expired` (410), every @@ -318,10 +337,13 @@ created by the 2LD's owner. A bracket label in a subname is hashed as written, so it points at a node nobody can own. ENS tooling accepts the bracketed form at any depth; this resolver does not, on purpose. -This hides interest in a name and nothing else: the registration itself is -public, and commit-reveal covers that step. A short or well-known label is easy -to guess by hashing candidates, and the reveal publishes the labelhash, so an -operator who logged the query can match it to the name afterwards. +Interest in a name is hidden only while the registrar has no label recorded for +it: for a name registered before, also one expired or ended in its dispute +period, the resolver reads the recorded label (`labelOf`) with the query. The +registration itself is public, and commit-reveal covers that step. A short or +well-known label is easy to guess by hashing candidates, and the reveal +publishes the labelhash, so an operator who logged the query can match it to the +name afterwards. ### What a name costs @@ -331,7 +353,7 @@ through `prices()`, in US cents per year, which is the unit this API carries. An ENS-shaped oracle exposes only `price1Letter()`..`price6Letter()`, in attoUSD per second, and charges a premium on a lapsed name that it does not expose. A -quote from one is therefore only safe for a name that was never registered: an +quote from one is therefore only safe for a name with a zero expiry: an `expired` name gets no price rather than one below what the registrar charges. **Set `SNRC_CONTROLLER_` wherever `SNRC_REGISTRAR_` is.** Without a @@ -366,16 +388,17 @@ The resolver reads three contracts, each configured per TLD, the name policy a controller names, and the subname registrar a registrar names. The **registry** answers who owns a node, and `/resolve` reads the records from -it. The **registrar** (ERC-721) holds `nameExpires` and `GRACE_PERIOD`, which -is where every expiry field comes from, and `labelOf`, which is how a hashed -query is answered with a name. A name registered without recording its label -cannot answer one, and `/v2/resolve` refuses it rather than answer with a name -the client will reject. Its `subnameHook()` names the subname registrar, whose -`ownerOf` says who holds a subname it owns. With no registrar for a TLD, -`/resolve` still works and reports `"status": "unknown"`, and only subnames the -2LD's holder owns in the registry are answered. The **controller** holds -`reservedNames`, which is where `reasonCode` comes from. With no controller a -held-back name reads as not reserved, and no name can be priced. +it. The **registrar** (ERC-721) holds `nameExpires` and `GRACE_PERIOD`, the +source of every expiry field; `disputeUntil`, the end of a dispute period; and +`labelOf`, which is how a hashed query is answered with a name. A +name registered without recording its label cannot answer one, and +`/v2/resolve` refuses it rather than answer with a name the client will reject. +Its `subnameHook()` names the subname registrar, whose `ownerOf` says who holds +a subname it owns. With no registrar for a TLD, `/resolve` still works and +reports `"status": "unknown"`, and only subnames the 2LD's holder owns in the +registry are answered. The **controller** holds `reservedNames`, which is where +`reasonCode` comes from. With no controller a held-back name reads as not +reserved, and no name can be priced. All three default to the mainnet `.testing` deployment. `.simplex` is unset until it is deployed. diff --git a/scripts/resolver/service/snrc-resolve.py b/scripts/resolver/service/snrc-resolve.py index b017f196e..b60fb9aec 100755 --- a/scripts/resolver/service/snrc-resolve.py +++ b/scripts/resolver/service/snrc-resolve.py @@ -326,6 +326,16 @@ def request_reads(): del _request.reads +class CallReverted(RuntimeError): + pass + + +def rpc_error(error) -> RuntimeError: + code, message = (error.get("code"), error.get("message")) if isinstance(error, dict) else (None, None) + reverted = code == 3 or (code, message) == (-32000, "execution reverted") + return CallReverted(error) if reverted else RuntimeError(error) + + def rpc(method, params): reads = getattr(_request, "reads", None) if reads is not None: @@ -336,7 +346,7 @@ def rpc(method, params): return read res = _send_rpc({"jsonrpc": "2.0", "method": method, "params": params, "id": 1}) if "error" in res: - raise RuntimeError(res["error"]) + raise rpc_error(res["error"]) return res["result"] @@ -359,7 +369,7 @@ def _is_latest_call(method, params) -> bool: def _remember(reads, requests, answers): for (m, p), r in zip(requests, answers, strict=True): if r is not None and ("result" in r or "error" in r): - reads[_read_key(m, p)] = RuntimeError(r["error"]) if "error" in r else r["result"] + reads[_read_key(m, p)] = rpc_error(r["error"]) if "error" in r else r["result"] def prefetch(requests): @@ -397,7 +407,7 @@ def prefetch(requests): _remember(reads, calls, _send_batch(calls)) return for (m, p), (success, data) in zip(calls, results, strict=True): - reads[_read_key(m, p)] = "0x" + data.hex() if success else RuntimeError("execution reverted") + reads[_read_key(m, p)] = "0x" + data.hex() if success else CallReverted("execution reverted") AGGREGATE3 = "0x82ad56cb" # aggregate3((address,bool,bytes)[]) @@ -508,9 +518,19 @@ def grace_period(registrar: str) -> int: return decode_uint(eth_call(*grace_call(registrar))) +def dispute_end(registrar: str, token: int, now: int): + try: + until = decode_uint(eth_call(*dispute_until_call(registrar, token))) + except CallReverted: + return 0 + except RuntimeError: + return None + return until if until > now else 0 + + def expiry_status(expires: int, grace: int, now: int) -> str: """The registrar's `available(id)` is not enough on its own: it is also - true for a name nobody registered, since 0 + GRACE_PERIOD < now.""" + true for a name with a zero expiry, since 0 + GRACE_PERIOD < now.""" if expires == 0: return "unregistered" if expires > now: @@ -576,7 +596,7 @@ def read_oracle_prices(controller: str, oracle: str): """SimplexPriceOracle keeps the curve in US cents per year, the unit the SMP protocol carries. An ENS-shaped oracle prices in attoUSD per second and charges a premium on lapsed names that it does not expose, so a quote from - it is only safe for a name that was never registered.""" + it is only safe for a name with a zero expiry.""" # either oracle shape is answered in the same round trip prefetch([eth_call_read(*prices_call(oracle))] + [eth_call_read(*letter_price_call(oracle, n)) for n in LETTER_TIERS]) try: @@ -647,11 +667,12 @@ def name_status(name: str): "lastBlockTs": None, "expires": None, "graceEnds": None, + "disputeUntil": None, "reasonCode": None, "reason": None, } - # nameExpires and reservedNames are keyed on uint256(keccak(label)). + # nameExpires, disputeUntil and reservedNames are keyed on uint256(keccak(label)). # The 2LD's label is that key at any depth. node_of decodes a bracket only # in a two-label name, so a bracket subname gets a status but no record. token = label_token(labels[-2]) @@ -671,6 +692,7 @@ def name_status(name: str): "lastBlockTs": now, "expires": expires or None, "graceEnds": (expires + grace) if expires else None, + "disputeUntil": dispute_end(registrar, token, now), "reasonCode": reason[0] if reason else None, "reason": reason[1] if reason else None, } @@ -803,6 +825,10 @@ def expires_call(registrar: str, token: int): return registrar, selector("nameExpires(uint256)") + encode_uint(token) +def dispute_until_call(registrar: str, token: int): + return registrar, selector("disputeUntil(uint256)") + encode_uint(token) + + def grace_call(registrar: str): return registrar, selector("GRACE_PERIOD()") @@ -863,7 +889,7 @@ def lookup_reads(name: str): registrar = REGISTRARS.get(tld) if registrar and len(labels) >= 2: token = label_token(labels[-2]) - reads += [BLOCK_READ, eth_call_read(*expires_call(registrar, token)), eth_call_read(*grace_call(registrar))] + reads += [BLOCK_READ, eth_call_read(*expires_call(registrar, token)), eth_call_read(*dispute_until_call(registrar, token)), eth_call_read(*grace_call(registrar))] if len(labels) == 2 and is_encoded_labelhash(labels[0]): reads.append(eth_call_read(*label_call(registrar, token))) if len(labels) > 2: @@ -1197,6 +1223,7 @@ def registration(name: str): "type": "registered", "expires": reg["expires"], "graceUntil": reg["graceEnds"], + "disputeUntil": reg["disputeUntil"], "reservedReason_": reg["reasonCode"], "nameRecord": rec, }) @@ -1240,7 +1267,7 @@ def resolve(name: str): **reg, "error": reg["status"], "message": ( - "this name has never been registered" + "this name is not registered" if reg["status"] == "unregistered" else "this registration expired and is open to anyone" ), diff --git a/scripts/resolver/service/test_snrc_resolve.py b/scripts/resolver/service/test_snrc_resolve.py index 46d756769..463e74af8 100644 --- a/scripts/resolver/service/test_snrc_resolve.py +++ b/scripts/resolver/service/test_snrc_resolve.py @@ -22,6 +22,7 @@ import time import unittest from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from unittest import mock from urllib.error import HTTPError from urllib.parse import urlparse from urllib.request import Request, urlopen @@ -203,22 +204,33 @@ class NameStatusTests(unittest.TestCase): GRACE = 90 * 86400 - def _expiry(self, value): + def _expiry(self, value, dispute_until=0): def eth_call(to, data): if data.startswith(snrc.selector("GRACE_PERIOD()")): return "0x" + snrc.encode_uint(self.GRACE) + if data.startswith(snrc.selector("disputeUntil(uint256)")): + return "0x" + snrc.encode_uint(dispute_until) self.assertTrue(data.startswith(snrc.selector("nameExpires(uint256)"))) return "0x" + snrc.encode_uint(value) return eth_call - def _keys(self, status, expires, grace_ends, read_at=-1): + def _node(self, dispute_answer): + answers = { + snrc.selector("nameExpires(uint256)"): {"result": "0x" + snrc.encode_uint(self.now + 3600)}, + snrc.selector("GRACE_PERIOD()"): {"result": "0x" + snrc.encode_uint(self.GRACE)}, + snrc.selector("disputeUntil(uint256)"): dispute_answer, + } + return lambda payload: answers[payload["params"][0]["data"][:10]] + + def _keys(self, status, expires, grace_ends, read_at=-1, dispute_until=0): """Every branch answers with the same keys; only some carry values.""" return { "status": status, "lastBlockTs": self.now if read_at == -1 else read_at, "expires": expires, "graceEnds": grace_ends, + "disputeUntil": dispute_until, "reasonCode": None, "reason": None, } @@ -267,7 +279,7 @@ def test_a_registrar_that_is_not_a_contract_is_an_error_not_a_free_name(self): with self.assertRaises(RuntimeError): snrc.name_status("alice.testing") - def test_zero_expiry_means_never_registered(self): + def test_zero_expiry_means_unregistered(self): snrc.eth_call = self._expiry(0) self.assertEqual( snrc.name_status("alice.testing"), @@ -301,7 +313,7 @@ def test_future_expiry_is_registered(self): self._keys("registered", future, future + self.GRACE), ) - def test_never_registered_is_not_confused_with_claimable(self): + def test_zero_expiry_is_not_confused_with_claimable(self): """`available(id)` is true for both, since 0 + GRACE < now.""" snrc.eth_call = self._expiry(0) self.assertEqual(snrc.name_status("alice.testing")["status"], "unregistered") @@ -333,12 +345,49 @@ def eth_call(to, data): snrc.name_status("x." + hashed + ".testing") self.assertTrue(seen[0].endswith(snrc.keccak(b"alice").hex())) + def test_a_dispute_end_after_the_block_is_reported(self): + snrc.eth_call = self._expiry(self.now + 3600, dispute_until=self.now + 1) + self.assertEqual(snrc.name_status("alice.testing")["disputeUntil"], self.now + 1) + + def test_a_dispute_end_not_after_the_block_is_reported_as_0(self): + for until in (self.now, self.now - 1, 0): + with self.subTest(until=until): + snrc.eth_call = self._expiry(self.now + 3600, dispute_until=until) + self.assertEqual(snrc.name_status("alice.testing")["disputeUntil"], 0) + + def test_a_reverted_dispute_end_is_reported_as_0(self): + snrc.eth_call = self._saved[2] + for code in (3, -32000): + answer = {"error": {"code": code, "message": "execution reverted"}} + with self.subTest(code=code), mock.patch.object(snrc, "_send_rpc", self._node(answer)): + reg = snrc.name_status("alice.testing") + self.assertEqual((reg["status"], reg["disputeUntil"]), ("registered", 0)) + + def test_a_dispute_end_the_node_could_not_read_is_unknown(self): + snrc.eth_call = self._saved[2] + for answer in ({"error": {"code": -32000, "message": "header not found"}}, {"result": "0x"}): + with self.subTest(answer=answer), mock.patch.object(snrc, "_send_rpc", self._node(answer)): + reg = snrc.name_status("alice.testing") + self.assertEqual((reg["status"], reg["disputeUntil"]), ("registered", None)) + + def test_a_subname_is_answered_with_the_dispute_end_of_its_2ld(self): + alice = snrc.dispute_until_call(self.REGISTRAR, snrc.label_token("alice")) + + def eth_call(to, data): + if data.startswith(snrc.selector("disputeUntil(uint256)")): + self.assertEqual((to, data), alice) + return "0x" + snrc.encode_uint(self.now + 1) + return "0x" + snrc.encode_uint(self.now + 3600) + + snrc.eth_call = eth_call + self.assertEqual(snrc.name_status("x.alice.testing")["disputeUntil"], self.now + 1) + def test_unconfigured_tld_is_unknown_rather_than_unregistered(self): snrc.REGISTRARS = {"testing": ""} snrc.eth_call = lambda *a: self.fail("must not reach the chain") self.assertEqual( snrc.name_status("alice.testing"), - self._keys("unknown", None, None, read_at=None), + self._keys("unknown", None, None, read_at=None, dispute_until=None), ) def test_every_branch_returns_the_same_keys(self): @@ -347,6 +396,7 @@ def test_every_branch_returns_the_same_keys(self): "lastBlockTs", "expires", "graceEnds", + "disputeUntil", "reasonCode", "reason", } @@ -585,6 +635,8 @@ def _chain(self, expires, oracle=None, reserved=0): def eth_call(to, data): if data.startswith(snrc.selector("nameExpires(uint256)")): return "0x" + snrc.encode_uint(expires) + if data.startswith(snrc.selector("disputeUntil(uint256)")): + return "0x" + snrc.encode_uint(0) if data.startswith(snrc.selector("GRACE_PERIOD()")): return "0x" + snrc.encode_uint(self.GRACE) if data.startswith(snrc.selector("reservedNames(bytes32)")): @@ -696,6 +748,8 @@ def _chain(self, expires, letter_cents=0): def eth_call(to, data): if data.startswith(snrc.selector("nameExpires(uint256)")): return "0x" + snrc.encode_uint(expires) + if data.startswith(snrc.selector("disputeUntil(uint256)")): + return "0x" + snrc.encode_uint(0) if data.startswith(snrc.selector("GRACE_PERIOD()")): return "0x" + snrc.encode_uint(self.GRACE) if data.startswith(snrc.selector("reservedNames(bytes32)")): @@ -714,7 +768,7 @@ def eth_call(to, data): return eth_call - def test_a_never_registered_name_is_priced_from_the_letter_curve(self): + def test_a_zero_expiry_name_is_priced_from_the_letter_curve(self): snrc.eth_call = self._chain(0) reg = snrc.name_status("ghost.testing") self.assertEqual(reg["status"], "unregistered") @@ -786,6 +840,11 @@ def test_a_registration_problem_reports_the_status_as_the_code(self): self.assertEqual(body["error"], code) self.assertEqual(body["status"], code) + def test_a_zero_expiry_is_404_not_registered(self): + snrc.eth_call = self._chain(0) + status, body = snrc.resolve("alice.testing") + self.assertEqual((status, body["message"]), (404, "this name is not registered")) + def test_a_name_in_grace_still_resolves(self): snrc.eth_call = self._chain(int(time.time()) - 3600) status, body = snrc.resolve("alice.testing") @@ -883,7 +942,7 @@ def _abi_bytes(value: bytes) -> str: return ("0x" + snrc.encode_uint(0x20) + snrc.encode_uint(len(value)) + (value + b"\x00" * pad).hex()) - def _chain(self, expires, reserved=0, oracle=None, label=b"acme", owner=None, holder=None, subname_holder=None): + def _chain(self, expires, reserved=0, oracle=None, label=b"acme", owner=None, holder=None, subname_holder=None, dispute_until=0): """The registry answers a zero resolver, so name_record returns the empty record a registered name still has. `label` is what the registrar recorded for the 2LD; b"" means it recorded none. `owner` is the owner of @@ -899,6 +958,10 @@ def eth_call(to, data): return self._abi_bytes(label) if data.startswith(snrc.selector("nameExpires(uint256)")): return "0x" + snrc.encode_uint(expires) + if data.startswith(snrc.selector("disputeUntil(uint256)")): + if dispute_until is None: + raise RuntimeError({"code": -32000, "message": "header not found"}) + return "0x" + snrc.encode_uint(dispute_until) if data.startswith(snrc.selector("GRACE_PERIOD()")): return "0x" + snrc.encode_uint(self.GRACE) if data.startswith(snrc.selector("reservedNames(bytes32)")): @@ -948,6 +1011,30 @@ def test_a_registered_name_that_is_held_back_says_so(self): self.assertEqual(body["type"], "registered") self.assertEqual(body["reservedReason_"], "internal") + def test_a_registration_in_its_dispute_period_is_answered_with_its_end(self): + snrc.eth_call = self._chain(self.now + 3600, dispute_until=self.now + 600) + _, body = registration("acme.testing") + self.assertEqual(body["type"], "registered") + self.assertEqual(body["disputeUntil"], self.now + 600) + + def test_a_registration_without_a_dispute_period_has_a_dispute_end_of_0(self): + snrc.eth_call = self._chain(self.now + 3600) + _, body = registration("acme.testing") + self.assertEqual(body["disputeUntil"], 0) + + def test_a_dispute_end_the_node_could_not_read_is_null(self): + snrc.eth_call = self._chain(self.now + 3600, dispute_until=None) + _, body = registration("acme.testing") + self.assertEqual(body["type"], "registered") + self.assertIsNone(body["disputeUntil"]) + + def test_v1_answers_contain_the_dispute_end(self): + for until, reported in ((self.now + 600, self.now + 600), (0, 0), (None, None)): + with self.subTest(until=until): + snrc.eth_call = self._chain(self.now + 3600, dispute_until=until) + status, body = snrc.resolve("acme.testing") + self.assertEqual((status, body["disputeUntil"]), (200, reported)) + def test_an_unregistered_name_is_available_with_its_pricing(self): snrc.eth_call = self._chain(0) status, body = registration("acme.testing") @@ -1001,10 +1088,11 @@ def test_a_status_it_cannot_read_is_an_error_not_a_registration(self): self.assertEqual(body["error"], "unknown") def test_each_answer_carries_exactly_its_own_fields(self): - """The relay decodes by these names; an extra or missing one is a break.""" + """The relay decodes by these names; with the set pinned, a key cannot be + renamed or added without the Haskell side.""" cases = { "registered": (self._chain(self.now + 3600), - {"type", "expires", "graceUntil", "reservedReason_", "nameRecord"}), + {"type", "expires", "graceUntil", "disputeUntil", "reservedReason_", "nameRecord"}), "available": (self._chain(0), {"type", "pricing"}), "reserved": (self._chain(0, reserved=1), {"type", "reservedReason"}), } @@ -1061,6 +1149,16 @@ def test_a_subnode_a_former_holder_owns_is_not_registered(self): _, body = registration("sub.acme.testing") self.assertEqual(body["type"], "available") + def test_a_subname_under_a_2ld_with_zero_expiry_is_not_registered(self): + snrc.eth_call = self._chain(0, owner=self.FORMER_OWNER, holder=snrc.ZERO_ADDR) + _, body = registration("sub.acme.testing") + self.assertEqual(body["type"], "available") + + def test_v1_answers_404_for_a_subname_under_a_2ld_with_zero_expiry(self): + snrc.eth_call = self._chain(0, owner=self.FORMER_OWNER, holder=snrc.ZERO_ADDR) + status, body = snrc.resolve("sub.acme.testing") + self.assertEqual((status, body["error"]), (404, "unregistered")) + def test_v1_does_not_resolve_a_subnode_a_former_holder_owns(self): snrc.eth_call = self._chain(self.now + 3600, owner=self.FORMER_OWNER, holder=self.OWNER) status, body = snrc.resolve("sub.acme.testing") @@ -1354,8 +1452,8 @@ def test_a_fresh_connection_that_fails_is_not_retried(self): self.assertEqual(self.node.requests, 1) def test_a_node_failure_is_not_a_reverted_call(self): - """Callers read RuntimeError as the call reverting and fall back to an - empty value, so a node failure must not look like one.""" + """Callers read RuntimeError as a failed call and CallReverted as a revert, + so a node failure must be neither.""" self.node.status = 502 with self.assertRaises(HTTPError) as cm: snrc.rpc("eth_blockNumber", []) @@ -1417,6 +1515,22 @@ def test_a_registered_name_takes_two_round_trips(self): self.assertEqual(record["simplexChannel"], ["https://a.example/c#1", "https://b.example/c#2"]) self.assertIsNone(record["btc"]) + def test_the_dispute_end_is_read_in_the_round_of_the_expiry(self): + until = self.node.chain.now + 600 + self.node.chain.answers[snrc.dispute_until_call(FakeChain.REGISTRAR, snrc.label_token("acme"))] = "0x" + snrc.encode_uint(until) + _, body = self.assert_same_answer(snrc.registration, "acme.testing", 2) + self.assertEqual(body["registration"]["disputeUntil"], until) + + def test_a_reverted_dispute_end_is_0_in_a_multicall(self): + _, body = self.assert_same_answer(snrc.registration, "acme.testing", 2) + self.assertEqual(body["registration"]["disputeUntil"], 0) + + def test_a_reverted_dispute_end_is_0_in_a_batch(self): + self.node.multicall = False + with self.assertLogs("snrc_resolve", "WARNING"): + _, body = self.assert_same_answer(snrc.registration, "acme.testing", 4) + self.assertEqual(body["registration"]["disputeUntil"], 0) + def test_a_hashed_query_is_named_from_the_same_round_trip(self): hashed = "[" + snrc.keccak(b"acme").hex() + "].testing" status, body = self.assert_same_answer(snrc.registration, hashed, 2) diff --git a/src/Simplex/Messaging/Names/Record.hs b/src/Simplex/Messaging/Names/Record.hs index 42bdc9a99..ca075d0fe 100644 --- a/src/Simplex/Messaging/Names/Record.hs +++ b/src/Simplex/Messaging/Names/Record.hs @@ -87,6 +87,8 @@ data NameRegistration expires :: Maybe SystemSeconds, -- | unix seconds, > expires: until here only the owner may renew graceUntil :: Maybe SystemSeconds, + -- | unix seconds, > lastBlockTs: until here the registration can be ended and cannot be renewed; 0: it cannot be ended; absent: unknown, as from a router or resolver that predates it + disputeUntil :: Maybe SystemSeconds, -- | held back as well, which is why it will not free up at expiry reservedReason_ :: Maybe NameReservedReason, nameRecord :: NameRecord diff --git a/src/Simplex/Messaging/Protocol.hs b/src/Simplex/Messaging/Protocol.hs index 05efa40c5..783cfbef9 100644 --- a/src/Simplex/Messaging/Protocol.hs +++ b/src/Simplex/Messaging/Protocol.hs @@ -2109,7 +2109,7 @@ instance ProtocolEncoding SMPVersion ErrorType BrokerMsg where | otherwise -> fmap (RNAME . oldResponse) . J.eitherDecodeStrict . unTail <$?> _smpP where oldResponse nameRecord = - NameResponse {lastBlockTs = Nothing, registration = NRRegistered {expires = Nothing, graceUntil = Nothing, reservedReason_ = Nothing, nameRecord}} + NameResponse {lastBlockTs = Nothing, registration = NRRegistered {expires = Nothing, graceUntil = Nothing, disputeUntil = Nothing, reservedReason_ = Nothing, nameRecord}} serviceRespP resp | v >= rcvServiceSMPVersion = resp <$> _smpP <*> smpP | otherwise = resp <$> _smpP <*> pure mempty diff --git a/tests/RSLVTests.hs b/tests/RSLVTests.hs index e9b931314..41ae3b19a 100644 --- a/tests/RSLVTests.hs +++ b/tests/RSLVTests.hs @@ -29,7 +29,7 @@ import SMPClient import Simplex.Messaging.Client import qualified Simplex.Messaging.Crypto as C import Simplex.Messaging.Encoding.String (strDecode) -import SMPNamesTests (availableBody, registeredBody, reservedBody, resolved, testNameRecord, testPricing) +import SMPNamesTests (availableBody, disputedAlice, disputedBody, registeredBody, reservedBody, resolved, testNameRecord, testPricing) import Simplex.Messaging.Protocol ( BrokerMsg (..), Cmd (..), @@ -93,8 +93,10 @@ rslvTests = do describe "RSLV forwarded (PFWD)" $ do it "PFWD-wrapped RSLV reaches resolver via proxy (PCEProtocolError (NAME RESOLVER))" testRslvForwarded it "PFWD-wrapped RSLV success returns RNAME (record JSON frames over the proxy)" testRslvForwardedSuccess + it "PFWD-wrapped RNAME includes the dispute end the resolver sent" testRslvForwardedDisputeEnd describe "RSLV success path (RNAME response)" $ do it "returns RNAME with NameRecord" testRslvSuccess + it "RNAME includes the dispute end the resolver sent" testRslvDisputeEnd describe "RSLV availability (RNAME response)" $ do it "unregistered comes back AVAILABLE" testRslvAvailable it "reserved comes back with the reason" testRslvReserved @@ -175,6 +177,13 @@ testRslvForwardedSuccess = Right (Right NameResponse {registration = NRRegistered {nameRecord}}) -> nameRecord `shouldBe` testNameRecord _ -> expectationFailure $ "expected Right (Right NRRegistered), got: " <> show r +testRslvForwardedDisputeEnd :: HasTestEnv => IO () +testRslvForwardedDisputeEnd = + withProxyAndResolver (status200, disputedBody) $ + forwardedResolveAlice >>= \case + Right (Right res) -> res `shouldBe` resolved disputedAlice + r -> expectationFailure $ "expected Right (Right NameResponse), got: " <> show r + testRslvSuccess :: HasTestEnv => IO () testRslvSuccess = withResolverServer (status200, registeredBody testNameRecord) $ @@ -185,6 +194,13 @@ testRslvSuccess = Right (RNAME NameResponse {registration = NRRegistered {nameRecord}}) -> nameRecord `shouldBe` testNameRecord _ -> expectationFailure $ "expected Right (RNAME NRRegistered), got: " <> show resp +testRslvDisputeEnd :: HasTestEnv => IO () +testRslvDisputeEnd = + withResolverServer (status200, disputedBody) $ + testSMPClient @TLS $ \h -> do + (_, _, resp) <- sendRslv h "rs08" (domain "alice.simplex") + resp `shouldBe` Right (RNAME (resolved disputedAlice)) + testRslvAvailable :: HasTestEnv => IO () testRslvAvailable = withResolverServer (status200, availableBody) $ @@ -218,7 +234,7 @@ testRslvOldClientRecord = withResolverServer (status200, registeredBody testNameRecord) $ do pc <- oldClient r <- runExceptT' (directResolveName pc NRMInteractive (domain "alice.simplex")) - r `shouldBe` NameResponse Nothing (NRRegistered Nothing Nothing Nothing testNameRecord) + r `shouldBe` NameResponse Nothing (NRRegistered {expires = Nothing, graceUntil = Nothing, disputeUntil = Nothing, reservedReason_ = Nothing, nameRecord = testNameRecord}) testRslvOldClientNotFound :: HasTestEnv => IO () testRslvOldClientNotFound = diff --git a/tests/SMPNamesTests.hs b/tests/SMPNamesTests.hs index 452c99428..de3c581b7 100644 --- a/tests/SMPNamesTests.hs +++ b/tests/SMPNamesTests.hs @@ -3,7 +3,7 @@ {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} -module SMPNamesTests (smpNamesTests, testNameRecord, testPricing, registeredBody, availableBody, reservedBody, responseBody, resolved) where +module SMPNamesTests (smpNamesTests, testNameRecord, testPricing, registeredBody, disputedBody, disputedAlice, availableBody, reservedBody, responseBody, resolved) where import qualified Data.Aeson as J import qualified Data.ByteString.Char8 as B @@ -29,7 +29,7 @@ import Simplex.Messaging.Server.Names ) import Simplex.Messaging.Server.Names.HttpResolver (ResolverError (..)) import Simplex.Messaging.SimplexName (SimplexDomain (..), SimplexTLD (..), labelHash) -import Simplex.Messaging.SystemTime (RoundedSystemTime (..)) +import Simplex.Messaging.SystemTime (RoundedSystemTime (..), SystemSeconds) import Simplex.Messaging.Transport (nameAvailSMPVersion, serverInfoSMPVersion) import Test.Hspec @@ -53,8 +53,17 @@ testNameRecord = -- | What the resolver serves on /v2/resolve. Spelled out rather than encoded -- from the Haskell value: the literal JSON is the contract with the resolver. registeredBody :: NameRecord -> LB.ByteString -registeredBody nameRec = - responseBody $ "{\"type\":\"registered\",\"expires\":1813853483,\"graceUntil\":1821629483,\"reservedReason_\":null,\"nameRecord\":" <> J.encode nameRec <> "}" +registeredBody = registeredBodyWith "\"reservedReason_\":null," + +registeredBodyWith :: LB.ByteString -> NameRecord -> LB.ByteString +registeredBodyWith fields nameRec = + responseBody $ "{\"type\":\"registered\",\"expires\":1813853483,\"graceUntil\":1821629483," <> fields <> "\"nameRecord\":" <> J.encode nameRec <> "}" + +finalBody :: LB.ByteString +finalBody = registeredBodyWith "\"disputeUntil\":0,\"reservedReason_\":null," testNameRecord + +disputedBody :: LB.ByteString +disputedBody = registeredBodyWith "\"disputeUntil\":1813100000,\"reservedReason_\":null," testNameRecord availableBody :: LB.ByteString availableBody = responseBody "{\"type\":\"available\",\"pricing\":{\"registrationPrices\":{\"3\":12793,\"4\":3198},\"basePrice\":100,\"minLabelLength\":3}}" @@ -74,8 +83,17 @@ resolved registration = NameResponse {lastBlockTs = Just (RoundedSystemTime 1813 -- | What `registeredBody testNameRecord` resolves to. registeredAlice :: NameRegistration -registeredAlice = - NRRegistered {expires = Just (RoundedSystemTime 1813853483), graceUntil = Just (RoundedSystemTime 1821629483), reservedReason_ = Nothing, nameRecord = testNameRecord} +registeredAlice = aliceWith Nothing Nothing + +aliceWith :: Maybe SystemSeconds -> Maybe NameReservedReason -> NameRegistration +aliceWith dispute reason = + NRRegistered {expires = Just (RoundedSystemTime 1813853483), graceUntil = Just (RoundedSystemTime 1821629483), disputeUntil = dispute, reservedReason_ = reason, nameRecord = testNameRecord} + +finalAlice :: NameRegistration +finalAlice = aliceWith (Just (RoundedSystemTime 0)) Nothing + +disputedAlice :: NameRegistration +disputedAlice = aliceWith (Just (RoundedSystemTime 1813100000)) Nothing smpNamesTests :: Spec smpNamesTests = do @@ -160,8 +178,14 @@ availabilitySpec = do it "a registered name answers with its record and dates" $ answers (registeredBody testNameRecord) (resolved registeredAlice) it "a registered name can be held back too" $ - answers heldBackBody . resolved $ - NRRegistered {expires = Just (RoundedSystemTime 1813853483), graceUntil = Just (RoundedSystemTime 1821629483), reservedReason_ = Just NRRInternal, nameRecord = testNameRecord} + answers heldBackBody . resolved $ aliceWith Nothing (Just NRRInternal) + it "a registration in its dispute period is answered with its end" $ + answers disputedBody (resolved disputedAlice) + it "a registration that cannot be ended is answered with a dispute end of 0" $ + answers finalBody (resolved finalAlice) + it "an unknown dispute end is answered as unknown, and left out of RNAME" $ do + answers (registeredBodyWith "\"disputeUntil\":null,\"reservedReason_\":null," testNameRecord) (resolved registeredAlice) + LB.toStrict (J.encode (resolved registeredAlice)) `shouldNotSatisfy` B.isInfixOf "disputeUntil" it "an unregistered name answers with the price" $ answers availableBody (resolved NRAvailable {pricing = testPricing, nameTerms = Nothing}) it "reserved carries the reason and no price" $ @@ -174,7 +198,9 @@ availabilitySpec = do mapM_ (\a -> J.eitherDecodeStrict (LB.toStrict (J.encode a)) `shouldBe` Right a) [ registeredAlice, - NRRegistered {expires = Nothing, graceUntil = Nothing, reservedReason_ = Just NRRInternal, nameRecord = testNameRecord}, + finalAlice, + disputedAlice, + NRRegistered {expires = Nothing, graceUntil = Nothing, disputeUntil = Nothing, reservedReason_ = Just NRRInternal, nameRecord = testNameRecord}, NRAvailable {pricing = testPricing, nameTerms = Nothing}, NRReserved NRRInternal, NRReserved NRRTrademark, @@ -186,8 +212,7 @@ availabilitySpec = do J.encode (NRRUnknown "seasonal") `shouldBe` "\"seasonal\"" J.encode NRRTrademark `shouldBe` "\"trademark\"" where - heldBackBody = - responseBody $ "{\"type\":\"registered\",\"expires\":1813853483,\"graceUntil\":1821629483,\"reservedReason_\":\"internal\",\"nameRecord\":" <> J.encode testNameRecord <> "}" + heldBackBody = registeredBodyWith "\"reservedReason_\":\"internal\"," testNameRecord answers body a = withResolverServer (resolveResp status200 body) $ \port _ -> do env <- newNamesEnv (testNamesConfig port)