mirror of
https://github.com/simplex-chat/simplexmq.git
synced 2026-10-06 16:27:21 +00:00
* implement resolving 2LD names by labelhash * tiny test addition * simplify language * report expiry and availability correctly * compare block instead of wall clock * simplify language * simplify language * map resolver 410 to NAME NOT_FOUND (a lapsed name is an answer, not a failure) * split error into a machine-readable code and a human message * resolver: reduce comments * resolver: reduce comments, remove REVIEW.html * extend SMP protocol to support name availability queries with accurate and meaningful replies * review fixes * more review fixes * docs shortening and other review fixes * add catch all for furture variants * adversarial review (against simplex-chat) fix * next iteration fixes * adapt house style * eth_call guard and cache constants * revert NAVL command and wrap it all into RSLV * doc fixes * Update src/Simplex/Messaging/Server/Names.hs Co-authored-by: Evgeny <evgeny@poberezkin.com> * Update src/Simplex/Messaging/Protocol.hs Co-authored-by: Evgeny <evgeny@poberezkin.com> * Update src/Simplex/Messaging/Protocol.hs Co-authored-by: Evgeny <evgeny@poberezkin.com> * Update src/Simplex/Messaging/Protocol.hs Co-authored-by: Evgeny <evgeny@poberezkin.com> * Update src/Simplex/Messaging/Protocol.hs Co-authored-by: Evgeny <evgeny@poberezkin.com> * protocol types refactoring * next iteration on types only * rentPrices map * claude answering ep review. to be continued... * separate labelhash and plaintext names cleanly * align implementation with latest type changes to test against client * fix adversarial review findings * trim diff * align resolver with contract changes for names v2 * fix reverse compatibility with .testing mainnet * fix more robustly * NameQuery simplification * revert drive-by refactoring * implement full type change and introduce resolver endpoint versioning * fix stale docs * derive NameRegistration JSON the same way on every build sumTypeJSON switches to the _owsf form on swift builds, but this JSON is the RNAME payload and the resolver's HTTP contract, so a swift client and a Linux relay would disagree on every field. taggedObjectJSON is what it already resolves to everywhere else. The label modifier keeps the reservedReason_ collision escape out of the API, as AgentWorkersDetails does: both arms now say reservedReason. * fix resolver boundary: status before body, cover /v2, drop dead field httpGet read the response body before checking the status, so an oversized error page surfaced as a transient "response too large" instead of the authoritative status. Reverting it to its previous shape restores that and removes the status test both callers had been re-deriving. registration() had no tests at all, though it is the endpoint SMP v22 consumes. RegistrationV2Tests covers the three answer shapes, the error paths and the exact key set of each, which is the wire contract. auctionUntil was always None with no consumer. The spec claimed a reason word travels unchanged; a resolver can only send a word it has, and SNRC's registry records a number. * fix review findings * resolver errors say what went wrong, not "no such name" /v2/resolve answers 200, 400 or 502, and an unregistered name is NRAvailable, so no status means "not registered". Mapping 400/404/410 to NOT_FOUND made a misconfigured relay deny every name, and hid a relay upgraded ahead of its resolver. All three now surface as RESOLVER. rslvNotFound would have gone dead, so it counts what its name says: an availability answer the encoder downgrades for a session below v22. The wire is unchanged. A hashed query the registrar cannot name is refused with 502 rather than answered with a record named "unknown", which the client rejects anyway. NRRUnknown is capped to 32 printable characters again, as the spec says. A registered name that is also reserved no longer offers a date it will never free up on. rentPrices is registrationPrices throughout, and yearPriceUSD is USDCents rather than a bare Int64. * fix regressions found reviewing the last two commits resolveNameMsg read the version off thParams', which on the PFWD path is the proxy's session, not the client's. It takes the version as an argument now, so each call site passes its own — the forwarded one uses fwdVersion. reservedReasonOf matched the reason words before capping, so "internal review" became NRRUnknown "internal", which encodes back as NRRInternal. Capping precedes the match, so what is kept encodes to what it decoded. Four agent tests still pinned NAME NOT_FOUND from a 404 stub, and two spec statements still described the old mapping. A registrar that does not record labels cannot answer a hashed query, which the resolver README now says. * docs sweep * simplify encoding * drop resolver caching (#1866) * rename * remove trailing_ filter * fix resolver v2 for subnames (#1867) * fix resolver v2 for subnames * simplify doc * resolver should report response truth freshness (#1868) * first shot at reporting freshness * fix review findings * renaming --------- Co-authored-by: sh <github.shum@liber.li> Co-authored-by: Evgeny <evgeny@poberezkin.com>
162 lines
6.1 KiB
Haskell
162 lines
6.1 KiB
Haskell
{-# LANGUAGE LambdaCase #-}
|
||
{-# LANGUAGE NamedFieldPuns #-}
|
||
{-# LANGUAGE OverloadedStrings #-}
|
||
{-# LANGUAGE StrictData #-}
|
||
{-# LANGUAGE TemplateHaskell #-}
|
||
|
||
module Simplex.Messaging.SimplexName
|
||
( SimplexNameInfo (..),
|
||
SimplexDomain (..),
|
||
SimplexTLD (..),
|
||
SimplexNameType (..),
|
||
fullDomainName,
|
||
LabelHash (..),
|
||
labelHash,
|
||
boundedNonSpace,
|
||
shortNameInfoStr,
|
||
)
|
||
where
|
||
|
||
import Control.Applicative (optional, (<|>))
|
||
import Crypto.Hash (Digest, hash)
|
||
import Crypto.Hash.Algorithms (Keccak_256)
|
||
import qualified Data.Aeson.TH as J
|
||
import qualified Data.Attoparsec.ByteString.Char8 as A
|
||
import qualified Data.Attoparsec.Text as AT
|
||
import qualified Data.ByteArray as BA
|
||
import qualified Data.ByteArray.Encoding as BAE
|
||
import Data.ByteString.Char8 (ByteString)
|
||
import qualified Data.ByteString.Char8 as B
|
||
import Data.Char (isDigit)
|
||
import Data.Functor (($>))
|
||
import Data.Text (Text)
|
||
import qualified Data.Text as T
|
||
import Data.Text.Encoding (decodeLatin1, encodeUtf8)
|
||
import Simplex.Messaging.Agent.Store.DB (FromField (..), ToField (..), fromTextField_)
|
||
import Simplex.Messaging.Encoding (Encoding (..))
|
||
import Simplex.Messaging.Encoding.String
|
||
import Simplex.Messaging.Parsers (defaultJSON, dropPrefix, enumJSON)
|
||
import Simplex.Messaging.Util (eitherToMaybe, safeDecodeUtf8, (<$?>))
|
||
|
||
data SimplexNameInfo = SimplexNameInfo
|
||
{ nameType :: SimplexNameType,
|
||
nameDomain :: SimplexDomain
|
||
}
|
||
deriving (Eq, Show)
|
||
|
||
data SimplexDomain = SimplexDomain
|
||
{ nameTLD :: SimplexTLD,
|
||
domain :: Text,
|
||
subDomain :: [Text] -- parent to child: ["b", "a"] for a.b.domain.simplex
|
||
}
|
||
deriving (Eq, Show)
|
||
|
||
data SimplexTLD = TLDSimplex | TLDTesting | TLDWeb
|
||
deriving (Eq, Show)
|
||
|
||
data SimplexNameType = NTPublicGroup | NTContact
|
||
deriving (Eq, Show)
|
||
|
||
instance StrEncoding SimplexNameType where
|
||
strEncode = \case
|
||
NTPublicGroup -> "#"
|
||
NTContact -> "@"
|
||
strP = A.char '#' $> NTPublicGroup <|> A.char '@' $> NTContact
|
||
|
||
nameLabelP :: AT.Parser Text
|
||
nameLabelP = do
|
||
label <- T.intercalate "-" <$> AT.takeWhile1 (\c -> isNameLetter c || isDigit c) `AT.sepBy1` AT.char '-'
|
||
-- DNS label limit: each dot-separated component is at most 63 bytes (labels
|
||
-- are ASCII, so character count == byte count)
|
||
if T.length label > 63 then fail "name label exceeds 63 bytes" else pure label
|
||
where
|
||
-- ASCII letters only. SNRC contracts hash byte sequences via keccak; ENS
|
||
-- uses UTS-46 + Punycode for IDN, which we do not implement. Admitting
|
||
-- Cyrillic / Greek / etc. via Data.Char.isAlpha would (a) make namehash
|
||
-- diverge from any IDN-aware registrar and (b) allow homograph spoofing
|
||
-- (Cyrillic а vs ASCII a hash to different on-chain records).
|
||
isNameLetter c = c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z'
|
||
|
||
-- | The registry's key for a label: 32 bytes, as labelOf takes it.
|
||
newtype LabelHash = LabelHash ByteString
|
||
deriving (Eq, Show)
|
||
|
||
-- | keccak-256 of the lowercased label, as the registry keys it.
|
||
labelHash :: Text -> LabelHash
|
||
labelHash label = LabelHash $ BA.convert (hash (encodeUtf8 (T.toLower label)) :: Digest Keccak_256)
|
||
|
||
instance StrEncoding LabelHash where
|
||
strEncode (LabelHash h) = '[' `B.cons` (BAE.convertToBase BAE.Base16 h `B.snoc` ']')
|
||
strP = do
|
||
h <- BAE.convertFromBase BAE.Base16 <$?> (A.char '[' *> A.takeWhile (/= ']') <* A.char ']')
|
||
if B.length h == 32 then pure $ LabelHash h else fail "bad LabelHash"
|
||
|
||
-- | Cap the name at 253 bytes (DNS full-domain limit)
|
||
boundedNonSpace :: A.Parser ByteString
|
||
boundedNonSpace = do
|
||
bs <- A.scan (0 :: Int) $ \i c ->
|
||
if i <= 253 && not (A.isSpace c) then Just (i + 1) else Nothing
|
||
if B.null bs
|
||
then fail "expected non-empty name token"
|
||
else if B.length bs > 253 then fail "name exceeds 253 bytes" else pure bs
|
||
|
||
instance StrEncoding SimplexNameInfo where
|
||
strEncode SimplexNameInfo {nameType, nameDomain} =
|
||
strEncode nameType <> strEncode nameDomain
|
||
strP = optional "simplex:/name" *> ((strP >>= infoP) <|> infoP NTPublicGroup)
|
||
where
|
||
infoP NTPublicGroup = SimplexNameInfo NTPublicGroup <$> (strP <|> bareName)
|
||
infoP NTContact = SimplexNameInfo NTContact <$> strP
|
||
bareName = parseBare . safeDecodeUtf8 <$?> boundedNonSpace
|
||
parseBare s = (\name -> SimplexDomain TLDSimplex (T.toLower name) []) <$> AT.parseOnly (nameLabelP <* AT.endOfInput) s
|
||
|
||
instance StrEncoding SimplexDomain where
|
||
strEncode = encodeUtf8 . fullDomainName
|
||
strP = parseDomain . safeDecodeUtf8 <$?> boundedNonSpace
|
||
where
|
||
parseDomain s = AT.parseOnly (nameLabelP `AT.sepBy1` AT.char '.' <* AT.endOfInput) s >>= mkDomain
|
||
mkDomain labels = case reverse lowered of
|
||
[] -> Left "empty name"
|
||
[_] -> Left "domain requires TLD"
|
||
"simplex" : name : sub -> Right (SimplexDomain TLDSimplex name sub)
|
||
"testing" : name : sub -> Right (SimplexDomain TLDTesting name sub)
|
||
_ -> Right (SimplexDomain TLDWeb (T.intercalate "." lowered) [])
|
||
where
|
||
lowered = map T.toLower labels
|
||
|
||
instance Encoding SimplexDomain where
|
||
smpEncode = strEncode
|
||
smpP = strP
|
||
|
||
fullDomainName :: SimplexDomain -> Text
|
||
fullDomainName SimplexDomain {nameTLD, domain, subDomain} = T.intercalate "." (reverse subDomain ++ [domain]) <> decodeLatin1 (strEncode nameTLD)
|
||
|
||
instance StrEncoding SimplexTLD where
|
||
strEncode = \case
|
||
TLDSimplex -> ".simplex"
|
||
TLDTesting -> ".testing"
|
||
TLDWeb -> ""
|
||
strP =
|
||
".simplex" $> TLDSimplex <|> ".testing" $> TLDTesting <|> pure TLDWeb
|
||
|
||
shortNameInfoStr :: SimplexNameInfo -> Text
|
||
shortNameInfoStr = \case
|
||
SimplexNameInfo {nameType = NTPublicGroup, nameDomain = SimplexDomain {nameTLD = TLDSimplex, domain, subDomain = []}} -> "#" <> domain
|
||
info -> pfx <> fullDomainName (nameDomain info)
|
||
where
|
||
pfx = case nameType info of
|
||
NTPublicGroup -> "#"
|
||
NTContact -> "@"
|
||
|
||
instance ToField SimplexDomain where toField = toField . decodeLatin1 . strEncode
|
||
|
||
instance FromField SimplexDomain where fromField = fromTextField_ (eitherToMaybe . strDecode . encodeUtf8)
|
||
|
||
$(J.deriveJSON (enumJSON $ dropPrefix "TLD") ''SimplexTLD)
|
||
|
||
$(J.deriveJSON (enumJSON $ dropPrefix "NT") ''SimplexNameType)
|
||
|
||
$(J.deriveJSON defaultJSON ''SimplexDomain)
|
||
|
||
$(J.deriveJSON defaultJSON ''SimplexNameInfo)
|