Files
simplex-chat/tests/Bots/StoreService/NameRegistrationTests.hs
T
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

218 lines
14 KiB
Haskell

{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
module Bots.StoreService.NameRegistrationTests (badgeNameRegistrationTests) where
import StoreService.Names.Chain
import StoreService.Names.Registration
import StoreService.Names.Revert (RevertName (..))
import Bots.StoreService.FakeEthNode hiding (address)
import Bots.StoreService.WebUIMock
import Control.Concurrent.STM (TVar)
import Crypto.Random (ChaChaDRG)
import Data.ByteArray.Encoding (Base (Base16), convertFromBase, convertToBase)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.Text (Text)
import qualified Data.Text as T
import Data.Word (Word64)
import qualified Simplex.Messaging.Crypto as C
import Simplex.Messaging.Crypto.Secp256k1 (signRecoverable)
import Simplex.Messaging.Encoding.String (strDecode)
import Simplex.Messaging.Eth.Address (Address)
import Simplex.Messaging.Eth.EIP712 (Eip712Domain)
import Simplex.Messaging.Eth.Transaction (Eip1559Tx (..), signEip1559Tx)
import Simplex.Messaging.SimplexName (SimplexTLD (..))
import StoreService.Names.Signatures (parseSignature)
import Test.Hspec
badgeNameRegistrationTests :: Spec
badgeNameRegistrationTests = describe "StoreService names: registration" $ do
g <- runIO C.newRandom
-- expected encodings and signatures are viem's, against the SimplexController, SimplexSponsor and SimplexResolver ABIs
describe "encoding" $ do
it "encodes registerWithCredit with records" $ testRegisterCalldataWithRecords g
it "encodes registerWithCredit without records" $ testRegisterCalldataWithoutRecords g
it "encodes commit with the commitment of a registration" testCommitCalldata
describe "verifying the register intent" $ do
it "rejects an intent signed by another wallet" $ testVerifyOtherSigner g
it "rejects an intent past its deadline" $ testVerifyExpired g
it "rejects a secret that is not 32 bytes" $ testVerifyShortSecret g
-- viem's hashTypedData and encodeFunctionData against the SimplexNamePolicy ABI of ens-contracts 6ccb5c5
describe "terms acceptance" $ do
it "hashes AcceptGeneralTerms and AcceptCommunityTerms as the policy does" testAcceptanceDigest
it "encodes commitUnderGeneralTermsWithSig and commitUnderCommunityTermsWithSig" testAcceptCalldata
it "verifies the owner's acceptance, and rejects another signer, another deadline and the other kind of terms" $ testVerifyAcceptance g
it "reads the register's dry run reverting as the sponsor's error" $ testRevertedDryRun g
it "registers a name the client committed to without revealing it" $ testCommitThenRegister g
testRegisterCalldataWithRecords :: TVar ChaChaDRG -> IO ()
testRegisterCalldataWithRecords g = do
intent <- knownIntent g knownRegistration
toHex (registerWithCreditCalldata intent)
`shouldBe` "c4bd2ab50000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f4865700000000000000000000000000000000000000000000000000000000000000046000000000000000000000000000000000000000000000000000000000000001000000000000000000000000009858effd232b4033e47d90003d41ec34ecaeda940000000000000000000000000000000000000000000000000000000003c2670011111111111111111111111111111111111111111111111111111111111111110000000000000000000000002279b7a0a67db372996a5fab50d91eaa73d2ebe6000000000000000000000000000000000000000000000000000000000000014000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000762616b657279310000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000016000000000000000000000000000000000000000000000000000000000000000e410f13a8c58c186cadf476923d25ea4950487d1aaf21906ba5574c87f5b9435b61b994370000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000000f73696d706c65782e636f6e746163740000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002068747470733a2f2f736d702e73696d706c65782e696d2f6123636f6e746163740000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e410f13a8c58c186cadf476923d25ea4950487d1aaf21906ba5574c87f5b9435b61b994370000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000000f73696d706c65782e6368616e6e656c0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001d68747470733a2f2f736d70312e73696d706c65782e696d2f63236f6e65000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000041f310b273d0e0ab0975a66d383fe818a5ec3474fcd922dbf3fe70094a3c0ceae86559b13ea0728a330613c6fe236a89a026daf345dcc8c0616e9eda2c69cbeb091b00000000000000000000000000000000000000000000000000000000000000"
testRegisterCalldataWithoutRecords :: TVar ChaChaDRG -> IO ()
testRegisterCalldataWithoutRecords g = do
intent <- knownIntent g knownRegistration {rContactLink = Nothing, rChannelLink = Nothing}
toHex (registerWithCreditCalldata intent)
`shouldBe` "c4bd2ab50000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f486570000000000000000000000000000000000000000000000000000000000000001e000000000000000000000000000000000000000000000000000000000000001000000000000000000000000009858effd232b4033e47d90003d41ec34ecaeda940000000000000000000000000000000000000000000000000000000003c2670011111111111111111111111111111111111111111111111111111111111111110000000000000000000000002279b7a0a67db372996a5fab50d91eaa73d2ebe6000000000000000000000000000000000000000000000000000000000000014000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000762616b6572793100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000411d0b3a477c99fbcadada2937b71127bf6da202f5cd25856649829653d8cf6a8c0ce0afb8505e398e23b3b01fcb3b17ffcf82d8ba6d24e9b854506894b2864ecf1c00000000000000000000000000000000000000000000000000000000000000"
testCommitCalldata :: IO ()
testCommitCalldata =
toHex (commitCalldata $ makeCommitment knownRegistration) `shouldBe` "f14fcbc8810f0645b8d9839e3744bb956f9da4fa12bb51ec97459e08739c576a36cba0df"
testVerifyOtherSigner :: TVar ChaChaDRG -> IO ()
testVerifyOtherSigner g = do
other <- newEphemeralWallet g
intent <- signRegisterIntent g domain other knownRegistration deadline
verifyRegisterIntent domain deadline intent `shouldReturn` Left "intent is not signed by the owner"
testVerifyExpired :: TVar ChaChaDRG -> IO ()
testVerifyExpired g = do
intent <- knownIntent g knownRegistration
verifyRegisterIntent domain (deadline + 1) intent `shouldReturn` Left "intent expired"
testVerifyShortSecret :: TVar ChaChaDRG -> IO ()
testVerifyShortSecret g = do
intent <- knownIntent g knownRegistration {rSecret = B.replicate 31 0x11}
verifyRegisterIntent domain deadline intent `shouldReturn` Left "secret: expected 32 bytes"
testRevertedDryRun :: TVar ChaChaDRG -> IO ()
testRevertedDryRun g = withFakeEthNode $ \node -> do
-- viem's encodeErrorResult of InsufficientAllowance(10000, 2500)
setFault node "eth_estimateGas" $ revertFault $ fromHex "2a1b2dd8000000000000000000000000000000000000000000000000000000000000271000000000000000000000000000000000000000000000000000000000000009c4"
intent <- knownIntent g knownRegistration
c <- newChainClient g $ fakeChainConfig node
estimateGas c fakeSponsor (registerWithCreditCalldata intent) `shouldReturn` Left (ChainReverted $ Just RNInsufficientAllowance)
testCommitThenRegister :: TVar ChaChaDRG -> IO ()
testCommitThenRegister g = withFakeEthNode $ \node -> do
c <- newChainClient g $ fakeChainConfig node
w <- newEphemeralWallet g
ewAddress <$> walletFromCode g (redemptionCode w) `shouldReturn` ewAddress w
let registration = knownRegistration {rOwner = ewAddress w}
commitCall = commitCalldata $ makeCommitment registration
commitTx <- expectedTransaction g 0 fakeController commitCall
send g c fakeController commitCall `shouldReturn` SignedTx commitTx (TxHash $ C.keccak256 commitTx)
intent <- signRegisterIntent g domain w registration deadline
verifyRegisterIntent domain deadline intent `shouldReturn` Right ()
let registerCall = registerWithCreditCalldata intent
registerTx <- expectedTransaction g 1 fakeSponsor registerCall
send g c fakeSponsor registerCall `shouldReturn` SignedTx registerTx (TxHash $ C.keccak256 registerTx)
sentTransactions node `shouldReturn` [commitTx, registerTx]
-- | The dry run, the registrar's next nonce and the fees, then the signed transaction sent and its hash checked.
send :: TVar ChaChaDRG -> ChainClient -> Address -> ByteString -> IO SignedTx
send g c@ChainClient {ccRegistrar} to calldata = do
gas <- right' =<< estimateGas c to calldata
nonce <- right' =<< transactionCount c ccRegistrar Pending
tip <- right' =<< maxPriorityFee c
Block {blockBaseFee} <- right' =<< latestBlock c
tx@SignedTx {stRaw, stHash} <-
right <$> signTransaction g c TxRequest {trTo = to, trData = calldata, trNonce = nonce, trGasLimit = gas, trMaxFeePerGas = 2 * blockBaseFee + tip, trMaxPriorityFeePerGas = tip}
sendRawTransaction c stRaw `shouldReturn` Right stHash
pure tx
where
right' = either (fail . show) pure
-- fixtures
knownRegistration :: Registration
knownRegistration =
Registration
{ rLabel = "bakery1",
rTLD = TLDSimplex,
rOwner = address "0x9858EfFD232B4033E47d90003D41EC34EcaEda94",
rDuration = 63072000,
rSecret = B.replicate 32 0x11,
rResolver = address "0x2279b7a0a67db372996a5fab50d91eaa73d2ebe6",
rContactLink = Just "https://smp.simplex.im/a#contact",
rChannelLink = Just "https://smp1.simplex.im/c#one"
}
knownIntent :: TVar ChaChaDRG -> Registration -> IO RegisterIntent
knownIntent g r = do
w <- walletFromCode g knownCode
signRegisterIntent g domain w r deadline
knownCode :: Text
knownCode = "SN-00000-00000-00000-00000-00000-0VME2"
domain :: Eip712Domain
domain = sponsorDomain fakeChainId fakeSponsor
deadline :: Word64
deadline = 4102444800
expectedTransaction :: TVar ChaChaDRG -> Word64 -> Address -> ByteString -> IO ByteString
expectedTransaction g nonce to calldata =
right
<$> signEip1559Tx
g
fakeRegistrarKey
Eip1559Tx
{ txChainId = fakeChainId,
txNonce = nonce,
txMaxPriorityFeePerGas = fakeTip,
txMaxFeePerGas = 2 * fakeBaseFee + fakeTip,
txGasLimit = fakeGas,
txTo = to,
txValue = 0,
txData = calldata
}
acceptanceDomain :: Eip712Domain
acceptanceDomain = policyDomain fakeChainId fakeNamePolicy
-- viem: keccak256(toHex("SimpleX community terms v1")) and keccak256(toHex("alicebakery commitment"))
acceptedHash, acceptedCommitment :: ByteString
acceptedHash = fromHex "eed23f946d290583f5f55c2ae8255db70adac4fc4c5de714a920d35eed9c7dac"
acceptedCommitment = fromHex "26d4dc807322bcdc1f68a2459b580919c4e6c5629d07cb20c38a31f7b72b7e5d"
acceptanceDeadline :: Word64
acceptanceDeadline = 1767315600
testAcceptanceDigest :: IO ()
testAcceptanceDigest = do
toHex (acceptanceDigest acceptanceDomain (termsKind False) acceptedCommitment acceptedHash 3 acceptanceDeadline) `shouldBe` "f486b536cdf4e28031b02fb4345f26678a088d84846a0a6c72896062af283065"
toHex (acceptanceDigest acceptanceDomain (termsKind True) acceptedCommitment acceptedHash 3 acceptanceDeadline) `shouldBe` "6df583ad3bcbef3e4061599fa9d45174fcda5731764320cd08ade35c8324eef7"
testAcceptCalldata :: IO ()
testAcceptCalldata = do
sig <- either (fail . show) pure $ parseSignature $ "0x" <> T.replicate 32 "11" <> T.replicate 32 "22" <> "1b"
let acceptance = TermsAcceptance {taTermsHash = acceptedHash, taNonce = 3, taSignature = sig}
calldata community = toHex (acceptCalldata (termsKind community) acceptedCommitment (address "0x14dC79964da2C08b23698B3D3cc7Ca32193d9955") acceptanceDeadline acceptance)
args =
"26d4dc807322bcdc1f68a2459b580919c4e6c5629d07cb20c38a31f7b72b7e5deed23f946d290583f5f55c2ae8255db70adac4fc4c5de714a920d35eed9c7dac\
\00000000000000000000000014dc79964da2c08b23698b3d3cc7ca32193d99550000000000000000000000000000000000000000000000000000000000000003\
\000000000000000000000000000000000000000000000000000000006957189000000000000000000000000000000000000000000000000000000000000000c0\
\00000000000000000000000000000000000000000000000000000000000000411111111111111111111111111111111111111111111111111111111111111111\
\22222222222222222222222222222222222222222222222222222222222222221b00000000000000000000000000000000000000000000000000000000000000"
calldata False `shouldBe` "c50f972f" <> args
calldata True `shouldBe` "4b1a8e04" <> args
testVerifyAcceptance :: TVar ChaChaDRG -> IO ()
testVerifyAcceptance g = do
owner <- newEphemeralWallet g
other <- newEphemeralWallet g
sig <- signRecoverable g (ewKey owner) (acceptanceDigest acceptanceDomain (termsKind True) acceptedCommitment acceptedHash 3 acceptanceDeadline) >>= either fail pure
let acceptance = TermsAcceptance {taTermsHash = acceptedHash, taNonce = 3, taSignature = sig}
verify community w = verifyAcceptance acceptanceDomain (termsKind community) (ewAddress w) acceptedCommitment
verify True owner acceptanceDeadline acceptance `shouldReturn` Right ()
verify True other acceptanceDeadline acceptance `shouldReturn` Left "acceptance is not signed by the owner"
verify True owner (acceptanceDeadline + 1) acceptance `shouldReturn` Left "acceptance is not signed by the owner"
verify False owner acceptanceDeadline acceptance `shouldReturn` Left "acceptance is not signed by the owner"
address :: ByteString -> Address
address = right . strDecode
toHex :: ByteString -> ByteString
toHex = convertToBase Base16
fromHex :: ByteString -> ByteString
fromHex = right . convertFromBase Base16
right :: Either String a -> a
right = either (error . ("unexpected Left: " <>)) id