store: reveal and retry an owner's order

This commit is contained in:
sh-agents committed 2026-11-01 15:27:04 +00:00
1 parent e82eb07076
commit 06adad1f18
8 files changed
+779 -12

No files matched your search

@@ -1,6 +1,7 @@
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
-- | The checks every order runs, by paid invoice or prepaid code, in the contract's order.
module StoreService.Names.Orders
@@ -10,6 +11,8 @@ module StoreService.Names.Orders
OrderRefusal (..),
ExistingOrder (..),
ClosedOrder (..),
WriteRefusal (..),
Landing (..),
maxSealedChars,
signedRequestSeconds,
parseOrderRequest,
@@ -27,11 +30,14 @@ module StoreService.Names.Orders
checkDuration,
checkNameFree,
checkPrice,
versionWritten,
confirmLanded,
)
where
import qualified Control.Exception as E
import Control.Monad (unless, when)
import Control.Monad (forM, unless, when)
import Control.Monad.Except (ExceptT (..), runExceptT)
import qualified Data.Aeson as J
import qualified Data.Aeson.KeyMap as KM
import Data.Bifunctor (first)
@@ -51,14 +57,14 @@ import Simplex.Messaging.Eth.Address (Address, recoverAddress)
import Simplex.Messaging.SimplexName (LabelHash (..))
import Simplex.Messaging.Util (tshow)
import StoreService.Config (NamesConfig (..))
import StoreService.Log (logWarn)
import StoreService.Names.Codes (CodeRefusal (..), codeRefusal, reserveRefusal)
import StoreService.Names.Contracts (Contracts, NameStatus (..), chainPriceCents, nameStatus, secondsPerYear)
import StoreService.Log (logError, logWarn)
import StoreService.Names.Codes (CodeRefusal (..), codeRefusal, reserveRefusal, spendLandedCode)
import StoreService.Names.Contracts (Contracts, NameStatus (..), chainPriceCents, confirmedTag, nameExpires, nameStatus, ownerOfToken, secondsPerYear)
import StoreService.Names.Env (NamesEnv (..))
import StoreService.Names.Phases (Phases, RegistrationId (..))
import StoreService.Names.Abi (bytes32FromHex)
import StoreService.Names.Abi (bytes32FromHex, hex)
import StoreService.Names.Signatures (OrderFields (..), orderMessage, parseChecksumAddress, parseSignature, personalDigest)
import StoreService.Names.Store (LiveOrder (..), NameRegistration (..), NewRegistration (..), PrepaidCode (..), RegistrationRefused (..), closeOverdue, createCodeRegistration, getLiveOrders, getPrepaidCode, getRegistrationByOrderHash, isLabelRegistering)
import StoreService.Names.Store (LiveOrder (..), NamePhase (..), NameRegistration (..), NewRegistration (..), PrepaidCode (..), RegistrationPayment (..), RegistrationRefused (..), NameTransaction (..), TxFor (..), TxStatus (..), VersionWrite (..), closeOverdue, createCodeRegistration, getLiveOrders, getPrepaidCode, getPrepaidCodeById, getRegistrationByOrderHash, isLabelRegistering, registrationTransactions, updateRegistration)
import StoreService.Names.Turns (Turns, withCodeTurn)
data OrdersEnv = OrdersEnv
@@ -104,6 +110,15 @@ data ExistingOrder = EOResent NameRegistration | EONew [NameRegistration] | EOMe
-- | An overdue order a new order closed, at its new version; its invoice is now expired.
data ClosedOrder = ClosedOrder {coRegistration :: NameRegistration, coVersion :: Int64}
-- | Why an owner's write changed nothing: the registration changed since it was read, or a refusal.
data WriteRefusal = WRChanged | WRRefused OrderRefusal
deriving (Eq, Show)
-- | What /retry's first check found on the order's current name: no register through, the order registered at a new version,
-- the order changed since it was read, or a failed chain read.
data Landing = LNotLanded | LRegistered Int64 | LChanged | LUnread
deriving (Eq, Show)
maxSealedChars :: Int
maxSealedChars = 11095
@@ -241,3 +256,54 @@ checkPrice ct len years price =
unixSeconds :: UTCTime -> Integer
unixSeconds = floor . utcTimeToPOSIXSeconds
versionWritten :: VersionWrite -> Either WriteRefusal Int64
versionWritten = \case
Written v -> Right v
VersionChanged -> Left WRChanged
LiveOrderExists -> Left $ WRRefused OROrderExists
NotLive -> Left $ WRRefused ORBadRequest
-- | /retry's first check, on the order's current name: a register mined with status 1, or the owner holding the name at the confirmation depth,
-- went through with only its confirmation lost. The order then becomes registered by a compare-and-set on the version read, a code order spending its code.
-- The caller holds the turn of the order's label hash and passes the order as registrationAt reads it.
confirmLanded :: OrdersEnv -> NameRegistration -> IO Landing
confirmLanded OrdersEnv {oeStore, oeContracts, oeTurns, oeNow} r@NameRegistration {nrId, nrOwner, nrLabelHash, nrPayment} = do
txs <- withTransaction oeStore (`registrationTransactions` nrId)
let mined = [(ntHash, ntMinedBlock) | NameTransaction {ntFor = TxRegister _, ntStatus = TSMined, ntHash, ntMinedBlock} <- txs]
runExceptT (landed mined) >>= \case
Left e -> LUnread <$ logWarn ("names: a register check's chain read failed: " <> tshow e)
Right Nothing -> pure LNotLanded
Right (Just (tx, expiry)) -> either (const LChanged) LRegistered <$> markRegistered tx expiry
where
landed mined = do
confirmed <- ExceptT $ confirmedTag oeContracts
registerTx <- case mined of
tx : _ -> pure $ Just $ Just tx
[] -> (\holder -> if holder == Just nrOwner then Just Nothing else Nothing) <$> ExceptT (ownerOfToken oeContracts confirmed nrLabelHash)
forM registerTx $ \tx -> (tx,) <$> ExceptT (nameExpires oeContracts confirmed nrLabelHash)
markRegistered tx expiry = do
now <- oeNow
let registered =
r
{ nrPhase = PRegistered,
-- judged by ownerOf alone, no hash is known to have mined: none is shown (contract section 6)
nrRegisterTx = fst <$> tx,
nrRegisterBlock = snd =<< tx,
nrExpiresAt = Just expiry,
nrRegisteredAt = Just now,
nrFailedAt = Nothing,
nrError = Nothing
}
write db = versionWritten <$> updateRegistration db registered now
case nrPayment of
RPInvoice {} -> withTransaction oeStore write
RPCode codeId -> spendLandedCode oeTurns oeStore now codeId nrId write >>= traverse (paidWith codeId)
paidWith codeId (v, spent) = do
unless spent $ do
code <- withTransaction oeStore (`getPrepaidCodeById` codeId)
logError $
"names: registration " <> ridText nrId <> " turned out registered with prepaid code " <> maybe (tshow codeId) (hex . pcCodeHash) code
<> ", which was released and then spent, revoked or expired: the name was paid with it"
pure v
ridText (RegistrationId t) = t
@@ -0,0 +1,134 @@
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
-- | The reveal's checks, in the contract's order: the signed label, the order's own label and links,
-- the commitment, the owner's intent, and the links' kinds last.
module StoreService.Names.Reveal
( RevealRefusal (..),
SignedLabel (..),
RevealFields (..),
parseSignedLabel,
parseRevealFields,
isRepeat,
committedRegistration,
checkIntent,
linksValid,
revealOf,
intentOf,
)
where
import Control.Monad (unless)
import qualified Data.Aeson as J
import qualified Data.Aeson.KeyMap as KM
import Data.Bifunctor (first)
import Data.ByteString (ByteString)
import Data.Foldable (toList)
import Data.Text (Text)
import qualified Data.Text as T
import Data.Time.Clock (UTCTime)
import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds)
import Data.Word (Word64)
import Simplex.Messaging.Crypto.Secp256k1 (RecoverableSignature)
import Simplex.Messaging.SimplexName (labelHash)
import Simplex.Messaging.Util (tshow)
import StoreService.Config (ChainConfig (..), NamesConfig (..))
import StoreService.Log (logWarn)
import StoreService.Names.Abi (bytes32FromHex)
import StoreService.Names.Contracts (Contracts, sponsorNonce)
import StoreService.Names.Label (validLabel)
import StoreService.Names.Links (LinkKind (..), linkKindOf)
import StoreService.Names.Orders (integerField, textField)
import StoreService.Names.Registration (RegisterIntent (..), Registration (..), makeCommitment, sponsorDomain, verifyRegisterIntent)
import StoreService.Names.Signatures (parseSignature)
import StoreService.Names.Store (NameRegistration (..), NameReveal (..))
data RevealRefusal = RVBadRequest | RVInvalidLink | RVChainUnavailable
deriving (Eq, Show)
-- | What an identical repeat is compared on.
data SignedLabel = SignedLabel {slLabel :: Text, slSignature :: RecoverableSignature}
data RevealFields = RevealFields
{ rfSecret :: ByteString,
rfContactLinks :: [Text],
rfChannelLinks :: [Text],
rfNonce :: Word64,
rfDeadline :: Word64
}
-- | The signature's format and low s, and the label as text.
parseSignedLabel :: J.Object -> Maybe SignedLabel
parseSignedLabel o = do
slSignature <- either (const Nothing) Just . parseSignature =<< textField o "signature"
slLabel <- textField o "label"
pure SignedLabel {slLabel, slSignature}
-- | The links of each key as sent, however many; at most one per key is a check of its own.
parseRevealFields :: J.Object -> Maybe RevealFields
parseRevealFields o = do
rfSecret <- bytes32FromHex =<< textField o "secret"
rfNonce <- integerField =<< KM.lookup "nonce" o
rfDeadline <- integerField =<< KM.lookup "deadline" o
records <- case KM.lookup "records" o of
Just (J.Object records) -> Just records
_ -> Nothing
rfContactLinks <- links "contact" records
rfChannelLinks <- links "channel" records
pure RevealFields {rfSecret, rfContactLinks, rfChannelLinks, rfNonce, rfDeadline}
where
links key records = case KM.lookup key records of
Just (J.Array items) -> mapM text $ toList items
_ -> Nothing
text = \case
J.String t -> Just t
_ -> Nothing
isRepeat :: SignedLabel -> NameReveal -> Bool
isRepeat SignedLabel {slLabel, slSignature} NameReveal {rvLabel, rvSignature} = slLabel == rvLabel && slSignature == rvSignature
-- | The registration the reveal commits to, rebuilt from the order's stored owner and duration and the default resolver.
committedRegistration :: NamesConfig -> NameRegistration -> SignedLabel -> RevealFields -> Either RevealRefusal Registration
committedRegistration NamesConfig {nTLD, nChain = ChainConfig {cResolver}} NameRegistration {nrLabelHash, nrLength, nrOwner, nrDuration, nrCommitment} SignedLabel {slLabel} RevealFields {rfSecret, rfContactLinks, rfChannelLinks} = do
label <- first (const RVBadRequest) $ validLabel nTLD slLabel
unless (labelHash label == nrLabelHash && T.length label == nrLength) $ Left RVBadRequest
rContactLink <- oneLink rfContactLinks
rChannelLink <- oneLink rfChannelLinks
let r = Registration {rLabel = label, rTLD = nTLD, rOwner = nrOwner, rDuration = nrDuration, rSecret = rfSecret, rResolver = cResolver, rContactLink, rChannelLink}
unless (makeCommitment r == nrCommitment) $ Left RVBadRequest
pure r
where
oneLink = \case
[] -> Right Nothing
[link] -> Right $ Just link
_ -> Left RVInvalidLink
-- | The deadline and the owner's signature first, so a request nobody signed reads nothing from the chain.
-- A deadline before revealBefore would expire while the commitment can still register.
checkIntent :: NamesConfig -> Contracts -> UTCTime -> Maybe Word64 -> RegisterIntent -> IO (Either RevealRefusal ())
checkIntent NamesConfig {nChain = ChainConfig {cChainId, cSponsor}} ct now revealBefore intent@RegisterIntent {riRegistration = Registration {rOwner}, riNonce, riDeadline}
| maybe True (riDeadline <) revealBefore = pure $ Left RVBadRequest
| otherwise =
verifyRegisterIntent (sponsorDomain cChainId cSponsor) (floor $ utcTimeToPOSIXSeconds now) intent >>= \case
Left _ -> pure $ Left RVBadRequest
Right () ->
sponsorNonce ct rOwner >>= \case
Left e -> Left RVChainUnavailable <$ logWarn ("names: a reveal's nonce read failed: " <> tshow e)
Right nonce -> pure $ if nonce == riNonce then Right () else Left RVBadRequest
linksValid :: Registration -> Bool
linksValid Registration {rContactLink, rChannelLink} = all (ofKind LKContact) rContactLink && all (ofKind LKChannel) rChannelLink
where
ofKind kind link = linkKindOf link == Just kind
revealOf :: RegisterIntent -> NameReveal
revealOf RegisterIntent {riRegistration = Registration {rLabel, rSecret, rContactLink, rChannelLink}, riNonce, riDeadline, riSignature} =
NameReveal {rvLabel = rLabel, rvSecret = rSecret, rvContactLink = rContactLink, rvChannelLink = rChannelLink, rvNonce = riNonce, rvDeadline = riDeadline, rvSignature = riSignature}
-- | The intent an accepted reveal stored, as the register sends it.
intentOf :: NamesConfig -> NameRegistration -> NameReveal -> RegisterIntent
intentOf NamesConfig {nTLD, nChain = ChainConfig {cResolver}} NameRegistration {nrOwner, nrDuration} NameReveal {rvLabel, rvSecret, rvContactLink, rvChannelLink, rvNonce, rvDeadline, rvSignature} =
RegisterIntent {riRegistration = registration, riNonce = rvNonce, riDeadline = rvDeadline, riSignature = rvSignature}
where
registration = Registration {rLabel = rvLabel, rTLD = nTLD, rOwner = nrOwner, rDuration = nrDuration, rSecret = rvSecret, rResolver = cResolver, rContactLink = rvContactLink, rChannelLink = rvChannelLink}
@@ -9,10 +9,10 @@ import Network.HTTP.Types (Method)
import Network.Wai (Request, ResponseReceived, pathInfo)
import StoreService.Names.Env (NamesEnv (..))
import StoreService.Names.Orders (ordersEnv)
import StoreService.Web.Http (HttpEnv, Limit, Respond, codeLimit, holdMicros, limited, only, previewLimit, readLimit, searchLimit)
import StoreService.Web.Http (HttpEnv, Limit, Respond, codeLimit, createLimit, holdMicros, limited, only, previewLimit, readLimit, searchLimit)
import StoreService.Web.Names.Codes (codeCheckHandler)
import StoreService.Web.Names.Orders (codeOrderHandler)
import StoreService.Web.Names.Registration (registrationHandler)
import StoreService.Web.Names.Registration (registrationHandler, retryHandler, revealHandler)
import StoreService.Web.Names.Search (previewHandler, searchHandler)
data Route = Route
@@ -29,6 +29,8 @@ namesRoutes env@NamesEnv {neConfig, neStore, neContracts, neProfiles, neWaiters,
-- below every fixed /api/name/<word> route, which it would otherwise match
["api", "name", hash] -> Just Route {rMethod = "GET", rLimit = searchLimit, rHandler = searchHandler neConfig neStore neContracts neProfiles hash}
["api", "registration", rid] -> Just Route {rMethod = "GET", rLimit = readLimit, rHandler = registrationHandler (ordersEnv env) holdMicros rid}
["api", "registration", rid, "reveal"] -> Just Route {rMethod = "POST", rLimit = readLimit, rHandler = revealHandler (ordersEnv env) rid}
["api", "registration", rid, "retry"] -> Just Route {rMethod = "POST", rLimit = createLimit, rHandler = retryHandler (ordersEnv env) rid}
_ -> Nothing
-- | Nothing for a path no route knows. The limit is taken only once the route and the method match.
@@ -5,6 +5,8 @@
module StoreService.Web.Names.Registration
( registrationHandler,
revealHandler,
retryHandler,
registrationChangedResponse,
registrationRefusalResponse,
heldFor,
@@ -12,23 +14,31 @@ module StoreService.Web.Names.Registration
)
where
import Control.Concurrent.STM (atomically)
import Control.Monad (join)
import Data.Aeson ((.=))
import qualified Data.Aeson as J
import qualified Data.ByteString.Char8 as B
import Data.Char (isDigit)
import Data.Int (Int64)
import Data.Maybe (maybeToList)
import Data.Maybe (isJust, maybeToList)
import Data.Text (Text)
import Data.Time.Clock (UTCTime, diffUTCTime)
import Network.HTTP.Types (status200, status409)
import Network.Wai (Request, Response, ResponseReceived, queryString)
import Simplex.Messaging.Agent.Store.Common (withTransaction)
import Simplex.Messaging.Util (tshow)
import StoreService.Log (logInfo)
import StoreService.Names.Orders (OrdersEnv (..))
import StoreService.Names.Phases (RegistrationId (..), awaitChange)
import StoreService.Names.Store (NameRegistration (..), getRegistration)
import StoreService.Names.Phases (RegistrationId (..), awaitChange, publish)
import StoreService.Names.Registration (RegisterIntent (..))
import StoreService.Names.Reveal (RevealFields (..), RevealRefusal (..), SignedLabel (..), checkIntent, committedRegistration, isRepeat, linksValid, parseRevealFields, parseSignedLabel, revealOf)
import StoreService.Names.Store (NamePhase (..), NameRegistration (..), VersionWrite (..), getRegistration, updateRegistration)
import StoreService.Names.Turns (withLabelTurn)
import StoreService.Names.View (lapseMoment, registrationAt, registrationVersion, registrationView)
import StoreService.Web.Http (Respond, jsonResponse, notFound)
import StoreService.Names.Worker (Retried (..), RetryRefusal (..), retryRegistration)
import StoreService.Web.Http (Respond, badRequest, invalidLink, jsonResponse, nameBodyBytes, notFound, providerUnavailable, readBoundedBody)
import StoreService.Web.Names.Codes (codeRefusalResponse)
import Text.Read (readMaybe)
-- | GET /api/registration/:id, held while its version is seenVersion.
@@ -46,6 +56,87 @@ registrationHandler OrdersEnv {oeStore, oeConfig, oeContracts, oePhases, oeNow}
readNow = oeNow >>= \now -> fmap (now,) <$> withTransaction oeStore (`getRegistration` rid)
answer (now, r) = respond . jsonResponse status200 =<< registrationView oeStore oeConfig oeContracts (registrationAt now r)
-- | What a reveal decided in the name's turn, with the version it wrote; the publish and the answer come after the turn.
data RevealDecision
= RDAccepted (Maybe Int64)
| RDRefused RevealRefusal (Maybe Int64)
| RDChanged
| RDGone
-- | POST /api/registration/:id/reveal, its checks in the contract's order, from the stored commitment in the name's turn.
revealHandler :: OrdersEnv -> Text -> Request -> Respond -> IO ResponseReceived
revealHandler env@OrdersEnv {oeStore, oeConfig, oeContracts, oeTurns, oePhases, oeNow} ridText req respond =
withTransaction oeStore (`getRegistration` rid) >>= \case
Nothing -> respond notFound
Just NameRegistration {nrLabelHash} ->
readBoundedBody nameBodyBytes req >>= \case
Just body | Just (J.Object o) <- J.decode body, Just signed <- parseSignedLabel o -> withLabelTurn oeTurns nrLabelHash (decide nrLabelHash o signed) >>= answer
_ -> answer $ RDRefused RVBadRequest Nothing
where
rid = RegistrationId ridText
decide turnHash o signed = do
now <- oeNow
withTransaction oeStore (`getRegistration` rid) >>= \case
Nothing -> pure RDGone
Just r@NameRegistration {nrLabelHash, nrReveal}
-- moved to another name while this request waited for the turn
| nrLabelHash /= turnHash -> pure RDChanged
| Just stored <- nrReveal -> pure $ if isRepeat signed stored then RDAccepted Nothing else RDRefused RVBadRequest Nothing
| nrPhase (registrationAt now r) /= PCommitted -> pure $ RDRefused RVBadRequest Nothing
| otherwise -> case parseRevealFields o of
Nothing -> pure $ RDRefused RVBadRequest Nothing
Just fields -> either (\refusal -> pure $ RDRefused refusal Nothing) (signedReveal now r signed fields) $ committedRegistration oeConfig r signed fields
signedReveal now r SignedLabel {slSignature} RevealFields {rfNonce, rfDeadline} registration = do
let intent = RegisterIntent {riRegistration = registration, riNonce = rfNonce, riDeadline = rfDeadline, riSignature = slSignature}
checkIntent oeConfig oeContracts now (nrRevealBefore r) intent >>= \case
Left refusal -> pure $ RDRefused refusal Nothing
Right ()
| linksValid registration -> write now (RDAccepted . Just) r {nrReveal = Just $ revealOf intent}
| isJust (nrLinksRefusedAt r) -> pure $ RDRefused RVInvalidLink Nothing
| otherwise -> write now (RDRefused RVInvalidLink . Just) r {nrLinksRefusedAt = Just now}
write now decided r =
withTransaction oeStore (\db -> updateRegistration db r now) >>= \case
Written v -> pure $ decided v
_ -> pure RDChanged
answer = \case
RDAccepted v -> published v >> respond (jsonResponse status200 $ J.object [])
RDRefused refusal v -> do
published v
logInfo ("POST /api/registration/:id/reveal refused: " <> tshow refusal)
respond $ case refusal of
RVBadRequest -> badRequest
RVInvalidLink -> invalidLink
RVChainUnavailable -> providerUnavailable
RDChanged -> respond =<< registrationChangedResponse env rid
RDGone -> respond notFound
published = mapM_ (atomically . publish oePhases rid)
-- | POST /api/registration/:id/retry, Try again in the name's turn; the publish and the answer come after the turn.
retryHandler :: OrdersEnv -> Text -> Request -> Respond -> IO ResponseReceived
retryHandler env@OrdersEnv {oeStore, oeTurns, oePhases} ridText _ respond =
withTransaction oeStore (`getRegistration` rid) >>= \case
Nothing -> respond notFound
Just NameRegistration {nrLabelHash} -> withLabelTurn oeTurns nrLabelHash (decide nrLabelHash) >>= maybe (respond notFound) answer
where
rid = RegistrationId ridText
decide turnHash = withTransaction oeStore (`getRegistration` rid) >>= traverse (inTurn turnHash)
inTurn turnHash r
-- moved to another name while this request waited for the turn
| nrLabelHash r /= turnHash = pure RTChanged
| otherwise = retryRegistration env r
answer = \case
RTWritten v -> do
atomically $ publish oePhases rid v
respond . maybe notFound (jsonResponse status200) =<< currentView env rid
RTChanged -> respond =<< registrationChangedResponse env rid
RTRefused refusal -> do
logInfo ("POST /api/registration/:id/retry refused: " <> tshow refusal)
respond $ case refusal of
RFNotFailed -> badRequest
RFLinksRefused -> badRequest
RFCode code -> codeRefusalResponse code
RFUnread -> providerUnavailable
-- | The registration's current view, for a request that lost the race to change it.
registrationChangedResponse :: OrdersEnv -> RegistrationId -> IO Response
registrationChangedResponse env = registrationRefusalResponse env "registration_changed"
+10
View File
@@ -463,11 +463,14 @@ executable simplex-store-service
StoreService.Names.Phases
StoreService.Names.Profiles
StoreService.Names.Registration
StoreService.Names.Reveal
StoreService.Names.Revert
StoreService.Names.Sender
StoreService.Names.Signatures
StoreService.Names.Store
StoreService.Names.Turns
StoreService.Names.View
StoreService.Names.Worker
StoreService.Options
StoreService.Orders
StoreService.Poller
@@ -787,12 +790,16 @@ test-suite simplex-chat-test
Bots.StoreService.NamesLabelTests
Bots.StoreService.NamesLinksTests
Bots.StoreService.NamesOrdersTests
Bots.StoreService.NamesOwnerTests
Bots.StoreService.NamesPhasesTests
Bots.StoreService.NamesProfilesTests
Bots.StoreService.NamesRevealTests
Bots.StoreService.NamesSearchTests
Bots.StoreService.NamesSenderTests
Bots.StoreService.NamesSignatureTests
Bots.StoreService.NamesStoreTests
Bots.StoreService.NamesWiringTests
Bots.StoreService.NamesWorkerTests
Bots.StoreService.StoreVerifierTests
Bots.StoreService.StripeTests
Bots.StoreService.WaitersTests
@@ -826,11 +833,14 @@ test-suite simplex-chat-test
StoreService.Names.Phases
StoreService.Names.Profiles
StoreService.Names.Registration
StoreService.Names.Reveal
StoreService.Names.Revert
StoreService.Names.Sender
StoreService.Names.Signatures
StoreService.Names.Store
StoreService.Names.Turns
StoreService.Names.View
StoreService.Names.Worker
StoreService.Options
StoreService.Orders
StoreService.Poller
+456
View File
@@ -0,0 +1,456 @@
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
module Bots.StoreService.NamesRevealTests (namesRevealTests) where
import Bots.StoreService.FakeEthNode
import Bots.StoreService.NamesContractsTests (noncesCall)
import Bots.StoreService.NamesOrdersTests (Ctx (..), Order (..), aliceOrder, invoiceRegistration, orderTime, placed, post, registrationOf, settleNow, settled, withOrders)
import Bots.StoreService.NamesPhasesTests (change, held, registrationPath, seenVersion, woken)
import Bots.StoreService.NamesStoreTests (ownerA)
import Bots.StoreService.WebTests (bounded, jsonObject, statusOf, webGet, webRequestBody)
import Control.Concurrent.Async (Async, async, wait)
import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar)
import Control.Monad (forM_, replicateM)
import Crypto.Number.Serialize (i2ospOf_, os2ip)
import qualified Crypto.PubKey.ECC.Types as ECC
import qualified Data.Aeson as J
import Data.Aeson ((.=))
import qualified Data.Aeson.Key as K
import qualified Data.Aeson.KeyMap as KM
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as LB
import Data.IORef (writeIORef)
import Data.Int (Int64)
import Data.Maybe (fromJust, fromMaybe, isJust, maybeToList)
import Data.Text (Text)
import qualified Data.Text as T
import Data.Time.Clock.POSIX (posixSecondsToUTCTime, utcTimeToPOSIXSeconds)
import Data.Word (Word64)
import Network.HTTP.Client (defaultManagerSettings, newManager)
import Network.HTTP.Types (hContentType)
import Network.Wai (Application)
import qualified Network.Wai.Handler.Warp as Warp
import Simplex.Chat.PaymentService.Types (InvoiceStatus (..))
import Simplex.Messaging.Agent.Store.Common (withTransaction)
import Simplex.Messaging.Crypto.Secp256k1 (RecoverableSignature (..), Secp256k1PrivateKey, signRecoverable)
import Simplex.Messaging.Eth.EIP712 (serializeSignature)
import Simplex.Messaging.SimplexName (SimplexTLD (..))
import StoreService.Names.Abi (hex, uint256)
import StoreService.Names.Links (linkMaxBytes)
import StoreService.Names.Phases (RegistrationId (..))
import StoreService.Names.Registration (Registration (..), makeCommitment, registerIntentDigest, sponsorDomain)
import StoreService.Names.Store (NamePhase (..), NameRegistration (..), NameReveal (..), getRegistration)
import StoreService.Web.Http (holdMicros, maxBodyBytes, nameBodyBytes, readLimit)
import StoreService.Web.Names (Route (..), namesApp)
import StoreService.Web.Names.Registration (registrationHandler, revealHandler)
import StoreService.Web.Server (WebEnv (..), webApp)
import System.Timeout (timeout)
import Test.Hspec
namesRevealTests :: Spec
namesRevealTests = describe "StoreService names: reveal" $ do
describe "accepted" $ do
it "accepts a reveal with links, setting the label at a new version and waking a held poll" testWithLinks
it "accepts a reveal without links" testWithoutLinks
it "accepts the reveal the page signs, as viem signs it" testViemReveal
it "accepts a reveal with two records at the link bound, over the 8192-byte cap" testRecordsAtBound
it "answers an identical repeat in a later phase, and refuses a different one" testRepeats
it "answers after the name's turn, so a slow reader of one answer holds no other reveal" testAnswersAfterTurn
describe "refused" $ do
it "refuses a high-s intent, a wrong signer, a stale nonce, and a deadline past or before revealBefore, writing nothing" testIntentRefusals
it "refuses a label not of the order, another secret or other links, writing nothing" testCommitmentRefusals
it "refuses a commitment of another duration than the order's" testWrongDuration
it "refuses a second link for one key with invalid_link, recording nothing" testSecondLink
it "refuses an unknown id, a registration not committed or lapsed, and malformed bodies" testStateAndFormat
it "answers provider_unavailable when the nonce read fails, writing nothing" testNonceUnavailable
describe "links refusal" $ do
it "records invalid_link for a committed link one byte over the bound, waking a held poll, once" testLinksRefused
it "records no refusal for links that do not rebuild the commitment, or for another signer" testNoRefusalRecorded
describe "races" $ do
it "answers registration_changed with the current view when the registration changed during the checks" testLostRace
it "takes one read token per request, whatever its outcome" testReadToken
-- fixtures
data Fx = Fx {fCtx :: Ctx, fApp :: Application}
-- | The registration routes as namesRoutes registers them, the reveal's included.
withReveals :: (Fx -> IO a) -> IO a
withReveals action = withOrders $ \ctx@Ctx {cNode, cOrders, cWeb} -> do
answerCall cNode fakeSponsor noncesCall $ Returns $ uint256 (0 :: Int)
let web = cWeb {weOrders = Just cOrders}
routes = \case
["api", "registration", rid] -> Just Route {rMethod = "GET", rLimit = readLimit, rHandler = registrationHandler cOrders holdMicros rid}
["api", "registration", rid, "reveal"] -> Just Route {rMethod = "POST", rLimit = readLimit, rHandler = revealHandler cOrders rid}
_ -> Nothing
app req respond = fromMaybe (webApp web req respond) (namesApp (weHttp web) routes req respond)
mgr <- newManager defaultManagerSettings
Warp.testWithApplication (pure app) $ \port ->
action Fx {fCtx = ctx {cWeb = web, cClient = (mgr, "http://127.0.0.1:" <> show port)}, fApp = app}
-- | The request, held at its first chain read: a reveal's nonce read or its last check before it writes, in its turns.
pausedAtChainRead :: Ctx -> IO a -> IO (Async a, Gate)
pausedAtChainRead Ctx {cNode} = pausedAt cNode "eth_call"
orderSeconds :: Word64
orderSeconds = floor $ utcTimeToPOSIXSeconds orderTime
-- | The commit's window: opened a minute before the order's time, closing a day after it.
revealAfter, revealBefore :: Word64
revealAfter = orderSeconds - 60
revealBefore = orderSeconds + 86400
keyA :: Secp256k1PrivateKey
keyA = oKey aliceOrder
contactLink, channelLink :: Text
contactLink = "https://smp8.simplex.im/a#Y8m3qT0vLw2Ab7cD9eF1gH3jK5mN7pQ9rS"
channelLink = "simplex:/c#Rk27xN4pDe9Tz1Wb3Yc5Vd7Xf9Hg2Jk4Lm?v=1"
-- | A short link of the kind's path padded to this many bytes.
padded :: Text -> Int -> Text
padded kind n = base <> T.replicate (n - T.length base) "a"
where
base = "https://smp6.simplex.im/" <> kind <> "#lrdvu2d8A1GumSmoKb2krQmtKhWXq-tyGpHuM7aMwsw?x="
alice :: Registration
alice =
Registration
{ rLabel = "alicebakery",
rTLD = TLDSimplex,
rOwner = ownerA,
rDuration = oDuration aliceOrder,
rSecret = B.replicate 32 0x5a,
rResolver = fakeResolver,
rContactLink = Just contactLink,
rChannelLink = Just channelLink
}
-- | The same owner's order for another name, at its 7-letter price.
dynamis :: Registration
dynamis = alice {rLabel = "dynamis"}
-- | At the launch prices for 2 years that the orders fixture answers: 7 letters 20000 cents, 11 letters 10000.
orderOf :: Registration -> Order
orderOf r@Registration {rLabel} = aliceOrder {oLabel = rLabel, oCommitment = makeCommitment r, oPrice = if T.length rLabel == 7 then 20000 else 10000}
-- | Ordered, paid, and committed by the worker with its reveal window open.
committed :: Ctx -> Order -> IO RegistrationId
committed ctx o = do
NameRegistration {nrId} <- paidOrder ctx o
_ <- change ctx nrId $ \r -> r {nrPhase = PCommitted, nrRevealAfter = Just revealAfter, nrRevealBefore = Just revealBefore}
pure nrId
paidOrder :: Ctx -> Order -> IO NameRegistration
paidOrder ctx o = do
(inv, _) <- placed ctx o
settleNow ctx inv settled `shouldReturn` Right ISPaid
invoiceRegistration ctx inv
signIntent :: Ctx -> Secp256k1PrivateKey -> Registration -> Word64 -> Word64 -> IO RecoverableSignature
signIntent Ctx {cRandom} key r nonce deadline =
either error id <$> signRecoverable cRandom key (registerIntentDigest (sponsorDomain fakeChainId fakeSponsor) r nonce deadline)
bodyOf :: RecoverableSignature -> Registration -> Word64 -> Word64 -> J.Object
bodyOf sig Registration {rLabel, rSecret, rContactLink, rChannelLink} nonce deadline =
KM.fromList
[ ("label", J.String rLabel),
("secret", J.String $ hex rSecret),
("records", J.object ["contact" .= maybeToList rContactLink, "channel" .= maybeToList rChannelLink]),
("nonce", J.toJSON nonce),
("deadline", J.toJSON deadline),
("signature", J.String $ hex $ serializeSignature sig)
]
-- | As the page sends it: the owner's intent for the chain's nonce 0, until the commitment's revealBefore.
ownerBody :: Ctx -> Registration -> IO J.Object
ownerBody ctx r = (\sig -> bodyOf sig r 0 revealBefore) <$> signIntent ctx keyA r 0 revealBefore
withRecords :: [Text] -> [Text] -> J.Object -> J.Object
withRecords contact channel = KM.insert "records" $ J.object ["contact" .= contact, "channel" .= channel]
ownerReveal :: Ctx -> RegistrationId -> Registration -> IO (Int, Maybe J.Object)
ownerReveal ctx rid r = reveal ctx rid =<< ownerBody ctx r
revealPath :: RegistrationId -> String
revealPath rid = registrationPath rid <> "/reveal"
reveal :: Ctx -> RegistrationId -> J.Object -> IO (Int, Maybe J.Object)
reveal ctx rid = post ctx (revealPath rid) . J.encode
accepted :: (Int, Maybe J.Object)
accepted = (200, Just KM.empty)
refused :: Int -> Text -> (Int, Maybe J.Object)
refused status tag = (status, Just $ KM.singleton "error" (J.String tag))
badRequest :: (Int, Maybe J.Object)
badRequest = refused 400 "bad_request"
stored :: Ctx -> RegistrationId -> IO NameRegistration
stored Ctx {cStore} rid = withTransaction cStore $ \db -> fromJust <$> getRegistration db rid
-- | The fields a refused reveal must leave as they were.
unwritten :: NameRegistration -> (Int64, Maybe NameReveal, Bool)
unwritten NameRegistration {nrVersion, nrReveal, nrLinksRefusedAt} = (nrVersion, nrReveal, isJust nrLinksRefusedAt)
field :: Text -> J.Object -> Maybe J.Value
field k = KM.lookup (K.fromText k)
-- | The same signature with s mirrored to n - s, which recovers the same signer.
highS :: RecoverableSignature -> RecoverableSignature
highS sig@RecoverableSignature {rsS, rsRecId} = sig {rsS = i2ospOf_ 32 (n - os2ip rsS), rsRecId = 1 - rsRecId}
where
n = ECC.ecc_n $ ECC.common_curve $ ECC.getCurveByName ECC.SEC_p256k1
-- | Waits until this many requests hold or wait for the label's turn.
-- tests
testWithLinks :: IO ()
testWithLinks = bounded "with links" $ withReveals $ \Fx {fCtx = ctx} -> do
rid <- committed ctx (orderOf alice)
NameRegistration {nrVersion = v} <- stored ctx rid
poll <- held ctx (0, 1) $ registrationPath rid <> seenVersion v
sig <- signIntent ctx keyA alice 0 revealBefore
reveal ctx rid (bodyOf sig alice 0 revealBefore) `shouldReturn` accepted
NameRegistration {nrVersion, nrPhase, nrReveal, nrLinksRefusedAt} <- stored ctx rid
(nrVersion, nrPhase, nrLinksRefusedAt) `shouldBe` (v + 1, PCommitted, Nothing)
nrReveal
`shouldBe` Just NameReveal {rvLabel = "alicebakery", rvSecret = rSecret alice, rvContactLink = Just contactLink, rvChannelLink = Just channelLink, rvNonce = 0, rvDeadline = revealBefore, rvSignature = sig}
(status, view) <- woken "registration poll" poll
(status, field "version" view, field "label" view) `shouldBe` (200, Just (J.toJSON $ v + 1), Just "alicebakery")
testWithoutLinks :: IO ()
testWithoutLinks = withReveals $ \Fx {fCtx = ctx} -> do
let bare = alice {rContactLink = Nothing, rChannelLink = Nothing}
rid <- committed ctx (orderOf bare)
ownerReveal ctx rid bare `shouldReturn` accepted
fmap (\NameReveal {rvLabel, rvContactLink, rvChannelLink} -> (rvLabel, rvContactLink, rvChannelLink)) . nrReveal <$> stored ctx rid
`shouldReturn` Just ("alicebakery", Nothing, Nothing)
-- | The webapp's dynamis order (NamesSignatureTests), revealed with viem 2.57.5's signTypedData by the webapp's wallet, account 0.
testViemReveal :: IO ()
testViemReveal = withReveals $ \Fx {fCtx = ctx} -> do
let page = dynamis {rSecret = B.replicate 32 0x11, rContactLink = Just "https://smp8.simplex.im/a#contact", rChannelLink = Nothing}
viemSignature = "0xed92eb1e37a191cb270651b57fd132eb652357a90aa602e8c29ed1dfabe0a14738f0bfe38fc2d9687ad5e0820cad2f5af386f00087cb91b4eb6577c2ec2869641c"
body =
KM.fromList
[ ("label", "dynamis"),
("secret", J.String $ "0x" <> T.replicate 32 "11"),
("records", J.object ["contact" .= ["https://smp8.simplex.im/a#contact" :: Text], "channel" .= ([] :: [Text])]),
("nonce", J.Number 0),
("deadline", J.Number 1792660500),
("signature", J.String viemSignature)
]
hex (makeCommitment page) `shouldBe` "0x9cf04ddef2eedfb02e6e7ba58f879c0636c584b6acc67ffe9f97a06bfb016ac1"
(\sig -> bodyOf sig page 0 revealBefore) <$> signIntent ctx keyA page 0 revealBefore `shouldReturn` body
rid <- committed ctx (orderOf page)
reveal ctx rid body `shouldReturn` accepted
testRecordsAtBound :: IO ()
testRecordsAtBound = withReveals $ \Fx {fCtx = ctx} -> do
let longest = alice {rContactLink = Just $ padded "a" linkMaxBytes, rChannelLink = Just $ padded "c" linkMaxBytes}
rid <- committed ctx (orderOf longest)
body <- J.encode <$> ownerBody ctx longest
LB.length body `shouldSatisfy` (\n -> n > fromIntegral maxBodyBytes && n <= fromIntegral nameBodyBytes)
post ctx (revealPath rid) body `shouldReturn` accepted
testRepeats :: IO ()
testRepeats = withReveals $ \Fx {fCtx = ctx} -> do
rid <- committed ctx (orderOf alice)
body <- ownerBody ctx alice
reveal ctx rid body `shouldReturn` accepted
v <- change ctx rid $ \r -> r {nrPhase = PRegistering}
reveal ctx rid body `shouldReturn` accepted
resigned <- (\sig -> bodyOf sig alice 0 revealBefore) <$> signIntent ctx keyA alice 1 revealBefore
reveal ctx rid resigned `shouldReturn` badRequest
reveal ctx rid (KM.insert "label" "alicebakerz" body) `shouldReturn` badRequest
nrVersion <$> stored ctx rid `shouldReturn` v
-- | A response held before it is written, as for a client that reads it slowly, must not hold the name's turn.
testAnswersAfterTurn :: IO ()
testAnswersAfterTurn = bounded "answers after the turn" $ withReveals $ \Fx {fCtx = ctx, fApp} -> do
rid <- committed ctx (orderOf alice)
body <- ownerBody ctx alice
writing <- newEmptyMVar
release <- newEmptyMVar
let slow req respond = fApp req $ \r -> putMVar writing () >> takeMVar release >> respond r
mgr <- newManager defaultManagerSettings
Warp.testWithApplication (pure slow) $ \port -> do
first' <- async $ statusOf <$> webRequestBody (mgr, "http://127.0.0.1:" <> show port) "POST" (revealPath rid) [(hContentType, "application/json")] (J.encode body)
takeMVar writing
timeout 2000000 (reveal ctx rid body) `shouldReturn` Just accepted
putMVar release ()
wait first' `shouldReturn` 200
testIntentRefusals :: IO ()
testIntentRefusals = withReveals $ \Fx {fCtx = ctx@Ctx {cNode}} -> do
rid <- committed ctx (orderOf alice)
unchanged <- unwritten <$> stored ctx rid
sig <- signIntent ctx keyA alice 0 revealBefore
other <- signIntent ctx fakeRegistrarKey alice 0 revealBefore
early <- signIntent ctx keyA alice 0 (revealBefore - 1)
past <- signIntent ctx keyA alice 0 (orderSeconds - 1)
forM_
[ ("high s", bodyOf (highS sig) alice 0 revealBefore),
("another signer", bodyOf other alice 0 revealBefore),
("a deadline a second before revealBefore", bodyOf early alice 0 (revealBefore - 1)),
("a past deadline", bodyOf past alice 0 (orderSeconds - 1))
]
$ \(what, body) -> (what,) <$> reveal ctx rid body `shouldReturn` (what :: String, badRequest)
answerCall cNode fakeSponsor noncesCall $ Returns $ uint256 (1 :: Int)
reveal ctx rid (bodyOf sig alice 0 revealBefore) `shouldReturn` badRequest
unwritten <$> stored ctx rid `shouldReturn` unchanged
answerCall cNode fakeSponsor noncesCall $ Returns $ uint256 (0 :: Int)
reveal ctx rid (bodyOf sig alice 0 revealBefore) `shouldReturn` accepted
testCommitmentRefusals :: IO ()
testCommitmentRefusals = withReveals $ \Fx {fCtx = ctx} -> do
rid <- committed ctx (orderOf alice)
unchanged <- unwritten <$> stored ctx rid
forM_
[ ("a label of another hash", alice {rLabel = "alicebakerz"}),
("a label in upper case", alice {rLabel = "Alicebakery"}),
("another secret", alice {rSecret = B.replicate 32 0x5b}),
("another contact link", alice {rContactLink = Just "https://smp8.simplex.im/a#other"}),
("no channel link", alice {rChannelLink = Nothing})
]
$ \(what, r) -> (what,) <$> ownerReveal ctx rid r `shouldReturn` (what :: String, badRequest)
unwritten <$> stored ctx rid `shouldReturn` unchanged
ownerReveal ctx rid alice `shouldReturn` accepted
-- | The commitment is of another duration than the order states; the intent, of the order's, passes on its own.
testWrongDuration :: IO ()
testWrongDuration = withReveals $ \Fx {fCtx = ctx} -> do
rid <- committed ctx (orderOf alice {rDuration = rDuration alice + 1})
nrDuration <$> stored ctx rid `shouldReturn` rDuration alice
ownerReveal ctx rid alice `shouldReturn` badRequest
nrReveal <$> stored ctx rid `shouldReturn` Nothing
testSecondLink :: IO ()
testSecondLink = withReveals $ \Fx {fCtx = ctx} -> do
rid <- committed ctx (orderOf alice)
unchanged <- unwritten <$> stored ctx rid
body <- ownerBody ctx alice
reveal ctx rid (withRecords [contactLink, "https://smp8.simplex.im/a#other"] [channelLink] body) `shouldReturn` refused 400 "invalid_link"
reveal ctx rid (withRecords [contactLink] [channelLink, channelLink] body) `shouldReturn` refused 400 "invalid_link"
unwritten <$> stored ctx rid `shouldReturn` unchanged
testStateAndFormat :: IO ()
testStateAndFormat = withReveals $ \Fx {fCtx = ctx@Ctx {cClock}} -> do
body <- ownerBody ctx alice
reveal ctx (RegistrationId "t2Jk8RmQ4vXw9NcP3yLb6g") body `shouldReturn` refused 404 "not_found"
NameRegistration {nrId = rid} <- paidOrder ctx (orderOf alice)
reveal ctx rid body `shouldReturn` badRequest
_ <- change ctx rid $ \r -> r {nrPhase = PCommitted, nrRevealAfter = Just revealAfter, nrRevealBefore = Just revealBefore}
unchanged <- unwritten <$> stored ctx rid
let text k = case KM.lookup k body of
Just (J.String t) -> t
_ -> error "not text"
upper t = "0x" <> T.toUpper (T.drop 2 t)
forM_
[ ("a signature in upper case", KM.insert "signature" (J.String $ upper $ text "signature") body),
("no signature", KM.delete "signature" body),
("a label that is not text", KM.insert "label" (J.Number 1) body),
("a secret in upper case", KM.insert "secret" (J.String $ upper $ text "secret") body),
("a short secret", KM.insert "secret" (J.String $ T.dropEnd 2 $ text "secret") body),
("a nonce as text", KM.insert "nonce" (J.String "0") body),
("a fractional deadline", KM.insert "deadline" (J.Number 1792660500.5) body),
("no records", KM.delete "records" body),
("records without a channel list", KM.insert "records" (J.object ["contact" .= [contactLink]]) body),
("a link that is not text", KM.insert "records" (J.object ["contact" .= [J.Number 1], "channel" .= [channelLink]]) body)
]
$ \(what, b) -> (what,) <$> reveal ctx rid b `shouldReturn` (what :: String, badRequest)
forM_ [("not an object", "[]"), ("not JSON", "label=alicebakery"), ("over the cap", J.encode $ KM.insert "pad" (J.String $ T.replicate nameBodyBytes "a") body)] $
\(what, b) -> (what,) <$> post ctx (revealPath rid) b `shouldReturn` (what :: String, badRequest)
unwritten <$> stored ctx rid `shouldReturn` unchanged
-- signed past revealBefore, so only the lapse refuses it
let deadline = revealBefore + 3600
late <- (\sig -> bodyOf sig alice 0 deadline) <$> signIntent ctx keyA alice 0 deadline
writeIORef cClock $ posixSecondsToUTCTime $ fromIntegral revealBefore + 1
reveal ctx rid late `shouldReturn` badRequest
unwritten <$> stored ctx rid `shouldReturn` unchanged
writeIORef cClock orderTime
reveal ctx rid late `shouldReturn` accepted
testNonceUnavailable :: IO ()
testNonceUnavailable = withReveals $ \Fx {fCtx = ctx@Ctx {cNode}} -> do
rid <- committed ctx (orderOf alice)
unchanged <- unwritten <$> stored ctx rid
body <- ownerBody ctx alice
setFault cNode "eth_call" HttpFailure
reveal ctx rid body `shouldReturn` refused 503 "provider_unavailable"
clearFault cNode "eth_call"
unwritten <$> stored ctx rid `shouldReturn` unchanged
reveal ctx rid body `shouldReturn` accepted
testLinksRefused :: IO ()
testLinksRefused = bounded "links refused" $ withReveals $ \Fx {fCtx = ctx@Ctx {cClient}} -> do
let overBound = alice {rContactLink = Just $ padded "a" (linkMaxBytes + 1)}
rid <- committed ctx (orderOf overBound)
NameRegistration {nrVersion = v} <- stored ctx rid
poll <- held ctx (0, 1) $ registrationPath rid <> seenVersion v
body <- ownerBody ctx overBound
reveal ctx rid body `shouldReturn` refused 400 "invalid_link"
(status, view) <- woken "registration poll" poll
(status, field "version" view, field "linksRefused" view, field "label" view) `shouldBe` (200, Just (J.toJSON $ v + 1), Just (J.Bool True), Just J.Null)
NameRegistration {nrVersion, nrReveal, nrLinksRefusedAt} <- stored ctx rid
(nrVersion, nrReveal, nrLinksRefusedAt) `shouldBe` (v + 1, Nothing, Just orderTime)
-- another browser, holding only the order link
r <- webGet cClient (registrationPath rid)
other <- jsonObject r
(statusOf r, field "linksRefused" other) `shouldBe` (200, Just (J.Bool True))
reveal ctx rid body `shouldReturn` refused 400 "invalid_link"
unwritten <$> stored ctx rid `shouldReturn` (v + 1, Nothing, True)
testNoRefusalRecorded :: IO ()
testNoRefusalRecorded = withReveals $ \Fx {fCtx = ctx} -> do
committedGood <- committed ctx (orderOf alice)
goodBefore <- unwritten <$> stored ctx committedGood
ownerReveal ctx committedGood alice {rContactLink = Just "hello"} `shouldReturn` badRequest
unwritten <$> stored ctx committedGood `shouldReturn` goodBefore
let overBound = dynamis {rContactLink = Just $ padded "a" (linkMaxBytes + 1)}
committedBad <- committed ctx (orderOf overBound)
badBefore <- unwritten <$> stored ctx committedBad
other <- signIntent ctx fakeRegistrarKey overBound 0 revealBefore
reveal ctx committedBad (bodyOf other overBound 0 revealBefore) `shouldReturn` badRequest
unwritten <$> stored ctx committedBad `shouldReturn` badBefore
ownerReveal ctx committedBad overBound `shouldReturn` refused 400 "invalid_link"
isJust . nrLinksRefusedAt <$> stored ctx committedBad `shouldReturn` True
-- | A writer that takes no turn, as the worker re-committing, moves the version while the reveal reads the nonce.
testLostRace :: IO ()
testLostRace = bounded "lost race" $ withReveals $ \Fx {fCtx = ctx} -> do
let overBound = dynamis {rContactLink = Just $ padded "a" (linkMaxBytes + 1)}
forM_ [(alice, "accepted"), (overBound, "links refused")] $ \(r, what :: String) -> do
rid <- committed ctx (orderOf r)
body <- ownerBody ctx r
(inFlight, gate) <- pausedAtChainRead ctx (reveal ctx rid body)
v <- change ctx rid $ \x -> x {nrRevealAfter = (+ 60) <$> nrRevealAfter x, nrRevealBefore = (+ 60) <$> nrRevealBefore x}
releaseGate gate
(status, answer) <- wait inFlight
let view = registrationOf $ fromJust answer
(what, status, field "error" =<< answer, field "version" view, field "label" view, field "linksRefused" view, field "revealBefore" view)
`shouldBe` (what, 409, Just "registration_changed", Just (J.toJSON v), Just J.Null, Just (J.Bool False), Just (J.toJSON $ revealBefore + 60))
(what,) . unwritten <$> stored ctx rid `shouldReturn` (what, (v, Nothing, False))
testReadToken :: IO ()
testReadToken = withReveals $ \Fx {fCtx = ctx@Ctx {cClient}} -> do
rid <- committed ctx (orderOf alice)
body <- J.encode <$> ownerBody ctx alice
let client = [(hContentType, "application/json"), ("X-Forwarded-For", "203.0.113.9")]
from verb path b = statusOf <$> webRequestBody cClient verb path client b
round' =
sequence
[ from "POST" (revealPath rid) body,
from "POST" (revealPath rid) "{}",
from "POST" (revealPath $ RegistrationId "t2Jk8RmQ4vXw9NcP3yLb6g") body,
from "GET" (registrationPath rid) ""
]
concat <$> replicateM 15 round' `shouldReturn` concat (replicate 15 [200, 400, 404, 200])
from "POST" (revealPath rid) body `shouldReturn` 429
from "GET" (registrationPath rid) "" `shouldReturn` 429
@@ -113,6 +113,7 @@ namesConfig node =
nYears = 2,
nTermStart = UTCTime (fromGregorian 2027 1 1) 0,
nTermSlackSeconds = 3600,
nRevealMarginSeconds = 900,
nCodesOnly = False,
nChain = fakeChainConfig node
}
+7
View File
@@ -18,10 +18,13 @@ import Bots.StoreService.NamesLinksTests
import Bots.StoreService.NamesOrdersTests
import Bots.StoreService.NamesPhasesTests
import Bots.StoreService.NamesProfilesTests
import Bots.StoreService.NamesRevealTests
import Bots.StoreService.NamesSearchTests
import Bots.StoreService.NamesSenderTests
import Bots.StoreService.NamesSignatureTests
import Bots.StoreService.NamesStoreTests
import Bots.StoreService.NamesWiringTests
import Bots.StoreService.NamesWorkerTests
import Bots.StoreService.StoreVerifierTests
import Bots.StoreService.StripeTests
import Bots.StoreService.WaitersTests
@@ -109,10 +112,13 @@ main = do
namesOrdersTests
namesPhasesTests
namesProfilesTests
namesRevealTests
namesSearchTests
namesSenderTests
namesSignatureTests
namesStoreTests
namesWiringTests
namesWorkerTests
describe "SimpleX chat markdown" markdownTests
describe "JSON Tests" jsonTests
describe "Member relations" memberRelationsTests
@@ -144,6 +150,7 @@ main = do
storeServiceTests
describe "managed group" badgeGroupIntegrationTests
describe "StoreService names: boot" namesBootTests
describe "StoreService names: worker" namesWorkerBootTests
namesCodesChatTests
namesProfilesChatTests
describe "Remote session" remoteTests