Files
simplex-chat/tests/Bots/StoreService/NamesCommunityTests.hs
ad75fe706f store: sell and register SimpleX names (#7979)
* core: add prepaid name codes and length bounds

* store: run the names migration after badges

* store: issue and revoke prepaid name codes

* store: document issuing prepaid name codes

* store: move the ABI helpers to Names.Abi

* store: read the [names] and [chain] settings

* store: add the names chain client and reads

* store: refuse group name codes while names are off

* store: search names and preview links

* store: serve each site on its own port

* scripts: deploy the badges and names sites

* store: document search and the two sites

* store: add the drop_taken_codes migration

* store: read the names codes_only setting

* store: add the names store and order signatures

* store: take name orders by card, crypto or code

* store: document name orders and codes-only

* store: add the names transaction sender

* store: commit and register queued orders

* store: reveal and retry an owner's order

* store: document the gas key

* store: add the name balance migrations

* store: read crypto units, rates and confirmations

* store: keep a taken order's money as a balance

* store: spend a balance on another name

* store: record refunds with //refund

* store: document balances and refunds

* store: add the agreed terms migration

* store: read the terms and community names

* store: answer community and terms in search

* store: sign and store the agreed terms

* store: document the terms and community names

* store: add the invoiced units migration

* store: read the crypto an invoice asks

* store: credit late and overpaid crypto by share

* store: document crediting late crypto by share

* store: add the record changes migration

* store: find an owner's orders and move one

* store: relay owners' link edits on chain

* store: document link edits

* store: move isLoopbackHost to Config

* store: trust dev issuer keys on the local chain

* scripts: build the names site from a submodule

* scripts: add the dev setup and contract run

* store: document the dev setup and names image

* store: send a Stripe idempotency key for names

* tests: wait until a relay lets go of its edit

* store: refuse a link edit deadline under 10 min

* store: count reverted link edits in the year limit

* store: require https for a remote chain node

* store: refuse zero chain confirmations

* store: set up the dev stack from the names branch

* store: rerun a failed unpaid cleanup next pass

* store: never replace a succeeded Stripe intent

* store: refuse an ini setting written as key: value

* store: note the webapp submodule's pinned branch

* store: document confirmLanded judging by ownerOf

* store: update the names webapp submodule

* store-service: register names under the name policy, every name accepting its terms on chain (#7889)

* store: accept each name's terms on chain under the name policy

* ci: run the reduced build on sh/names-deploy

* store: address review: policy re-read, terms reads and startup log

* store: never credit an unconfirmed extra

* store: alert money sent to a paid name invoice

* store: refuse to start on another chain's node

* store: keep orders while the allowance is used up

* store: replace a stalled transaction after 3 blocks

* store: judge a name taken at confirmation depth

* store: bind the template's listener to loopback

* store: scan only the ids of active name orders

* store: refuse unknown [names] and [chain] settings

* store: fetch the webapp submodule in upgrade steps

* store: delete definitions only tests use

* store: lock only name invoices at settlement

* store: retry an unexpired commitment as usual

* store: share the helpers defined twice

* store: test route limits on the running service

* store: fix tests that could not fail

* ci: test the store service on Postgres

* store: count IPv6 clients by their /64

* store: sweep invoices read alone past a list cap

* store: cap checkouts of all clients together

* store: cap the long polls held at once

* store: stop the old badge project at upgrade

* store: keep search lookups free of previews

* store: read the ini as UTF-8 in any locale

* ci: run Postgres store tests in a UTF-8 locale

* store: cap the transactions one order sends

* store: cancel a card intent after three declines

* store: refuse a name price under a cent

* store: send each transaction with gas headroom

* store: cap searches and read terms once per block

* store: never log the group join link

* store: mask the database password at startup

* store: run one instance per database

* store: limit name codes to admins, 100 a day

* store: refuse HighSpeed settlement with names

* store: no unverified receipts with a trusted key

* store: cap the log lines of refused webhooks

* store: check Apple certificates at the signed date

* store: refuse a malformed Stripe publishable key

* store: check the owner before a refund

* store: fold the names migrations into one

* store: read onion name links through the proxy

* store: refund money after paid once confirmed

* store: limit the allowance wait to a dry run

* store: bind loopback when upgrading

* ci: cache and widen the store Postgres job

* store: fix stale and duplicate names tests

* store: fix the submodule path in the upgrade

* store: refuse unpaid name codes on the CLI

* store: apply the review's names test list

* store: finish the review's names test list

* store: restore the base registration tests

* store: pass link hosts that do not resolve here

* store: refuse a move once its sends are used up

* store: take the shared checkout at the provider

* store: hold a search slot for chain reads only

* store: state which refunds are safe on a reference

* store: check a failed order's name before refusing its move (#8060)

* store: test and document the shared checkout cap for name orders

* store: check a failed order's name on chain before refusing its move

* store: test name links whose host lookup fails

* store: test that a search holds its slot through the chain reads only

* store: restore the signed transaction check in the chain tests

* store: remove the chain tests' copy of the signed transaction check

* store: correct the search slot texts and the README's balance endpoints

* docs: system and sequence diagrams of the names service (#8068)

---------

Co-authored-by: sh-agents <350651734+sh-agents@users.noreply.github.com>
Co-authored-by: Evgeny Poberezkin <evgeny@poberezkin.com>
Co-authored-by: brenzi-agent <brenzi-agent@brenzi.ch>
Co-authored-by: Evgeny @ SimpleX Chat <259188159+evgeny-simplex@users.noreply.github.com>
2026-11-07 10:45:19 +00:00

176 lines
10 KiB
Haskell

{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
module Bots.StoreService.NamesCommunityTests (namesCommunityTests) where
import Bots.StoreService.ConfigTests (chainSection, namesIni, namesRefusal, namesSection, parseIni, parsedNames, withIni)
import Bots.StoreService.FakeEthNode (CallAnswer (..), answerCall, answerListing, fakeCommunityTerms, fakeCommunityTermsText, fakeController, fakeGeneralTerms, fakeGeneralTermsText, fakeNamePolicy, fakeTermsLink, fetchedTexts, setCommunityTerms, setGeneralTerms, nextBlock)
import Bots.StoreService.NamesContractsTests (withContracts)
import Bots.StoreService.NamesSearchTests (aliceHex)
import Bots.StoreService.WebTests (capturingStderr)
import Control.Concurrent.STM (TVar)
import Control.Monad (forM_, void)
import Crypto.Random (ChaChaDRG)
import Data.Ini (readIniFile)
import qualified Data.Map.Strict as M
import Data.Maybe (fromJust)
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Encoding (encodeUtf8)
import qualified Simplex.Messaging.Crypto as C
import Simplex.Messaging.SimplexName (LabelHash (..), labelHash)
import StoreService.Config (NamesConfig (..), unknownKeys)
import StoreService.Names.Abi (AbiValue (..), abiBytes, abiTuple, bytes32FromHex, hex, selector)
import StoreService.Names.Community (agreedTermsHash, communityFor, termsFor)
import StoreService.Names.Contracts (Terms (..))
import StoreService.Names.View (addressText)
import StoreService.Service (logNamePolicy)
import Test.Hspec
namesCommunityTests :: Spec
namesCommunityTests = describe "StoreService names: community" $ do
g <- runIO C.newRandom
it "reads the list keyed by the label's keccak256, empty without [community]" testCommunityParsed
it "refuses [community] without [names]" testCommunityWithoutNames
it "refuses a section header written twice, naming it" testRepeatedHeader
it "refuses a key written twice in any section, naming it" testRepeatedKey
it "refuses a label that is not a valid name, upper case included, naming it" testBadLabel
it "refuses an empty or over-long text, or one with a control, format or line separator character" testBadText
it "names no community label as a setting nothing reads" testNoUnknownKeys
it "logs how many community names it loaded" testLoadedCount
it "gives the terms' hash for an unlisted name and community/ with it for a listed one, and reads a community hash back" testTermsFor
it "logs the name policy and both terms links with their hashes at startup, fetching no text, and checks the [community] lines" $ testStartupCheck g
it "checks no [community] line when the policy cannot be read at startup" $ testStartupUnread g
it "warns at startup on terms not set, unread, or of a link the service does not take, fetching no text" $ testStartupWarnings g
bakersText :: Text
bakersText = "bakers and bakeries in Portugal"
communityLines :: [Text] -> [Text]
communityLines entries = "[community]" : entries
withCommunity :: [Text] -> IO NamesConfig
withCommunity entries = parsedNames namesSection (chainSection <> communityLines entries)
refusedCommunity :: [Text] -> IO String
refusedCommunity entries = namesRefusal namesSection (chainSection <> communityLines entries)
-- viem: keccak256 of "alicebakery", as the page sends it
aliceHash :: LabelHash
aliceHash = LabelHash $ fromJust $ bytes32FromHex aliceHex
testCommunityParsed :: IO ()
testCommunityParsed = do
NamesConfig {nCommunity} <- parsedNames namesSection chainSection
nCommunity `shouldBe` M.empty
cfg@NamesConfig {nCommunity = listed} <- withCommunity ["bakers = " <> bakersText, "alicebakery = Alice's bakery, Lisbon; open daily"]
M.size listed `shouldBe` 2
communityFor cfg aliceHash `shouldBe` Just "Alice's bakery, Lisbon; open daily"
communityFor cfg (labelHash "bakers") `shouldBe` Just bakersText
communityFor cfg (labelHash "bobsbakery") `shouldBe` Nothing
testCommunityWithoutNames :: IO ()
testCommunityWithoutNames =
namesRefusal [] (communityLines ["bakers = " <> bakersText]) `shouldReturn` "[community] is set but [names] is absent, so nothing would use it"
testRepeatedHeader :: IO ()
testRepeatedHeader = do
refusedCommunity ["bakers = " <> bakersText, "[community]", "florists = florists in Lisbon"]
`shouldReturn` "[community] is written twice, and only the last of them would be read"
namesRefusal (namesSection <> chainSection <> namesSection) [] `shouldReturn` "[names] is written twice, and only the last of them would be read"
namesRefusal namesSection (chainSection <> ["[legacy]", "a = 1", " [ legacy ] "]) `shouldReturn` "[legacy] is written twice, and only the last of them would be read"
testRepeatedKey :: IO ()
testRepeatedKey = do
refusedCommunity ["bakers = " <> bakersText, "florists = florists in Lisbon", "bakers = bakers of Porto"]
`shouldReturn` "community.bakers is written twice, and only the first of them would be read"
namesRefusal (namesSection <> ["tld = simplex"]) chainSection
`shouldReturn` "names.tld is written twice, and only the first of them would be read"
testBadLabel :: IO ()
testBadLabel = do
forM_ ["Bakers", "bak--ers", "bakers-", "bak_ers", "bäkers"] $ \l ->
refusedCommunity [l <> " = " <> bakersText] `shouldReturn` ("community." <> T.unpack l <> " must be lower-case letters and digits, with single hyphens between them")
forM_ ["baker", T.replicate 64 "a"] $ \l ->
refusedCommunity [l <> " = " <> bakersText] `shouldReturn` ("community." <> T.unpack l <> " must be 6 to 63 characters")
testBadText :: IO ()
testBadText = do
let badLength = "community.bakers must be 1 to 200 characters"
invisible = "community.bakers has a control, format or line separator character"
refusedCommunity ["bakers ="] `shouldReturn` badLength
refusedCommunity ["bakers = " <> T.replicate 201 "a"] `shouldReturn` badLength
forM_ ["bakers\tand bakeries", "bakers \ESC[31m", "bakers\DEL"] $ \t ->
refusedCommunity ["bakers = " <> t] `shouldReturn` invisible
-- right-to-left override and zero-width space (format), line and paragraph separators
forM_ ["bakers \x202E and bakeries", "bakers\x200B and bakeries", "bakers\x2028 and bakeries", "bakers\x2029 and bakeries"] $ \t ->
refusedCommunity ["bakers = " <> t] `shouldReturn` invisible
NamesConfig {nCommunity} <- withCommunity ["bakers = " <> T.replicate 200 "é"]
M.elems nCommunity `shouldBe` [T.replicate 200 "é"]
testNoUnknownKeys :: IO ()
testNoUnknownKeys =
withIni (namesIni namesSection (chainSection <> communityLines ["bakers = " <> bakersText, "florists = florists in Lisbon"])) $ \p -> do
Right ini <- readIniFile p
unknownKeys ini `shouldBe` []
testLoadedCount :: IO ()
testLoadedCount = do
listed <- capturingStderr $ void $ parseIni (namesIni namesSection (chainSection <> communityLines ["bakers = " <> bakersText, "florists = florists in Lisbon"]))
listed `shouldSatisfy` T.isInfixOf "names: 2 community names loaded"
none <- capturingStderr $ void $ parseIni (namesIni namesSection chainSection)
none `shouldSatisfy` T.isInfixOf "names: 0 community names loaded"
testTermsFor :: IO ()
testTermsFor = do
let hexDigits = "e2937ea655d8e743e2a8cecbab83acdf055846c80e13001ec1f8dc404e4ef2d9"
h = fromJust $ bytes32FromHex $ "0x" <> hexDigits
terms = Terms {tmLink = "https://git.simplex.chat/simplex-chat/simplex-chat/raw/commit/4cb24444a1f2e3d4c5b6a7980716253443526170/docs/terms.md#sha256=" <> hexDigits, tmHash = h}
listed = "community/" <> hexDigits
termsFor False terms `shouldBe` hexDigits
termsFor True terms `shouldBe` listed
agreedTermsHash listed `shouldBe` Just h
agreedTermsHash hexDigits `shouldBe` Nothing
agreedTermsHash "community" `shouldBe` Nothing
agreedTermsHash "2026-10-23" `shouldBe` Nothing
agreedTermsHash ("community/" <> T.toUpper hexDigits) `shouldBe` Nothing
testStartupCheck :: TVar ChaChaDRG -> IO ()
testStartupCheck g = withContracts g $ \node ct -> do
cfg <- withCommunity ["alicebakery = Alice's bakery"]
logged <- capturingStderr $ logNamePolicy cfg ct
logged `shouldSatisfy` T.isInfixOf ("names: name policy " <> addressText fakeNamePolicy)
logged `shouldSatisfy` T.isInfixOf ("names: general terms " <> fakeTermsLink fakeGeneralTermsText <> ", hash " <> hex fakeGeneralTerms)
logged `shouldSatisfy` T.isInfixOf ("names: community terms " <> fakeTermsLink fakeCommunityTermsText <> ", hash " <> hex fakeCommunityTerms)
logged `shouldSatisfy` T.isInfixOf "names: [community] lists a name the name policy does not list, so it is sold as a plain name: Alice's bakery"
fetchedTexts node `shouldReturn` []
answerListing node aliceHash $ Reverts ""
unread <- capturingStderr $ logNamePolicy cfg ct
unread `shouldSatisfy` T.isInfixOf "names: a [community] name's listing could not be read: Alice's bakery"
testStartupUnread :: TVar ChaChaDRG -> IO ()
testStartupUnread g = withContracts g $ \node ct -> do
cfg <- withCommunity ["alicebakery = a bakery the policy is not read for"]
answerCall node fakeController (selector "namePolicy()") $ Reverts ""
warned <- capturingStderr $ logNamePolicy cfg ct
warned `shouldSatisfy` T.isInfixOf "names: the controller's name policy could not be read, it is read on first use"
-- a text no other case logs, so a line another case logs late cannot match it
warned `shouldNotSatisfy` T.isInfixOf "a bakery the policy is not read for"
testStartupWarnings :: TVar ChaChaDRG -> IO ()
testStartupWarnings g = withContracts g $ \node ct -> do
cfg <- parsedNames namesSection chainSection
let warns text = capturingStderr (logNamePolicy cfg ct) >>= (`shouldSatisfy` T.isInfixOf text)
otherLink = "https://example.org/simplex-chat/terms.md"
setGeneralTerms node ""
warns "names: the name policy has no general terms yet, so plain names cannot be ordered until the owner sets them"
setCommunityTerms node ""
warns "names: the name policy has no community terms yet, so community names cannot be ordered until the owner sets them"
answerCall node fakeNamePolicy (selector "generalTermsLink()") $ Returns $ abiTuple [Dynamic $ abiBytes $ encodeUtf8 otherLink]
nextBlock node
warns $ "names: the name policy's general terms are not a link the service takes, so plain names cannot be ordered: " <> otherLink
answerCall node fakeNamePolicy (selector "generalTermsLink()") $ Reverts ""
nextBlock node
warns "names: the name policy's terms could not be read: "
fetchedTexts node `shouldReturn` []