store: relay owners' link edits on chain

This commit is contained in:
sh-agents committed 2026-11-02 06:58:36 +00:00
1 parent 0ab19a8e5b
commit 7b4997fa80
21 files changed
+2282 -47

No files matched your search

@@ -11,6 +11,7 @@ import StoreService.Names.Chain (ChainClient, newChainClient)
import StoreService.Names.Contracts (Contracts, newContracts)
import StoreService.Names.Phases (Phases, newPhases)
import StoreService.Names.Profiles (Profiles, chatProfile, defaultProfileLimits, monotonicSeconds, newProfiles, systemResolver)
import StoreService.Names.Records (Records, newRecords)
import StoreService.Names.Sender (Sender, newSender)
import StoreService.Names.Turns (Turns)
import StoreService.Providers (Provider)
@@ -27,15 +28,17 @@ data NamesEnv = NamesEnv
neContracts :: Contracts,
neProfiles :: Profiles,
neSender :: Sender,
neRecords :: Records,
neWaiters :: Waiters,
neProviders :: [Provider]
}
newNamesEnv :: ChatController -> UserId -> NamesConfig -> DBStore -> Turns -> Waiters -> [Provider] -> IO NamesEnv
newNamesEnv neChat@ChatController {random} neUserId neConfig@NamesConfig {nTLD, nChain} neStore neTurns neWaiters neProviders = do
newNamesEnv neChat@ChatController {random} neUserId neConfig@NamesConfig {nTLD, nChain, nRecordEditsPerYear} neStore neTurns neWaiters neProviders = do
nePhases <- newPhases
neChain <- newChainClient random nChain
neContracts <- newContracts nTLD neChain
neProfiles <- newProfiles defaultProfileLimits monotonicSeconds (chatProfile neChat neUserId) systemResolver
neSender <- newSender random neChain neStore getCurrentTime
pure NamesEnv {neChat, neUserId, neConfig, neStore, nePhases, neTurns, neChain, neContracts, neProfiles, neSender, neWaiters, neProviders}
neRecords <- newRecords neStore neTurns neContracts neChain neSender nTLD nRecordEditsPerYear getCurrentTime
pure NamesEnv {neChat, neUserId, neConfig, neStore, nePhases, neTurns, neChain, neContracts, neProfiles, neSender, neRecords, neWaiters, neProviders}
@@ -0,0 +1,414 @@
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
-- | Record edits signed by a name's owner, each request relayed as one transaction through the registrar key's sender and followed to its outcome.
module StoreService.Names.Records
( Records (rsPendingAfter, rsEditsPerYear),
EditRequest (..),
EditAnswer (..),
EditsLeft (..),
newRecords,
nameEditsLeft,
relayEdit,
runRecordEdits,
recordsRound,
)
where
import Control.Concurrent (threadDelay)
import Control.Concurrent.STM
import Control.Exception (bracket)
import Control.Monad (forM, forM_, forever, unless, void, when)
import Control.Monad.Except (ExceptT (..), runExceptT)
import Control.Monad.IO.Class (liftIO)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.Int (Int64)
import Data.List.NonEmpty (NonEmpty (..))
import qualified Data.List.NonEmpty as L
import Data.Maybe (listToMaybe)
import Data.Set (Set)
import qualified Data.Set as S
import Data.Text (Text)
import Data.Text.Encoding (encodeUtf8)
import Data.Time.Clock (NominalDiffTime, UTCTime, addUTCTime, diffUTCTime)
import Data.Word (Word64)
import Simplex.Messaging.Agent.Store.Common (DBStore, withTransaction)
import qualified Simplex.Messaging.Agent.Store.DB as DB
import Simplex.Messaging.Crypto (sha256Hash)
import Simplex.Messaging.Eth.Address (Address, recoverAddress)
import Simplex.Messaging.Eth.EIP712 (Eip712Domain, serializeSignature)
import Simplex.Messaging.SimplexName (LabelHash, SimplexTLD)
import Simplex.Messaging.Util (tshow)
import StoreService.Config (ChainConfig (..))
import StoreService.Log (logWarn, safely)
import StoreService.Names.Chain
import StoreService.Names.Contracts (Contracts, NameStatus (..), RegisteredName (..), nameStatus, resolverNonce, textRecord)
import StoreService.Names.Registration (Node, channelRecordKey, clearRecordsDigest, clearRecordsWithSigCalldata, contactRecordKey, labelNode, multicallCalldata, resolverDomain, setTextDigest, setTextWithSigCalldata)
import StoreService.Names.Revert (RevertName (..), revertText)
import StoreService.Names.Sender (SendError (..), Sender, submitTransaction)
import StoreService.Names.Store
import StoreService.Names.Turns (Turns, withLabelTurn)
data Records = Records
{ rsStore :: DBStore,
rsTurns :: Turns,
rsContracts :: Contracts,
rsChain :: ChainClient,
rsSender :: Sender,
rsTLD :: SimplexTLD,
rsEditsPerYear :: Int,
rsNow :: IO UTCTime,
-- | microseconds a request waits for its edit's outcome
rsPendingAfter :: Int,
-- | the edits a request or the lane is sending or judging, so no edit is sent twice
rsClaimed :: TVar (Set Int64),
-- | the pending edits whose last chain read failed
rsStalled :: TVar (Set Int64),
-- | grows on every settlement and stall, waking the requests that wait for an edit
rsChanges :: TVar Int
}
-- | The changes of one Save, in nonce order, relayed together or not at all.
data EditRequest = EditRequest
{ erLabelHash :: LabelHash,
erChanges :: NonEmpty SignedChange
}
deriving (Eq, Show)
data EditAnswer
= -- | mined, Nothing when found applied with the applying transaction unknown
EAApplied (Maybe TxHash)
| -- | the revert's name when known; the nonce is free again
EAReverted (Maybe Text)
| -- | not settled within the wait, or the chain stopped answering after the send; the edit goes on
EAPending
| -- | the signers, the deadline, the owner or the nonce
EARefused
| -- | the chain failed before anything was sent, and nothing is stored
EAUnavailable
| -- | the per-name cap, with the seconds until another edit fits
EACapped Int
| -- | the name's yearly limit is used up until this time
EALimited UTCTime
deriving (Eq, Show)
-- | The edits a name has left in its window, and when the next one returns; Nothing while none counts.
data EditsLeft = EditsLeft {elLeft :: Int, elNextAt :: Maybe UTCTime}
deriving (Eq, Show)
-- | What the chain shows of an edit none of whose transactions mined.
data Judgment
= -- | one of its own hashes, or Nothing when the nonce passed with the record holding its value
Applied (Maybe TxHash)
| -- | the nonce passed with the record holding another value
NonceTaken
| NonceFree
-- | Below a proxy's idle timeout; the edit goes on after it.
editPendingAfter :: Int
editPendingAfter = 90000000
-- | Relayed edits per name in 'editCapWindow'.
editCap :: Int
editCap = 10
editCapWindow :: NominalDiffTime
editCapWindow = 3600
-- | The window of the yearly limit, in 365-day years as the names' terms count them.
editLimitWindow :: NominalDiffTime
editLimitWindow = 365 * 86400
recordsInterval :: Int
recordsInterval = 4000000
newRecords :: DBStore -> Turns -> Contracts -> ChainClient -> Sender -> SimplexTLD -> Int -> IO UTCTime -> IO Records
newRecords rsStore rsTurns rsContracts rsChain rsSender rsTLD rsEditsPerYear rsNow = do
rsClaimed <- newTVarIO S.empty
rsStalled <- newTVarIO S.empty
rsChanges <- newTVarIO 0
pure Records {rsStore, rsTurns, rsContracts, rsChain, rsSender, rsTLD, rsEditsPerYear, rsNow, rsPendingAfter = editPendingAfter, rsClaimed, rsStalled, rsChanges}
-- | A pending or mined edit counts. One refused, never sent, or reverted on chain does not.
nameEditsLeft :: DB.Connection -> Int -> LabelHash -> UTCTime -> IO EditsLeft
nameEditsLeft db perYear lh now = do
times <- countedEditTimes db lh $ addUTCTime (negate editLimitWindow) now
let counted = length times
-- the oldest edit returns one, unless a lowered limit is overrun and later ones must go too
pure EditsLeft {elLeft = max 0 $ perYear - counted, elNextAt = addUTCTime editLimitWindow <$> listToMaybe (drop (counted - perYear) times)}
-- | When the name's yearly limit is used up, the time the next edit fits.
usedUpUntil :: EditsLeft -> Maybe UTCTime
usedUpUntil EditsLeft {elLeft, elNextAt} = if elLeft == 0 then elNextAt else Nothing
-- | An identical repeat of a sent edit is answered from it, and the yearly limit is checked, before any chain read.
-- The wait for an outcome is bounded from the request's arrival, so the checks and the send count toward it.
relayEdit :: Records -> EditRequest -> IO EditAnswer
relayEdit rs@Records {rsPendingAfter, rsEditsPerYear, rsNow} req@EditRequest {erLabelHash, erChanges} = do
timer <- registerDelay rsPendingAfter
sequence <$> mapM (\(digest, SignedChange {scSignature}) -> recoverAddress scSignature digest) signed >>= \case
Right (signer :| others) | all (== signer) others ->
withStore rs (`getRecordEditByBody` bodyHash) >>= \case
Just RecordEdit {reId} -> awaitEdit rs timer reId
Nothing -> do
now <- rsNow
withStore rs (\db -> usedUpUntil <$> nameEditsLeft db rsEditsPerYear erLabelHash now)
>>= maybe (newEdit rs timer req signer bodyHash) (pure . EALimited)
_ -> pure EARefused
where
signed = L.map (\change -> (changeDigest rs erLabelHash change, change)) erChanges
-- one change hashes as edits stored before requests took two, so their repeats still match
bodyHash = sha256Hash $ B.concat [digest <> serializeSignature scSignature | (digest, SignedChange {scSignature}) <- L.toList signed]
newEdit :: Records -> TVar Bool -> EditRequest -> Address -> ByteString -> IO EditAnswer
newEdit rs timer req signer bodyHash =
chainAccepts rs req signer >>= \case
Left _ -> pure EAUnavailable
Right False -> pure EARefused
Right True ->
insertEdit rs req signer bodyHash >>= \case
Left answer -> pure answer
Right (Just editId) -> sendNew rs timer editId
-- a pending or mined edit holds the nonce: the identical twin is waited for, any other body refused
Right Nothing -> withStore rs (`getRecordEditByBody` bodyHash) >>= maybe (pure EARefused) (awaitEdit rs timer . reId)
-- | The earliest deadline after the latest block's time, the signer the registry's owner on the default resolver, the first nonce the owner's next.
chainAccepts :: Records -> EditRequest -> Address -> IO (Either ChainError Bool)
chainAccepts Records {rsChain, rsContracts} EditRequest {erLabelHash, erChanges} signer = runExceptT $ do
Block {blockTimestamp} <- ExceptT $ latestBlock rsChain
if earliestDeadline erChanges <= blockTimestamp
then pure False
else
ExceptT (nameStatus rsContracts erLabelHash) >>= \case
NSRegistered RegisteredName {rnOwner, rnResolver}
| rnOwner == signer && rnResolver == cResolver (ccConfig rsChain) -> (== firstNonce erChanges) <$> ExceptT (resolverNonce rsContracts signer)
_ -> pure False
-- | Left when the name's yearly limit or hourly cap is used up, checked again under the name's turn against a concurrent edit.
-- Right Nothing when a pending or mined edit holds the first nonce.
insertEdit :: Records -> EditRequest -> Address -> ByteString -> IO (Either EditAnswer (Maybe Int64))
insertEdit Records {rsStore, rsTurns, rsEditsPerYear, rsNow} EditRequest {erLabelHash, erChanges} signer bodyHash =
withLabelTurn rsTurns erLabelHash $ do
now <- rsNow
withTransaction rsStore $ \db -> do
limited <- usedUpUntil <$> nameEditsLeft db rsEditsPerYear erLabelHash now
times <- relayedEditTimes db erLabelHash (addUTCTime (negate editCapWindow) now)
let relayed = length times
case limited of
Just nextAt -> pure $ Left $ EALimited nextAt
Nothing
| relayed >= editCap -> pure $ Left $ EACapped $ max 1 $ ceiling $ diffUTCTime (addUTCTime editCapWindow $ times !! (relayed - editCap)) now
| otherwise -> Right <$> insertRecordEdit db edit now
where
edit = NewRecordEdit {nreLabelHash = erLabelHash, nreOwner = signer, nreChanges = erChanges, nreBodyHash = bodyHash}
-- | An edit that was not sent is answered and deleted while still claimed, so the lane cannot send it after.
sendNew :: Records -> TVar Bool -> Int64 -> IO EditAnswer
sendNew rs timer editId =
withClaim rs editId Nothing (withStore rs (`getRecordEdit` editId) >>= maybe (pure Nothing) send) >>= maybe (awaitEdit rs timer editId) pure
where
send edit =
sendEdit rs edit >>= \case
Right () -> pure Nothing
Left e -> do
answer <- case e of
SEChain (ChainReverted name) -> either (const EAUnavailable) (dryRunAnswer name) <$> judge rs edit
_ -> EAUnavailable <$ logWarn ("names records: edit " <> tshow editId <> " not sent: " <> tshow e)
Just answer <$ forget rs editId
-- anyone can relay a signed edit, so a revert may mean another relayer applied it
dryRunAnswer name = \case
Applied tx -> EAApplied tx
NonceTaken -> EAReverted $ revertText RNInvalidNonce
NonceFree -> EAReverted $ revertText =<< name
-- | Left when nothing was sent: the dry run reverted or the chain failed.
sendEdit :: Records -> RecordEdit -> IO (Either SendError ())
sendEdit rs@Records {rsSender} edit@RecordEdit {reId} =
submitTransaction rsSender (TxEdit reId) (resolver rs) (editCalldata rs edit) >>= \case
Right _ -> Right () <$ unstall rs reId
Left SEInFlight -> pure $ Right ()
Left e -> pure $ Left e
-- | Only sent edits are stored, so one never sent leaves no row and its repeat is checked anew.
forget :: Records -> Int64 -> IO ()
forget rs editId = withStore rs (`deleteUnsentEdit` editId) >> settled rs editId
-- | Waits until the edit settles, the chain stops answering for it, or the timer fires.
awaitEdit :: Records -> TVar Bool -> Int64 -> IO EditAnswer
awaitEdit rs@Records {rsChanges, rsStalled} timer editId = loop
where
loop = do
-- read before the row, so a change committed after the read still wakes this request
seen <- readTVarIO rsChanges
withStore rs (`getRecordEdit` editId) >>= \case
Nothing -> pure EAUnavailable
Just RecordEdit {reState = ESMined tx} -> pure $ EAApplied tx
Just RecordEdit {reState = ESReverted revert} -> pure $ EAReverted revert
Just RecordEdit {reState = ESPending} -> do
stalled <- S.member editId <$> readTVarIO rsStalled
if stalled
then pure EAPending
else do
changed <- atomically $ (True <$ (readTVar rsChanges >>= check . (/= seen))) `orElse` (False <$ (readTVar timer >>= check))
if changed then loop else pure EAPending
runRecordEdits :: Records -> IO ()
runRecordEdits rs = forever $ recordsRound rs >> threadDelay recordsInterval
-- | One pass over the pending edits that no request is sending. A pass or an edit that fails is logged, and the lane goes on.
recordsRound :: Records -> IO ()
recordsRound rs@Records {rsChain} = void $ safely "names records: the round" $ do
editIds <- withStore rs pendingEditIds
unless (null editIds) $
runExceptT (ExceptT (latestBlock rsChain) >>= \tip -> (tip,) <$> ExceptT (deepBlock rsChain tip)) >>= \case
Left e -> mapM_ (\editId -> stall rs editId e) editIds
-- each edit on its own, so a row that fails stops no other edit
Right (tip, deep) -> forM_ editIds $ \editId ->
safely ("names records: edit " <> tshow editId) $ withClaim rs editId () $ withStore rs (`getRecordEdit` editId) >>= mapM_ (follow rs tip deep)
-- | The newest block at the configured confirmation depth, as the sender counts it.
deepBlock :: ChainClient -> Block -> IO (Either ChainError Block)
deepBlock c tip@Block {blockNumber}
| deep == blockNumber = pure $ Right tip
| otherwise = blockAt c deep
where
deep = confirmedNumber c blockNumber
-- | One step for a pending edit, from its transactions' statuses as the sender settled them.
follow :: Records -> Block -> Block -> RecordEdit -> IO ()
follow rs@Records {rsChain} Block {blockTimestamp} Block {blockTimestamp = deepTime} edit@RecordEdit {reId, reChanges} = do
txs <- withStore rs (`editTransactions` reId)
case txs of
[] -> if ahead then sendUnsent else forget rs reId
_
| mined : _ <- [ntHash | NameTransaction {ntHash, ntStatus = TSMined} <- txs] -> settle rs reId $ ESMined $ Just mined
| any ((== TSPending) . ntStatus) txs -> if deepTime > reDeadline then expire else unstall rs reId
-- a mined revert carries no data: past the deadline it is SignatureExpired, else unnamed
| block : _ <- [b | NameTransaction {ntStatus = TSReverted, ntMinedBlock = Just b} <- txs] ->
blockAt rsChain block >>= \case
Left e -> stall rs reId e
Right Block {blockTimestamp = minedTime} -> judged rs edit $ settle rs reId $ ESReverted $ if minedTime > reDeadline then signatureExpired else Nothing
-- every transaction dropped: its registrar nonce went to another one
| otherwise -> judged rs edit $ if ahead then resend else expire
where
reDeadline = earliestDeadline reChanges
ahead = reDeadline > blockTimestamp
expire = judged rs edit $ settle rs reId $ ESReverted signatureExpired
sendUnsent =
sendEdit rs edit >>= \case
Left (SEChain (ChainReverted _)) -> forget rs reId
r -> either (stall rs reId) pure r
-- the edit was sent before, so its dry run's revert is its outcome
resend =
sendEdit rs edit >>= \case
Left (SEChain (ChainReverted name)) -> settle rs reId $ ESReverted $ revertText =<< name
r -> either (stall rs reId) pure r
-- | Settles the edit as the chain shows it, or runs the action when its nonce is still free.
judged :: Records -> RecordEdit -> IO () -> IO ()
judged rs edit@RecordEdit {reId} whenFree =
judge rs edit >>= \case
Left e -> stall rs reId e
Right (Applied tx) -> settle rs reId $ ESMined tx
Right NonceTaken -> settle rs reId $ ESReverted $ revertText RNInvalidNonce
Right NonceFree -> whenFree
-- | Its own transactions first: a status-1 receipt answers its hash. Without one, the owner's nonce and the records.
-- A nonce past the first change but not the last means another body took one of its nonces.
judge :: Records -> RecordEdit -> IO (Either ChainError Judgment)
judge rs@Records {rsChain, rsContracts} RecordEdit {reId, reLabelHash, reOwner, reChanges} = runExceptT $ do
txs <- liftIO $ withStore rs (`editTransactions` reId)
receipts <- forM txs $ \NameTransaction {ntHash} -> (ntHash,) <$> ExceptT (transactionReceipt rsChain ntHash)
case [h | (h, Just Receipt {receiptSuccess = True}) <- receipts] of
h : _ -> pure $ Applied $ Just h
[] -> do
nonce <- ExceptT $ resolverNonce rsContracts reOwner
if
| nonce <= firstNonce reChanges -> pure NonceFree
| nonce <= lastNonce reChanges -> pure NonceTaken
| otherwise -> do
holds <- and <$> mapM (holdsChange . scChange) reChanges
pure $ if holds then Applied Nothing else NonceTaken
where
holdsChange = \case
RCSetText key value -> (== value) <$> record (encodeUtf8 key)
RCClear -> (&&) <$> (unset <$> record contactRecordKey) <*> (unset <$> record channelRecordKey)
record = ExceptT . textRecord rsContracts reLabelHash
unset = (== "")
settle :: Records -> Int64 -> EditState -> IO ()
settle rs editId state = do
void $ withStore rs $ \db -> settleRecordEdit db editId state
settled rs editId
-- | Wakes the requests waiting for the edit, which read it again.
settled :: Records -> Int64 -> IO ()
settled Records {rsStalled, rsChanges} editId = atomically $ modifyTVar' rsStalled (S.delete editId) >> modifyTVar' rsChanges (+ 1)
-- | Logged once until the edit's next successful step.
stall :: Show e => Records -> Int64 -> e -> IO ()
stall Records {rsStalled, rsChanges} editId e = do
new <- atomically $ do
stalled <- readTVar rsStalled
let new = not $ S.member editId stalled
when new $ writeTVar rsStalled (S.insert editId stalled) >> modifyTVar' rsChanges (+ 1)
pure new
when new $ logWarn $ "names records: edit " <> tshow editId <> " waits for the chain: " <> tshow e
unstall :: Records -> Int64 -> IO ()
unstall Records {rsStalled} editId = atomically $ modifyTVar' rsStalled $ S.delete editId
-- | Runs the action only when nobody else holds the edit, else answers the fallback.
withClaim :: Records -> Int64 -> a -> IO a -> IO a
withClaim Records {rsClaimed} editId fallback action =
bracket claim (\claimed -> when claimed release) $ \claimed -> if claimed then action else pure fallback
where
claim = atomically $ do
held <- readTVar rsClaimed
if S.member editId held then pure False else True <$ writeTVar rsClaimed (S.insert editId held)
release = atomically $ modifyTVar' rsClaimed $ S.delete editId
changeDigest :: Records -> LabelHash -> SignedChange -> ByteString
changeDigest rs lh SignedChange {scChange, scNonce, scDeadline} = case scChange of
RCSetText key value -> setTextDigest (domain rs) node key value scNonce scDeadline
RCClear -> clearRecordsDigest (domain rs) node scNonce scDeadline
where
node = nodeOf rs lh
-- | One change is sent as its own call, which keeps the revert's name; two go in one multicall.
editCalldata :: Records -> RecordEdit -> ByteString
editCalldata rs RecordEdit {reLabelHash, reChanges} = case reChanges of
change :| [] -> changeCalldata change
_ -> multicallCalldata $ map changeCalldata $ L.toList reChanges
where
node = nodeOf rs reLabelHash
changeCalldata SignedChange {scChange, scNonce, scDeadline, scSignature} = case scChange of
RCSetText key value -> setTextWithSigCalldata node key value scNonce scDeadline scSignature
RCClear -> clearRecordsWithSigCalldata node scNonce scDeadline scSignature
firstNonce, lastNonce :: NonEmpty SignedChange -> Word64
firstNonce = scNonce . L.head
lastNonce = scNonce . L.last
-- | Past it the edit cannot land whole, so it is SignatureExpired.
earliestDeadline :: NonEmpty SignedChange -> Word64
earliestDeadline = minimum . L.map scDeadline
nodeOf :: Records -> LabelHash -> Node
nodeOf Records {rsTLD} = labelNode rsTLD
domain :: Records -> Eip712Domain
domain rs@Records {rsChain} = resolverDomain (cChainId $ ccConfig rsChain) (resolver rs)
resolver :: Records -> Address
resolver = cResolver . ccConfig . rsChain
signatureExpired :: Maybe Text
signatureExpired = revertText RNSignatureExpired
withStore :: Records -> (DB.Connection -> IO a) -> IO a
withStore Records {rsStore} = withTransaction rsStore
@@ -11,16 +11,23 @@ module StoreService.Names.Registration
contactRecordKey,
channelRecordKey,
sponsorDomain,
resolverDomain,
makeCommitment,
commitCalldata,
registerWithCreditCalldata,
registerIntentDigest,
verifyRegisterIntent,
setTextDigest,
clearRecordsDigest,
setTextWithSigCalldata,
clearRecordsWithSigCalldata,
multicallCalldata,
)
where
import Control.Monad (unless, when)
import Control.Monad.Except (ExceptT (..), runExceptT, throwError)
import Crypto.Number.Serialize (os2ip)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.Maybe (catMaybes)
@@ -66,6 +73,9 @@ data RegisterIntent = RegisterIntent
sponsorDomain :: Word64 -> Address -> Eip712Domain
sponsorDomain edChainId edVerifyingContract = Eip712Domain {edName = "SimplexSponsor", edVersion = "1", edChainId, edVerifyingContract}
resolverDomain :: Word64 -> Address -> Eip712Domain
resolverDomain edChainId edVerifyingContract = Eip712Domain {edName = "SimplexResolver", edVersion = "1", edChainId, edVerifyingContract}
makeCommitment :: Registration -> ByteString
makeCommitment r = keccak256 $ abiTuple [Dynamic $ registrationTuple r]
@@ -103,6 +113,44 @@ verifyRegisterIntent domain now RegisterIntent {riRegistration = r@Registration
signer <- ExceptT $ recoverAddress riSignature $ registerIntentDigest domain r riNonce riDeadline
unless (signer == rOwner) $ throwError "intent is not signed by the owner"
setTextDigest :: Eip712Domain -> Node -> Text -> Text -> Word64 -> Word64 -> ByteString
setTextDigest domain node key value nonce deadline =
hashTypedData
domain
"SetText(bytes32 node,string key,string value,uint256 nonce,uint256 deadline)"
[bytes32 node, VBytes $ encodeUtf8 key, VBytes $ encodeUtf8 value, VUint $ fromIntegral nonce, VUint $ fromIntegral deadline]
clearRecordsDigest :: Eip712Domain -> Node -> Word64 -> Word64 -> ByteString
clearRecordsDigest domain node nonce deadline =
hashTypedData
domain
"ClearRecords(bytes32 node,uint256 nonce,uint256 deadline)"
[bytes32 node, VUint $ fromIntegral nonce, VUint $ fromIntegral deadline]
setTextWithSigCalldata :: Node -> Text -> Text -> Word64 -> Word64 -> RecoverableSignature -> ByteString
setTextWithSigCalldata (Node node) key value nonce deadline sig =
selector "setTextWithSig(bytes32,string,string,uint256,uint256,bytes)"
<> abiTuple
[ Static node,
Dynamic $ abiBytes $ encodeUtf8 key,
Dynamic $ abiBytes $ encodeUtf8 value,
Static $ uint256 nonce,
Static $ uint256 deadline,
Dynamic $ abiBytes $ serializeSignature sig
]
clearRecordsWithSigCalldata :: Node -> Word64 -> Word64 -> RecoverableSignature -> ByteString
clearRecordsWithSigCalldata (Node node) nonce deadline sig =
selector "clearRecordsWithSig(bytes32,uint256,uint256,bytes)"
<> abiTuple [Static node, Static $ uint256 nonce, Static $ uint256 deadline, Dynamic $ abiBytes $ serializeSignature sig]
-- | The resolver runs each call on itself in order, and reverts all of them when one fails.
multicallCalldata :: [ByteString] -> ByteString
multicallCalldata calls = selector "multicall(bytes[])" <> abiTuple [Dynamic $ abiArray $ map abiBytes calls]
bytes32 :: Node -> Eip712Value
bytes32 (Node node) = VUint $ fromInteger $ os2ip node
registrationTuple :: Registration -> ByteString
registrationTuple r@Registration {rLabel, rOwner, rDuration, rSecret, rResolver} =
abiTuple
@@ -1,12 +1,15 @@
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
module StoreService.Names.Revert (RevertName (..), decodeRevert) where
module StoreService.Names.Revert (RevertName (..), decodeRevert, revertText) where
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as BC
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import Data.Text (Text)
import Data.Text.Encoding (decodeLatin1)
import StoreService.Names.Abi (selector)
-- | The custom errors of SimplexController, SimplexSponsor, BaseRegistrarImplementation and SimplexResolver.
@@ -107,6 +110,10 @@ revertSignature = \case
RNZeroAddress -> Just "ZeroAddress()"
RNWithoutData -> Nothing
-- | The error's name as the contracts declare it, Nothing for a revert without data.
revertText :: RevertName -> Maybe Text
revertText = fmap (decodeLatin1 . BC.takeWhile (/= '(')) . revertSignature
revertSelectors :: Map ByteString RevertName
revertSelectors = M.fromList [(selector signature, n) | n <- [minBound .. maxBound], Just signature <- [revertSignature n]]
@@ -33,6 +33,11 @@ module StoreService.Names.Store
TxStatus (..),
NameTransaction (..),
NewTransaction (..),
RecordChange (..),
SignedChange (..),
EditState (..),
RecordEdit (..),
NewRecordEdit (..),
findLimit,
orderHash,
orderLive,
@@ -47,6 +52,7 @@ module StoreService.Names.Store
getLiveOrders,
closeOverdue,
updateRegistration,
retargetRegistration,
findRegistrations,
isLabelRegistering,
activeRegistrations,
@@ -82,6 +88,16 @@ module StoreService.Names.Store
recordTransactionOutcome,
pendingTransactions,
registrationTransactions,
editTransactions,
insertRecordEdit,
getRecordEdit,
getRecordEditByBody,
getRecordEditByNonce,
settleRecordEdit,
pendingEditIds,
deleteUnsentEdit,
relayedEditTimes,
countedEditTimes,
)
where
@@ -92,6 +108,8 @@ import Data.ByteArray.Encoding (Base (Base16), convertToBase)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.Int (Int64)
import Data.List.NonEmpty (NonEmpty (..))
import qualified Data.List.NonEmpty as L
import Data.Maybe (isJust, listToMaybe)
import Data.String (fromString)
import Data.Text (Text)
@@ -387,7 +405,7 @@ data NewPrepaidCode = NewPrepaidCode
data CodeHashTaken = CodeHashTaken
deriving (Eq, Show)
data TxFor = TxCommit RegistrationId | TxRegister RegistrationId
data TxFor = TxCommit RegistrationId | TxRegister RegistrationId | TxEdit Int64
deriving (Eq, Show)
-- | A dropped transaction has no receipt and its registrar nonce is used.
@@ -424,6 +442,41 @@ data NewTransaction = NewTransaction
ntxNonce :: Word64
}
-- | A text record set to a value, "" removing it, or every record cleared.
data RecordChange = RCSetText Text Text | RCClear
deriving (Eq, Show)
data EditState = ESPending | ESMined (Maybe TxHash) | ESReverted (Maybe Text)
deriving (Eq, Show)
-- | A change the owner signed for the resolver's nonce it names.
data SignedChange = SignedChange
{ scChange :: RecordChange,
scNonce :: Word64,
scDeadline :: Word64,
scSignature :: RecoverableSignature
}
deriving (Eq, Show)
-- | One request's changes, relayed in one transaction, their nonces consecutive in this order.
data RecordEdit = RecordEdit
{ reId :: Int64,
reLabelHash :: LabelHash,
reOwner :: Address,
reChanges :: NonEmpty SignedChange,
reBodyHash :: ByteString,
reState :: EditState,
reCreatedAt :: UTCTime
}
deriving (Eq, Show)
data NewRecordEdit = NewRecordEdit
{ nreLabelHash :: LabelHash,
nreOwner :: Address,
nreChanges :: NonEmpty SignedChange,
nreBodyHash :: ByteString
}
findLimit :: Int
findLimit = 50
@@ -725,6 +778,34 @@ updateRegistration db r now = do
[(version, BI storedLive)] | version == nrVersion -> pure $ if storedLive then LiveOrderExists else NotLive
_ -> pure VersionChanged
-- | Another name, or other links, with the terms agreed for it: queued again with the reveal, transactions, reveal times and link refusal cleared.
-- The order hash stays the original order's, so a resend of that order still finds it.
retargetRegistration :: DB.Connection -> NameRegistration -> OrderFields -> Int -> UTCTime -> IO VersionWrite
retargetRegistration db r OrderFields {ofLabelHash, ofLength, ofDuration, ofCommitment, ofSealed, ofAgreedTerms} price =
updateRegistration
db
r
{ nrLabelHash = ofLabelHash,
nrLength = ofLength,
nrDuration = ofDuration,
nrCommitment = ofCommitment,
nrSealed = ofSealed,
nrAgreedTerms = ofAgreedTerms,
nrPrice = price,
nrPhase = PQueued,
nrMoves = nrMoves r + 1,
nrReveal = Nothing,
nrCommitTx = Nothing,
nrCommitBlock = Nothing,
nrRegisterTx = Nothing,
nrRegisterBlock = Nothing,
nrRevealAfter = Nothing,
nrRevealBefore = Nothing,
nrLinksRefusedAt = Nothing,
nrFailedAt = Nothing,
nrError = Nothing
}
-- | Newest first: findLimit of them, then every older one holding a balance above 0, since a balance never expires.
-- Each with the order holding its balance, as getBalance reads the hold at the given time.
findRegistrations :: DB.Connection -> Address -> UTCTime -> IO [(NameRegistration, Maybe RegistrationId)]
@@ -1269,23 +1350,24 @@ revokePrepaidCode db codeHash now = do
| isJust pcRevokedAt = AlreadyRevoked pcId
| otherwise = AlreadyRedeemed
txKind :: TxFor -> (Text, Text)
txKind :: TxFor -> (Text, Maybe Text, Maybe Int64)
txKind = \case
TxCommit (RegistrationId rid) -> ("commit", rid)
TxRegister (RegistrationId rid) -> ("register", rid)
TxCommit (RegistrationId rid) -> ("commit", Just rid, Nothing)
TxRegister (RegistrationId rid) -> ("register", Just rid, Nothing)
TxEdit editId -> ("edit", Nothing, Just editId)
-- | Saved once signed and before it is sent, so a restart can rebroadcast it.
insertTransaction :: DB.Connection -> TxFor -> NewTransaction -> UTCTime -> IO Int64
insertTransaction db for NewTransaction {ntxRaw, ntxHash, ntxNonce} now = do
let (kind, rid) = txKind for
let (kind, rid, editId) = txKind for
DB.execute
db
[sql|
INSERT INTO sx_badge_service_name_transactions
(registration_id, kind, raw, tx_hash, registrar_nonce, sent_at, status)
VALUES (?,?,?,?,?,?,?)
(registration_id, name_record_edit_id, kind, raw, tx_hash, registrar_nonce, sent_at, status)
VALUES (?,?,?,?,?,?,?,?)
|]
(rid, kind, Binary ntxRaw, txHashField ntxHash, int64 ntxNonce, truncateToSecond now, TSPending)
(rid, editId, kind, Binary ntxRaw, txHashField ntxHash, int64 ntxNonce, truncateToSecond now, TSPending)
insertedRowId db
-- | Moves a transaction on from the status the caller read, so an outcome is never overwritten unseen; False when it is not in that status.
@@ -1300,17 +1382,18 @@ recordTransactionOutcome db hash from status block =
transactionColumns :: Query
transactionColumns =
[sql|
SELECT name_transaction_id, kind, registration_id, raw, tx_hash, registrar_nonce, sent_at, mined_block, status
SELECT name_transaction_id, kind, registration_id, name_record_edit_id, raw, tx_hash, registrar_nonce, sent_at, mined_block, status
FROM sx_badge_service_name_transactions
|]
type TransactionRow = (Int64, Text, Maybe Text, Binary ByteString, Binary ByteString, Int64, UTCTime, Maybe Int64, TxStatus)
type TransactionRow = (Int64, Text, Maybe Text, Maybe Int64, Binary ByteString, Binary ByteString, Int64, UTCTime, Maybe Int64, TxStatus)
toTransaction :: TransactionRow -> Either Text NameTransaction
toTransaction (ntId, kind, rid_, Binary ntRaw, hash, nonce, ntSentAt, block, ntStatus) = do
ntFor <- case (kind, rid_) of
("commit", Just rid) -> Right $ TxCommit $ RegistrationId rid
("register", Just rid) -> Right $ TxRegister $ RegistrationId rid
toTransaction (ntId, kind, rid_, editId_, Binary ntRaw, hash, nonce, ntSentAt, block, ntStatus) = do
ntFor <- case (kind, rid_, editId_) of
("commit", Just rid, Nothing) -> Right $ TxCommit $ RegistrationId rid
("register", Just rid, Nothing) -> Right $ TxRegister $ RegistrationId rid
("edit", Nothing, Just editId) -> Right $ TxEdit editId
_ -> Left $ "name_transactions.kind: " <> kind
pure NameTransaction {ntId, ntFor, ntRaw, ntHash = txHash hash, ntNonce = word64 nonce, ntSentAt, ntMinedBlock = word64 <$> block, ntStatus}
@@ -1325,6 +1408,152 @@ registrationTransactions db (RegistrationId rid) =
DB.query db (transactionColumns <> " WHERE registration_id = ? ORDER BY name_transaction_id") (Only rid)
>>= decodeAll toTransaction
editTransactions :: DB.Connection -> Int64 -> IO [NameTransaction]
editTransactions db editId =
DB.query db (transactionColumns <> " WHERE name_record_edit_id = ? ORDER BY name_transaction_id") (Only editId)
>>= decodeAll toTransaction
pendingEdit :: Text
pendingEdit = "pending"
minedEdit :: Text
minedEdit = "mined"
revertedEdit :: Text
revertedEdit = "reverted"
-- | Nothing when a pending or mined edit already starts at the owner's first nonce.
insertRecordEdit :: DB.Connection -> NewRecordEdit -> UTCTime -> IO (Maybe Int64)
insertRecordEdit db NewRecordEdit {nreLabelHash = LabelHash lh, nreOwner, nreChanges, nreBodyHash} now = do
inserted <-
executeChanging
db
[sql|
INSERT INTO sx_badge_service_name_record_edits (label_hash, owner, nonce, body_hash, state, created_at)
VALUES (?,?,?,?,?,?)
ON CONFLICT DO NOTHING
|]
(Binary lh, Binary $ unAddress nreOwner, int64 $ scNonce $ L.head nreChanges, Binary nreBodyHash, pendingEdit, truncateToSecond now)
if inserted > 0
then do
editId <- insertedRowId db
mapM_ (insertChange editId) nreChanges
pure $ Just editId
else pure Nothing
where
insertChange editId SignedChange {scChange, scNonce, scDeadline, scSignature} =
DB.execute
db
"INSERT INTO sx_badge_service_name_record_changes (name_record_edit_id, nonce, record_key, record_value, deadline, signature) VALUES (?,?,?,?,?,?)"
(editId, int64 scNonce, key, value, int64 scDeadline, Binary $ serializeSignature scSignature)
where
(key, value) = case scChange of
RCSetText k v -> (Just k, Just v)
RCClear -> (Nothing, Nothing)
recordEditColumns :: Query
recordEditColumns =
[sql|
SELECT name_record_edit_id, label_hash, owner, body_hash, state, revert, mined_tx, created_at
FROM sx_badge_service_name_record_edits
|]
type RecordEditRow = (Int64, Binary ByteString, Binary ByteString, Binary ByteString, Text, Maybe Text, Maybe (Binary ByteString), UTCTime)
type ChangeRow = (Int64, Maybe Text, Maybe Text, Int64, Binary ByteString)
-- | An edit's row with its changes, in nonce order.
readRecordEdit :: DB.Connection -> RecordEditRow -> IO RecordEdit
readRecordEdit db row@(reId, _, _, _, _, _, _, _) = do
changes <- DB.query db "SELECT nonce, record_key, record_value, deadline, signature FROM sx_badge_service_name_record_changes WHERE name_record_edit_id = ? ORDER BY nonce" (Only reId)
either (E.throwIO . StoreDecodeError) pure $ toRecordEdit row changes
toRecordEdit :: RecordEditRow -> [ChangeRow] -> Either Text RecordEdit
toRecordEdit (reId, Binary lh, Binary owner, Binary reBodyHash, state, revert, minedTx, reCreatedAt) changeRows = do
reOwner <- decodeAddress owner
reChanges <- note ("name_record_edits changes: " <> tshow reId) . L.nonEmpty =<< mapM toChange changeRows
reState <- decodeState
pure RecordEdit {reId, reLabelHash = LabelHash lh, reOwner, reChanges, reBodyHash, reState, reCreatedAt}
where
toChange (nonce, key_, value_, deadline, Binary sig) = do
scSignature <- decodeSignature sig
scChange <- case (key_, value_) of
(Just key, Just value) -> Right $ RCSetText key value
(Nothing, Nothing) -> Right RCClear
_ -> Left $ "name_record_changes record: " <> tshow reId
pure SignedChange {scChange, scNonce = word64 nonce, scDeadline = word64 deadline, scSignature}
decodeState
| state == pendingEdit = Right ESPending
| state == minedEdit = Right $ ESMined $ txHash <$> minedTx
| state == revertedEdit = Right $ ESReverted revert
| otherwise = Left $ "name_record_edits.state: " <> state
firstRecordEdit :: DB.Connection -> IO [RecordEditRow] -> IO (Maybe RecordEdit)
firstRecordEdit db rows = rows >>= mapM (readRecordEdit db) . listToMaybe
getRecordEdit :: DB.Connection -> Int64 -> IO (Maybe RecordEdit)
getRecordEdit db editId =
firstRecordEdit db $ DB.query db (recordEditColumns <> " WHERE name_record_edit_id = ?") (Only editId)
-- | The newest edit sent with this signed body.
getRecordEditByBody :: DB.Connection -> ByteString -> IO (Maybe RecordEdit)
getRecordEditByBody db bodyHash =
firstRecordEdit db $
DB.query db (recordEditColumns <> " WHERE body_hash = ? ORDER BY name_record_edit_id DESC LIMIT 1") (Only $ Binary bodyHash)
-- | The pending or mined edit holding the owner's nonce among its changes.
getRecordEditByNonce :: DB.Connection -> Address -> Word64 -> IO (Maybe RecordEdit)
getRecordEditByNonce db owner nonce =
firstRecordEdit db $
DB.query
db
( recordEditColumns
<> " WHERE owner = ? AND state IN (?,?) AND name_record_edit_id IN (SELECT name_record_edit_id FROM sx_badge_service_name_record_changes WHERE nonce = ?)"
)
(Binary $ unAddress owner, pendingEdit, minedEdit, int64 nonce)
-- | Settles a pending edit; False when it was settled already.
settleRecordEdit :: DB.Connection -> Int64 -> EditState -> IO Bool
settleRecordEdit db editId state =
(> 0)
<$> executeChanging
db
"UPDATE sx_badge_service_name_record_edits SET state = ?, revert = ?, mined_tx = ? WHERE name_record_edit_id = ? AND state = ?"
(stateText, revert, txHashField <$> minedTx, editId, pendingEdit)
where
(stateText, revert, minedTx) = case state of
ESPending -> (pendingEdit, Nothing, Nothing)
ESMined tx -> (minedEdit, Nothing, tx)
ESReverted name -> (revertedEdit, name, Nothing)
pendingEditIds :: DB.Connection -> IO [Int64]
pendingEditIds db = map fromOnly <$> DB.query db "SELECT name_record_edit_id FROM sx_badge_service_name_record_edits WHERE state = ? ORDER BY name_record_edit_id" (Only pendingEdit)
deleteUnsentEdit :: DB.Connection -> Int64 -> IO ()
deleteUnsentEdit db editId =
DB.execute
db
"DELETE FROM sx_badge_service_name_record_edits WHERE name_record_edit_id = ? AND state = ? AND NOT EXISTS (SELECT 1 FROM sx_badge_service_name_transactions WHERE name_record_edit_id = ?)"
(editId, pendingEdit, editId)
-- | When each edit relayed for the name since the given time was sent, oldest first.
relayedEditTimes :: DB.Connection -> LabelHash -> UTCTime -> IO [UTCTime]
relayedEditTimes db (LabelHash lh) since =
map fromOnly
<$> DB.query
db
"SELECT created_at FROM sx_badge_service_name_record_edits WHERE label_hash = ? AND created_at > ? ORDER BY created_at"
(Binary lh, truncateToSecond since)
-- | When each pending or mined edit of the name was made since the given time, oldest first: the edits its yearly limit counts.
countedEditTimes :: DB.Connection -> LabelHash -> UTCTime -> IO [UTCTime]
countedEditTimes db (LabelHash lh) since =
map fromOnly
<$> DB.query
db
"SELECT created_at FROM sx_badge_service_name_record_edits WHERE label_hash = ? AND created_at > ? AND state IN (?,?) ORDER BY created_at"
(Binary lh, truncateToSecond since, pendingEdit, minedEdit)
int64 :: Word64 -> Int64
int64 = fromIntegral
@@ -45,6 +45,7 @@ import StoreService.Names.Codes (issueNameCode, revokeNameCode)
import StoreService.Names.Env (NamesEnv (..), newNamesEnv)
import StoreService.Names.Orders (ordersEnv)
import StoreService.Names.Phases (RegistrationId (..))
import StoreService.Names.Records (runRecordEdits)
import StoreService.Names.Sender (runSender)
import StoreService.Names.Store (Balance (..), BalanceHold (..), BalanceLink (..), LateCredit (..), RegistrationPayment (..), balanceByReference, balanceChain, methodText)
import StoreService.Names.Turns (Turns, newTurns)
@@ -266,9 +267,9 @@ startNames cc@ChatController {chatStore} turns waiters providers nc@NamesConfig
-- | The workers resume every registration in their phases, and the code sweep runs at the start and then daily.
namesLanes :: NamesEnv -> IO [IO ()]
namesLanes ne@NamesEnv {neChain, neSender} = do
namesLanes ne@NamesEnv {neChain, neSender, neRecords} = do
worker <- newWorker (ordersEnv ne) neChain neSender
pure [runSender neSender, runWorkers worker, runCodeSweep worker]
pure [runSender neSender, runRecordEdits neRecords, runWorkers worker, runCodeSweep worker]
seedServiceCatalog :: DBStore -> IO ()
seedServiceCatalog st = do
@@ -19,6 +19,8 @@ module StoreService.Web.Http
searchLimit,
previewLimit,
codeLimit,
findLimit,
recordsLimit,
holdMicros,
jsonResponse,
jsonError,
@@ -92,12 +94,14 @@ type Respond = Response -> IO ResponseReceived
holdMicros :: Int
holdMicros = 30 * 1000000
readLimit, createLimit, searchLimit, previewLimit, codeLimit :: Limit
readLimit, createLimit, searchLimit, previewLimit, codeLimit, findLimit, recordsLimit :: Limit
readLimit = Limit {lmName = "read", lmPerMinute = 60}
createLimit = Limit {lmName = "create", lmPerMinute = 5}
searchLimit = Limit {lmName = "search", lmPerMinute = 30}
previewLimit = Limit {lmName = "preview", lmPerMinute = 20}
codeLimit = Limit {lmName = "code", lmPerMinute = 10}
findLimit = Limit {lmName = "find", lmPerMinute = 5}
recordsLimit = Limit {lmName = "records", lmPerMinute = 10}
maxBodyBytes :: Int
maxBodyBytes = 8192
@@ -5,14 +5,17 @@
module StoreService.Web.Names (Route (..), namesRoutes, namesApp) where
import Data.Text (Text)
import Data.Time.Clock (getCurrentTime)
import Network.HTTP.Types (Method)
import Network.Wai (Request, ResponseReceived, pathInfo)
import StoreService.Config (ServiceConfig)
import StoreService.Names.Env (NamesEnv (..))
import StoreService.Names.Orders (ordersEnv)
import StoreService.Web.Http (HttpEnv, Limit, Respond, codeLimit, createLimit, holdMicros, limited, only, previewLimit, readLimit, searchLimit)
import StoreService.Web.Http (HttpEnv, Limit, Respond, codeLimit, createLimit, findLimit, holdMicros, limited, only, previewLimit, readLimit, recordsLimit, searchLimit)
import StoreService.Web.Names.Codes (codeCheckHandler)
import StoreService.Web.Names.Orders (codeOrderHandler, spendHandler)
import StoreService.Web.Names.Owner (findHandler, retargetHandler)
import StoreService.Web.Names.Records (recordsHandler)
import StoreService.Web.Names.Registration (registrationHandler, retryHandler, revealHandler)
import StoreService.Web.Names.Search (previewHandler, searchHandler)
@@ -23,13 +26,17 @@ data Route = Route
}
namesRoutes :: ServiceConfig -> NamesEnv -> [Text] -> Maybe Route
namesRoutes cfg env@NamesEnv {neConfig, neStore, neContracts, neProfiles, neWaiters, neProviders} = \case
namesRoutes cfg env@NamesEnv {neConfig, neStore, neContracts, neProfiles, neRecords, neWaiters, neProviders} = \case
["api", "name", "records"] -> Just Route {rMethod = "POST", rLimit = recordsLimit, rHandler = recordsHandler neRecords}
["api", "name", "register"] -> Just Route {rMethod = "POST", rLimit = codeLimit, rHandler = codeOrderHandler (ordersEnv env) neProviders neWaiters}
["api", "code", "check"] -> Just Route {rMethod = "POST", rLimit = codeLimit, rHandler = codeCheckHandler neStore}
["api", "link", "preview"] -> Just Route {rMethod = "POST", rLimit = previewLimit, rHandler = previewHandler neProfiles}
-- 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", "name", hash] -> Just Route {rMethod = "GET", rLimit = searchLimit, rHandler = searchHandler neConfig neStore neContracts neProfiles getCurrentTime hash}
-- above /api/registration/:id, which it would otherwise match
["api", "registration", "find"] -> Just Route {rMethod = "POST", rLimit = findLimit, rHandler = findHandler (ordersEnv env)}
["api", "registration", rid] -> Just Route {rMethod = "GET", rLimit = readLimit, rHandler = registrationHandler (ordersEnv env) holdMicros rid}
["api", "registration", rid, "name"] -> Just Route {rMethod = "POST", rLimit = createLimit, rHandler = retargetHandler (ordersEnv env) 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}
["api", "registration", rid, "spend"] -> Just Route {rMethod = "POST", rLimit = createLimit, rHandler = spendHandler (ordersEnv env) cfg neProviders neWaiters rid}
@@ -0,0 +1,94 @@
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
module StoreService.Web.Names.Records (EditInvalid (..), recordsHandler, editRequest, editsLeftJSON) where
import Control.Monad (forM_, unless)
import Data.Aeson ((.:), (.:?), (.=))
import qualified Data.Aeson as J
import qualified Data.Aeson.Types as JT
import Data.List (nub)
import qualified Data.List.NonEmpty as L
import Data.Maybe (isJust)
import Data.Text (Text)
import Data.Text.Encoding (decodeLatin1)
import Data.Time.Clock (UTCTime)
import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds)
import Data.Word (Word64)
import Network.HTTP.Types (status200, status409, status429, status504)
import Network.Wai (Request, Response, ResponseReceived)
import Simplex.Messaging.SimplexName (LabelHash (..))
import StoreService.Names.Abi (bytes32FromHex, hex)
import StoreService.Names.Chain (TxHash (..))
import StoreService.Names.Links (LinkKind (..), linkKindOf)
import StoreService.Names.Records (EditAnswer (..), EditRequest (..), EditsLeft (..), Records, relayEdit)
import StoreService.Names.Registration (channelRecordKey, contactRecordKey)
import StoreService.Names.Signatures (parseSignature)
import StoreService.Names.Store (RecordChange (..), SignedChange (..))
import StoreService.Web.Http (Respond, badRequest, invalidLink, jsonError, jsonResponse, nameBodyBytes, providerUnavailable, rateLimited, readBoundedBody)
data EditInvalid = EIBadRequest | EIInvalidLink
deriving (Eq, Show)
recordsHandler :: Records -> Request -> Respond -> IO ResponseReceived
recordsHandler rs req respond =
readBoundedBody nameBodyBytes req >>= \case
Just body | Just o <- J.decode body -> case editRequest o of
Right edit -> relayEdit rs edit >>= respond . editResponse
Left EIInvalidLink -> respond invalidLink
Left EIBadRequest -> respond badRequest
_ -> respond badRequest
-- | An edit as sent, before its key, link and signature are checked.
data SentEdit = SentEdit {seChange :: Maybe (Text, Text), seNonce :: Word64, seDeadline :: Word64, seSignature :: Text}
-- | One link of each kind, so a Save of both links is the most one request carries.
maxEdits :: Int
maxEdits = 2
-- | Every edit's format and key, then every link, then every signature's format and low s, as the page's checks run.
editRequest :: J.Object -> Either EditInvalid EditRequest
editRequest o = do
(labelHash, edits) <- maybe (Left EIBadRequest) Right $ JT.parseMaybe fields o
erLabelHash <- maybe (Left EIBadRequest) (Right . LabelHash) $ bytes32FromHex labelHash
sent <- maybe (Left EIBadRequest) Right $ L.nonEmpty edits
unless (length edits <= maxEdits && keysOnce edits && clearAlone edits && consecutive edits) $ Left EIBadRequest
links <- mapM (\SentEdit {seChange} -> mapM linkOf seChange) sent
forM_ links $ mapM_ $ \(kind, value) -> unless (value == "" || linkKindOf value == Just kind) $ Left EIInvalidLink
erChanges <- mapM signedChange sent
pure EditRequest {erLabelHash, erChanges}
where
fields v = (,) <$> v .: "labelHash" <*> (v .: "edits" >>= mapM (J.withObject "edit" sentEdit))
sentEdit v = do
clear <- v .:? "clear"
seChange <- if clear == Just True then pure Nothing else Just <$> ((,) <$> v .: "key" <*> v .: "value")
SentEdit seChange <$> v .: "nonce" <*> v .: "deadline" <*> v .: "signature"
keysOnce edits = let keys = [k | SentEdit {seChange = Just (k, _)} <- edits] in length keys == length (nub keys)
clearAlone edits = length edits == 1 || all (isJust . seChange) edits
consecutive edits = and $ zipWith (\a b -> seNonce b == seNonce a + 1) edits (drop 1 edits)
linkOf (key, value) = maybe (Left EIBadRequest) (Right . (,value)) $ lookup key recordKinds
signedChange SentEdit {seChange, seNonce, seDeadline, seSignature} = do
scSignature <- either (const $ Left EIBadRequest) Right $ parseSignature seSignature
pure SignedChange {scChange = maybe RCClear (uncurry RCSetText) seChange, scNonce = seNonce, scDeadline = seDeadline, scSignature}
recordKinds :: [(Text, LinkKind)]
recordKinds = [(decodeLatin1 contactRecordKey, LKContact), (decodeLatin1 channelRecordKey, LKChannel)]
editResponse :: EditAnswer -> Response
editResponse = \case
EAApplied tx -> jsonResponse status200 $ J.object ["tx" .= ((\(TxHash h) -> hex h) <$> tx)]
EAReverted revert -> jsonResponse status409 $ J.object ["error" .= ("record_reverted" :: Text), "revert" .= revert]
EAPending -> jsonError status504 "edit_pending"
EARefused -> badRequest
EAUnavailable -> providerUnavailable
EACapped seconds -> rateLimited seconds
EALimited nextAt -> jsonResponse status429 $ J.object ["error" .= ("edit_limit" :: Text), "nextAt" .= unixSeconds nextAt]
-- | The search answer's recordEdits.
editsLeftJSON :: EditsLeft -> J.Value
editsLeftJSON EditsLeft {elLeft, elNextAt} = J.object ["left" .= elLeft, "nextAt" .= (unixSeconds <$> elNextAt)]
unixSeconds :: UTCTime -> Integer
unixSeconds = floor . utcTimeToPOSIXSeconds
@@ -15,6 +15,7 @@ import qualified Data.Aeson.Types as JT
import qualified Data.ByteString.Char8 as B
import Data.Char (isDigit)
import Data.Text (Text)
import Data.Time.Clock (UTCTime)
import qualified Data.Text as T
import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds)
import Network.HTTP.Types (status200)
@@ -30,9 +31,11 @@ import StoreService.Names.Community (communityJSON, termsJSON)
import StoreService.Names.Contracts
import StoreService.Names.Links (LinkKind (..), linkKindOf)
import StoreService.Names.Profiles (Entity, Profiles, linkEntity, linkPreview)
import StoreService.Names.Records (nameEditsLeft)
import StoreService.Names.Store (isLabelRegistering)
import StoreService.Names.View (addressText, tldText)
import StoreService.Web.Http (Respond, badRequest, invalidLink, invalidName, jsonResponse, maxBodyBytes, providerUnavailable, readBoundedBody)
import StoreService.Web.Names.Records (editsLeftJSON)
import System.Timeout (timeout)
import Text.Read (readMaybe)
@@ -44,15 +47,15 @@ data Found
| FRegistered RegisteredName (Maybe NameRecords)
-- | The chain reads of one search share one deadline, so a node that answers slowly fails the search once.
searchHandler :: NamesConfig -> DBStore -> Contracts -> Profiles -> Text -> Request -> Respond -> IO ResponseReceived
searchHandler cfg@NamesConfig {nYears} st ct ps hashText req respond = case LabelHash <$> bytes32FromHex hashText of
searchHandler :: NamesConfig -> DBStore -> Contracts -> Profiles -> IO UTCTime -> Text -> Request -> Respond -> IO ResponseReceived
searchHandler cfg@NamesConfig {nYears} st ct ps clock hashText req respond = case LabelHash <$> bytes32FromHex hashText of
Nothing -> respond badRequest
Just lh -> case queryLength req of
Nothing -> respond invalidName
Just len -> do
registering <- withTransaction st (`isLabelRegistering` lh)
timeout (ctDeadline ct) (runExceptT $ found lh len registering) >>= \case
Just (Right f) -> respond =<< searchAnswer cfg ps lh f
Just (Right f) -> respond =<< searchAnswer cfg st ps clock lh f
Just (Left e) -> unavailable $ tshow e
Nothing -> unavailable "timed out"
where
@@ -77,8 +80,8 @@ queryLength req = case join $ lookup "length" $ queryString req of
| n >= toInteger minNameLength && n <= toInteger maxNameLength = Just $ fromInteger n
| otherwise = Nothing
searchAnswer :: NamesConfig -> Profiles -> LabelHash -> Found -> IO Response
searchAnswer cfg@NamesConfig {nTLD, nYears, nTermStart, nChain = ChainConfig {cChainId, cResolver, cSponsor}} ps lh = \case
searchAnswer :: NamesConfig -> DBStore -> Profiles -> IO UTCTime -> LabelHash -> Found -> IO Response
searchAnswer cfg@NamesConfig {nTLD, nYears, nTermStart, nRecordEditsPerYear, nChain = ChainConfig {cChainId, cResolver, cSponsor}} st ps clock lh = \case
FAvailable price ->
ok $
["status" .= ("available" :: Text), "price" .= price, "currency" .= ("usd" :: Text), "years" .= nYears, "termStart" .= termStart]
@@ -89,9 +92,11 @@ searchAnswer cfg@NamesConfig {nTLD, nYears, nTermStart, nChain = ChainConfig {cC
FReserved -> ok ["status" .= ("reserved" :: Text)]
FRegistered RegisteredName {rnOwner, rnResolver, rnExpiresAt, rnGracePeriod} records_ -> do
entities <- maybe (pure []) (recordEntities ps) records_
-- only a name on the default resolver is edited here
edits <- mapM (const editsLeft) records_
ok $
["status" .= ("registered" :: Text), "entities" .= entities, "records" .= (recordsJSON <$> records_)]
<> ["owner" .= addressText rnOwner, "resolver" .= addressText rnResolver, "recordsNonce" .= (rdNonce <$> records_)]
<> ["owner" .= addressText rnOwner, "resolver" .= addressText rnResolver, "recordsNonce" .= (rdNonce <$> records_), "recordEdits" .= (editsLeftJSON <$> edits)]
<> ["expiresAt" .= rnExpiresAt, "gracePeriod" .= rnGracePeriod]
<> chain
where
@@ -100,6 +105,7 @@ searchAnswer cfg@NamesConfig {nTLD, nYears, nTermStart, nChain = ChainConfig {cC
chain = ["chainId" .= cChainId, "tld" .= tldText nTLD]
termStart = floor (utcTimeToPOSIXSeconds nTermStart) :: Integer
recordsJSON NameRecords {rdContact, rdChannel} = J.object ["contact" .= rdContact, "channel" .= rdChannel]
editsLeft = clock >>= \now -> withTransaction st $ \db -> nameEditsLeft db nRecordEditsPerYear lh now
-- | Contact entities first. A record may hold several links joined as the app joins them; a value that is not
-- a short link of its record's kind makes no entity, and neither does a link past the first few of its kind.
@@ -114,8 +114,13 @@ idle_seconds = 60
;term_slack_seconds = 3600
; a commitment with less than this left before its reveal deadline is not reused
;reveal_margin_seconds = 900
; how many times one order may move to another name
;max_order_moves = 3
; on: only prepaid codes register names, and every paid name order answers 403 codes_only
;codes_only = off
; the owner's link edits relayed for one name in any 365 days, each a transaction whose gas the
; service pays; 1 to 100. A request refused, never sent or reverted on chain does not count
;record_edits_per_year = 3
;
; community names, with [names] only: one line per name, `<label> = <what it is for>`, the label in
; lower case and listed once, the text 1 to 200 characters without a full stop at the end, which
@@ -100,8 +100,13 @@ private_key = replace-me
;term_slack_seconds = 3600
; a commitment with less than this left before its reveal deadline is not reused
;reveal_margin_seconds = 900
; how many times one order may move to another name
;max_order_moves = 3
; on: only prepaid codes register names, and every paid name order answers 403 codes_only
;codes_only = off
; the owner's link edits relayed for one name in any 365 days, each a transaction whose gas the
; service pays; 1 to 100. A request refused, never sent or reverted on chain does not count
;record_edits_per_year = 3
;
; community names, with [names] only: one line per name, `<label> = <what it is for>`, the label in
; lower case and listed once, the text 1 to 200 characters without a full stop at the end, which
+7
View File
@@ -465,6 +465,7 @@ executable simplex-store-service
StoreService.Names.Orders
StoreService.Names.Phases
StoreService.Names.Profiles
StoreService.Names.Records
StoreService.Names.Registration
StoreService.Names.Reveal
StoreService.Names.Revert
@@ -493,6 +494,8 @@ executable simplex-store-service
StoreService.Web.Names
StoreService.Web.Names.Codes
StoreService.Web.Names.Orders
StoreService.Web.Names.Owner
StoreService.Web.Names.Records
StoreService.Web.Names.Registration
StoreService.Web.Names.Search
StoreService.Web.Server
@@ -799,6 +802,7 @@ test-suite simplex-chat-test
Bots.StoreService.NamesOwnerTests
Bots.StoreService.NamesPhasesTests
Bots.StoreService.NamesProfilesTests
Bots.StoreService.NamesRecordsTests
Bots.StoreService.NamesRevealTests
Bots.StoreService.NamesSearchTests
Bots.StoreService.NamesSenderTests
@@ -842,6 +846,7 @@ test-suite simplex-chat-test
StoreService.Names.Orders
StoreService.Names.Phases
StoreService.Names.Profiles
StoreService.Names.Records
StoreService.Names.Registration
StoreService.Names.Reveal
StoreService.Names.Revert
@@ -870,6 +875,8 @@ test-suite simplex-chat-test
StoreService.Web.Names
StoreService.Web.Names.Codes
StoreService.Web.Names.Orders
StoreService.Web.Names.Owner
StoreService.Web.Names.Records
StoreService.Web.Names.Registration
StoreService.Web.Names.Search
StoreService.Web.Server
+18 -1
View File
@@ -12,12 +12,14 @@ module Bots.StoreService.FakeEthNode
answerCall,
answerCallOnce,
answerCallFrom,
forgetCall,
setFault,
clearFault,
releaseGate,
pausedAt,
setBlock,
setFees,
revertDryRun,
mine,
dropTransaction,
pruneReceipt,
@@ -102,6 +104,8 @@ data FakeState = FakeState
-- | the transactions the node knows and has not mined, by nonce
fsPool :: Map Word64 ByteString,
fsReceipts :: Map ByteString (Bool, Word64),
-- | the revert data of the dry runs of these calldata
fsDryRuns :: Map ByteString ByteString,
-- | the key's transaction count at the latest block
fsUsed :: Word64,
fsBlock :: (Word64, Word64),
@@ -147,6 +151,7 @@ withFakeEthNode action = do
fsSent = [],
fsPool = M.empty,
fsReceipts = M.empty,
fsDryRuns = M.empty,
fsUsed = 0,
fsBlock = (1, genesisTime),
fsBlockTimes = M.fromList [(0, genesisTime - blockSeconds), (1, genesisTime)],
@@ -183,6 +188,10 @@ answerCallOnce FakeEthNode {fnState} to calldata a = atomically $ modifyTVar' fn
answerCallFrom :: FakeEthNode -> Word64 -> Address -> ByteString -> CallAnswer -> IO ()
answerCallFrom FakeEthNode {fnState} block to calldata a = atomically $ modifyTVar' fnState $ \s -> s {fsCallsFrom = M.insert (unAddress to, calldata) (block, a) $ fsCallsFrom s}
-- | The call has no answer any more, as if the node failed it.
forgetCall :: FakeEthNode -> Address -> ByteString -> IO ()
forgetCall FakeEthNode {fnState} to calldata = atomically $ modifyTVar' fnState $ \s -> s {fsCalls = M.delete (unAddress to, calldata) $ fsCalls s}
-- | Every request for the method fails this way until 'clearFault'.
setFault :: FakeEthNode -> Text -> Fault -> IO ()
setFault FakeEthNode {fnState} method f = atomically $ modifyTVar' fnState $ \s -> s {fsFaults = M.insert method f $ fsFaults s}
@@ -221,6 +230,10 @@ revertFault = RpcError 3 "execution reverted" . Just
setBlock :: FakeEthNode -> Word64 -> Word64 -> IO ()
setBlock FakeEthNode {fnState} number time = atomically $ modifyTVar' fnState $ \s -> s {fsBlock = (number, time), fsBlockTimes = M.insert number time $ fsBlockTimes s}
-- | The dry run of this calldata reverts with this data, or passes again with Nothing.
revertDryRun :: FakeEthNode -> ByteString -> Maybe ByteString -> IO ()
revertDryRun FakeEthNode {fnState} calldata revertData = atomically $ modifyTVar' fnState $ \s -> s {fsDryRuns = M.alter (const revertData) calldata $ fsDryRuns s}
setFees :: FakeEthNode -> Word64 -> Word64 -> IO ()
setFees FakeEthNode {fnState} tip baseFee = atomically $ modifyTVar' fnState $ \s -> s {fsFees = (tip, baseFee)}
@@ -291,7 +304,7 @@ fakeApp st req respond = do
answer :: TVar FakeState -> Text -> [J.Value] -> STM [JT.Pair]
answer st method params = do
s@FakeState {fsCalls, fsCallsOnce, fsCallsFrom, fsSent, fsPool, fsReceipts, fsUsed, fsBlock = (number, time), fsBlockTimes, fsFees = (tip, baseFee)} <- readTVar st
s@FakeState {fsCalls, fsCallsOnce, fsCallsFrom, fsSent, fsPool, fsReceipts, fsDryRuns, fsUsed, fsBlock = (number, time), fsBlockTimes, fsFees = (tip, baseFee)} <- readTVar st
case (method, params) of
("eth_call", [call, J.String tag])
| Just (to, calldata) <- JT.parseMaybe callTarget call,
@@ -306,6 +319,10 @@ answer st method params = do
Nothing -> pure $ callAnswer $ case M.lookup key fsCallsFrom of
Just (from, a) | at >= from -> Just a
_ -> M.lookup key fsCalls
("eth_estimateGas", call : _)
| Just (_, calldata) <- JT.parseMaybe callTarget call,
Just revertData <- M.lookup calldata fsDryRuns ->
pure $ rpcError 3 "execution reverted" (Just revertData)
("eth_estimateGas", _) -> pure $ result $ quantity fakeGas
("eth_getTransactionCount", [_, J.String "latest"]) -> pure $ result $ quantity $ toInteger fsUsed
("eth_getTransactionCount", [_, J.String "pending"]) ->
@@ -147,7 +147,7 @@ badgeGroupIntegrationTests = do
namesBootTests :: SpecWith TestParams
namesBootTests = do
it "boots codes-only, refusing paid name orders 403 codes_only and answering code orders and code checks, the badges shell as built" testNamesBootCodesOnly
it "boots with [names] and [chain], routing fixed /api/name paths ahead of a search, registrations to GET, a reveal, a spend and a retry to POST, a path no route knows and a taken order's code to 404, code checks and orders under one limit, and spends and retries under another" testNamesBoot
it "boots with [names] and [chain], routing fixed /api/name paths ahead of a search, find ahead of registrations, registrations to GET, another name, a reveal, a spend and a retry to POST, a path no route knows and a taken order's code to 404, code checks and orders under one limit, and another name and retries under another" testNamesBoot
testNamesBoot :: HasCallStack => TestParams -> IO ()
testNamesBoot ps = do
@@ -161,6 +161,8 @@ testNamesBoot ps = do
refused tag = (400, Just $ J.object ["error" J..= (tag :: Text)])
unknown <- request "/api/names/unknown"
statusCode . responseStatus <$> httpLbs unknown mgr `shouldReturn` 404
records <- request "/api/name/records"
answer records {method = "POST", requestBody = RequestBodyLBS "{}"} `shouldReturn` refused "bad_request"
register <- request "/api/name/register"
answer register {method = "POST", requestBody = RequestBodyLBS "{}"} `shouldReturn` refused "bad_request"
search <- request $ "/api/name/" <> T.unpack aliceHex <> "?length=5"
@@ -169,6 +171,12 @@ testNamesBoot ps = do
answer registration `shouldReturn` (404, Just $ J.object ["error" J..= ("not_found" :: Text)])
posted <- httpLbs registration {method = "POST"} mgr
(statusCode $ responseStatus posted, lookup "Allow" $ responseHeaders posted) `shouldBe` (405, Just "GET")
found <- request "/api/registration/find"
answer found {method = "POST", requestBody = RequestBodyLBS "{}"} `shouldReturn` refused "bad_request"
foundByGet <- httpLbs found mgr
(statusCode $ responseStatus foundByGet, lookup "Allow" $ responseHeaders foundByGet) `shouldBe` (405, Just "POST")
owned <- request "/api/registration/t2Jk8RmQ4vXw9NcP3yLb6g/name"
answer owned {method = "POST", requestBody = RequestBodyLBS "{}"} `shouldReturn` refused "bad_request"
coded <- request "/api/registration/t2Jk8RmQ4vXw9NcP3yLb6g/code"
answer coded {method = "POST", requestBody = RequestBodyLBS "{}"} `shouldReturn` (404, Just $ J.object ["error" J..= ("not_found" :: Text)])
revealed <- request "/api/registration/t2Jk8RmQ4vXw9NcP3yLb6g/reveal"
@@ -197,8 +205,8 @@ testNamesBoot ps = do
answer retried {method = "POST"} `shouldReturn` (404, Just $ J.object ["error" J..= ("not_found" :: Text)])
retriedByGet <- httpLbs retried mgr
(statusCode $ responseStatus retriedByGet, lookup "Allow" $ responseHeaders retriedByGet) `shouldBe` (405, Just "POST")
-- the spend and the retry above took 2 of this client's 5 create requests a minute
replicateM_ 3 $ statusCode . responseStatus <$> httpLbs retried {method = "POST"} mgr `shouldReturn` 404
-- another name, the spend and the retry above took 3 of this client's 5 create requests a minute
replicateM_ 2 $ statusCode . responseStatus <$> httpLbs retried {method = "POST"} mgr `shouldReturn` 404
statusCode . responseStatus <$> httpLbs retried {method = "POST"} mgr `shouldReturn` 429
-- the register above took the first of this client's 10 code requests a minute, which the code check shares
let codeRequest path = request path >>= \r -> statusCode . responseStatus <$> httpLbs r {method = "POST", requestBody = RequestBodyLBS "{}"} mgr
@@ -28,6 +28,7 @@ namesChainTests = describe "StoreService names: chain" $ do
g <- runIO C.newRandom
describe "reverts" $ do
it "names every contract error by the selector viem encodes it with" testRevertSelectors
it "writes a revert's name as the contracts declare it, none for a revert without data" testRevertText
it "reads a dry run's revert with data by its name" $ testDryRunRevertNamed g
it "reads an eth_call revert with data by its name" $ testCallRevertNamed g
it "reads ownerOf of a name nobody holds as a revert" $ testOwnerOfRevert g
@@ -107,6 +108,12 @@ testRevertSelectors = do
decodeRevert (B.take 3 $ unhex "74480cc9") `shouldBe` Nothing
decodeRevert "" `shouldBe` Just RNWithoutData
testRevertText :: IO ()
testRevertText = do
revertText RNInvalidNonce `shouldBe` Just "InvalidNonce"
revertText RNSignatureExpired `shouldBe` Just "SignatureExpired"
revertText RNWithoutData `shouldBe` Nothing
testDryRunRevertNamed :: TVar ChaChaDRG -> IO ()
testDryRunRevertNamed g = withChain g $ \node c -> do
setFault node "eth_estimateGas" $ revertFault insufficientAllowance
File diff suppressed because it is too large. Load diff
+29 -4
View File
@@ -27,7 +27,7 @@ import Bots.StoreService.NamesContractsTests
year,
)
import Bots.StoreService.NamesProfilesTests (bakeryLink, jpeg, newsLink)
import Bots.StoreService.NamesStoreTests (issue, order, ownerA, placeCode, t0, usable)
import Bots.StoreService.NamesStoreTests (atNonce, issue, newEdit, order, ownerA, placeCode, setChannel, t0, usable)
import Bots.StoreService.WebTests (withServiceStore)
import Control.Concurrent.STM
import Control.Monad (forM_, replicateM_)
@@ -44,7 +44,8 @@ import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Encoding (decodeUtf8, encodeUtf8)
import Data.Time.Calendar (fromGregorian)
import Data.Time.Clock (NominalDiffTime, UTCTime (..), diffUTCTime, getCurrentTime)
import Data.Time.Clock (NominalDiffTime, UTCTime (..), addUTCTime, diffUTCTime, getCurrentTime)
import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds)
import Network.HTTP.Client (Manager, Request, RequestBody (..), defaultManagerSettings, httpLbs, method, newManager, parseRequest, requestBody, responseBody, responseHeaders, responseStatus)
import qualified Network.HTTP.Client as HTTP
import Network.HTTP.Types.Status (statusCode)
@@ -59,7 +60,7 @@ import StoreService.Names.Abi (AbiValue (..), abiBytes, abiTuple, bytes32FromHex
import StoreService.Names.Contracts (Contracts (..))
import StoreService.Names.Phases (RegistrationId (..))
import StoreService.Names.Profiles (ChatKind (..), HostResolver, LinkProfile (..), ProfileFetcher, ProfileLimits (..), defaultProfileLimits, monotonicSeconds, newProfiles)
import StoreService.Names.Store (NamePhase (..), NameRegistration (..), VersionWrite (..), getRegistration, updateRegistration)
import StoreService.Names.Store (EditState (..), NamePhase (..), NameRegistration (..), VersionWrite (..), getRegistration, insertRecordEdit, settleRecordEdit, updateRegistration)
import StoreService.Web.Http (newHttpEnv, notFound, previewLimit, searchLimit)
import StoreService.Web.Names (Route (..), namesApp)
import StoreService.Web.Names.Search (previewHandler, searchHandler)
@@ -77,6 +78,7 @@ namesSearchTests = describe "StoreService names: search" $ do
it "makes one entity per short link of its record's kind, splitting on ';', and none from other values" $ testRecordLinks g
it "makes entities of the first 5 short links of a record only, fetching no other" $ testRecordLinksCap g
it "reads no records from another resolver" $ testOtherResolver g
it "answers a registered name's record edits left and when the next one returns, counting pending and mined edits of 365 days" $ testRecordEdits g
it "answers a link whose profile was not read unread, and a private host's unavailable without fetching it" $ testEntityProfiles g
it "answers provider_unavailable to any failed chain read, records and price included" $ testFailedReads g
it "fails a search whose reads together pass one deadline, though each read meets it" $ testOneDeadline g
@@ -104,7 +106,7 @@ withSearch g adjustConfig adjust action = withServiceStore $ \store -> withContr
let cfg = adjustConfig $ namesConfig node
routes = \case
["api", "link", "preview"] -> Just Route {rMethod = "POST", rLimit = previewLimit, rHandler = previewHandler ps}
["api", "name", hash] -> Just Route {rMethod = "GET", rLimit = searchLimit, rHandler = searchHandler cfg store (adjust ct) ps hash}
["api", "name", hash] -> Just Route {rMethod = "GET", rLimit = searchLimit, rHandler = searchHandler cfg store (adjust ct) ps (pure t0) hash}
_ -> Nothing
app req respond = fromMaybe (respond notFound) (namesApp http routes req respond)
mgr <- newManager defaultManagerSettings
@@ -118,7 +120,9 @@ namesConfig node =
nTermStart = UTCTime (fromGregorian 2027 1 1) 0,
nTermSlackSeconds = 3600,
nRevealMarginSeconds = 900,
nMaxOrderMoves = 3,
nCodesOnly = False,
nRecordEditsPerYear = 3,
nTerms = TermsConfig {tVersion = termsVersion, tUrl = termsUrl},
nCommunity = M.empty,
nChain = fakeChainConfig node
@@ -269,6 +273,7 @@ registeredAnswer entities records resolver nonce =
"owner" .= ownerText,
"resolver" .= resolver,
"recordsNonce" .= nonce,
"recordEdits" .= if records == J.Null then J.Null else editsLeft 3 J.Null,
"expiresAt" .= (now + year),
"gracePeriod" .= gracePeriod,
"chainId" .= fakeChainId,
@@ -276,6 +281,9 @@ registeredAnswer entities records resolver nonce =
"community" .= J.Null
]
editsLeft :: Int -> J.Value -> J.Value
editsLeft left nextAt = J.object ["left" .= left, "nextAt" .= nextAt]
reservedAnswer, registeringAnswer :: Answer
reservedAnswer = ok ["status" .= str "reserved", "community" .= J.Null]
registeringAnswer = ok ["status" .= str "registered", "entities" .= ([] :: [J.Value]), "tld" .= str "simplex", "community" .= J.Null]
@@ -407,6 +415,23 @@ testOtherResolver g = withSearch g id id $ \s@Search {node} -> do
answerRegistered node otherResolver
searchAlice s 12 `shouldReturn` registeredAnswer [] J.Null otherResolverText J.Null
testRecordEdits :: TVar ChaChaDRG -> IO ()
testRecordEdits g = forM_ [(3, 1), (2, 0)] $ \(perYear, left) -> withSearch g (\cfg -> cfg {nRecordEditsPerYear = perYear}) id $ \s@Search {node, store} -> do
registeredWith node fullLink ""
let daysAgo :: Int -> UTCTime
daysAgo d = addUTCTime (fromIntegral $ negate d * 86400) t0
inserted n d = withTransaction store $ \db -> insertRecordEdit db (atNonce (fromIntegral n) $ newEdit ownerA n setChannel) (daysAgo d)
Just _ <- inserted 1 366
Just minedId <- inserted 2 10
Just revertedId <- inserted 3 5
Just _ <- inserted 4 1
withTransaction store $ \db -> do
settleRecordEdit db minedId (ESMined Nothing) `shouldReturn` True
settleRecordEdit db revertedId (ESReverted Nothing) `shouldReturn` True
answer <- searchAlice s 12
(snd answer >>= JT.parseMaybe (J.withObject "answer" (J..: "recordEdits")))
`shouldBe` Just (editsLeft left $ J.toJSON (floor (utcTimeToPOSIXSeconds $ daysAgo 10) + 365 * 86400 :: Int))
testEntityProfiles :: TVar ChaChaDRG -> IO ()
testEntityProfiles g = withSearch g id id $ \s@Search {node} -> do
let gone = taggedLink "smp8.simplex.im" 'a' "Gone"
+210 -9
View File
@@ -3,12 +3,12 @@
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
module Bots.StoreService.NamesStoreTests (namesStoreTests, at, btc, insertInvoiceRow, invoiceStatus, issue, newReg, order, ownerA, ownerB, paidOrder, placeCode, placePaid, price, reg, reveal, signature, t0, usable, write) where
module Bots.StoreService.NamesStoreTests (namesStoreTests, at, btc, insertInvoiceRow, invoiceStatus, atNonce, issue, newEdit, newReg, order, ownerA, ownerB, paidOrder, placeCode, placePaid, price, reg, reveal, setChannel, signature, t0, usable, write) where
import Bots.StoreService.ConfigTests (termsVersion)
import Bots.StoreService.WebTests (columnsOf, digestFixture, runMigrations, withServiceStore)
import Control.Arrow ((&&&))
import Control.Monad (forM_, void)
import Control.Monad (forM, forM_, void)
import Data.Int (Int64)
import Data.List (sort)
import Data.Maybe (fromJust, mapMaybe)
@@ -16,7 +16,8 @@ import Data.Text (Text)
import qualified Data.Text as T
import Data.Time.Calendar (fromGregorian)
import Data.Time.Clock (UTCTime (..), addUTCTime)
import Data.Word (Word8)
import Data.List.NonEmpty (NonEmpty (..))
import Data.Word (Word64, Word8)
import Simplex.Chat.Badges.Types (BadgeCodePaymentStatus (..))
import Simplex.Chat.PaymentService.Types (CardProvider (..), CryptoCurrency (..), InvoiceId (..), ServicePaymentMethod (..))
import Simplex.Messaging.Agent.Store.Common (DBStore, withTransaction)
@@ -24,6 +25,7 @@ import qualified Simplex.Messaging.Agent.Store.DB as DB
import Simplex.Messaging.Agent.Store.Shared (Migration (..), MigrationsToRun (..), toDownMigration)
import Simplex.Messaging.Crypto.Secp256k1 (RecoverableSignature)
import Simplex.Messaging.Eth.Address (Address, unAddress)
import Simplex.Messaging.Eth.EIP712 (serializeSignature)
import Simplex.Messaging.SimplexName (LabelHash (..), labelHash)
import StoreService.Names.Chain (TxHash (..))
import StoreService.Names.Phases (RegistrationId (..))
@@ -50,6 +52,7 @@ namesStoreTests = describe "StoreService names: store" $ do
it "makes taken orders not live and gives a taken paid order a balance of its price, none to a code order or a price of 0, and rolls back the balance tables and columns" testNameBalancesMigration
it "gives the orders stored before it empty agreed terms, and rolls the column back keeping them" testNameTermsMigration
it "adds the payments' invoiced units with the index of overpaid payments, and rolls both back keeping the payments" testInvoicedUnitsMigration
it "moves each stored edit's change to a row of its own, and rolls back keeping each edit's first change" testRecordChangesMigration
describe "order hash" $ do
it "is equal for the same order fields, and differs when any one field differs" testOrderHashFields
it "keeps field boundaries, so moving a byte between two fields changes it" testOrderHashBoundaries
@@ -68,6 +71,8 @@ namesStoreTests = describe "StoreService names: store" $ do
it "is live while an order can still progress to a registration for its name" testOrderLive
it "lets a wallet order a name again once its registration is done" testReorderAfterRegistered
it "refuses to queue a closed order, also when a newer live order holds its name" testLatePayment
it "refuses a write that would meet another live order, writing nothing" testWriteMeetsLiveOrder
it "retargets to the new fields, clearing the reveal, transactions, reveal times and refusal" testRetarget
it "finds an owner's orders newest first, at most 50" testFind
it "orders registrations made in the same second by their id" testSameSecondOrder
it "tells a label being registered here" testLabelRegistering
@@ -83,6 +88,14 @@ namesStoreTests = describe "StoreService names: store" $ do
describe "transactions" $ do
it "keeps a signed transaction pending until its outcome, and lists them by owner" testTransactions
it "moves a transaction only from the status its caller read" testTransactionFromStatus
describe "record edits" $ do
it "holds one pending or mined edit per owner and nonce, freed by a revert" testEditNonceUnique
it "settles a pending edit once, with its mined hash" testSettleEdit
it "round-trips a clear edit" testClearEdit
it "stores an edit's two changes and reads them back in nonce order, found by either nonce" testTwoChangeEdit
it "deletes an unsent edit with its changes" testDeleteUnsentChanges
it "gives the times of a name's relayed edits in the window" testRelayedEditTimes
it "gives the times of a name's pending and mined edits in the window, leaving out reverted ones" testCountedEditTimes
t0 :: UTCTime
t0 = UTCTime (fromGregorian 2026 10 21) 0
@@ -160,7 +173,7 @@ write :: DBStore -> NameRegistration -> IO VersionWrite
write st r = withTransaction st $ \db -> updateRegistration db r (at 1)
namesTables :: [Text]
namesTables = map ("sx_badge_service_name_" <>) ["prepaid_codes", "registrations", "invoices", "record_edits", "transactions", "balances", "late_credits"]
namesTables = map ("sx_badge_service_name_" <>) ["prepaid_codes", "registrations", "invoices", "record_edits", "record_changes", "transactions", "balances", "late_credits"]
-- | Added to the badge tables' payments by the names migrations.
balancePaymentColumns :: [Text]
@@ -185,13 +198,14 @@ testNamesColumns = withServiceStore $ \st -> do
has "sx_badge_service_name_late_credits" ["invoice_id", "credit_no", "registration_id", "units", "invoice_rate", "current_rate", "rate_used", "cents", "created_at"]
has "sx_badge_service_payments" balancePaymentColumns
has "sx_badge_service_name_record_edits" ["label_hash", "owner", "nonce", "body_hash", "state", "revert", "mined_tx", "created_at"]
has "sx_badge_service_name_record_changes" ["name_record_edit_id", "nonce", "record_key", "record_value", "deadline", "signature"]
has "sx_badge_service_name_transactions" ["registration_id", "name_record_edit_id", "kind", "raw", "tx_hash", "registrar_nonce", "sent_at", "mined_block", "status"]
testNamesDownUp :: IO ()
testNamesDownUp = withServiceStore $ \st -> do
let names = dropWhile ((/= "20261013_names") . name) storeServiceSchemaMigrations
badgeColumns = mapM (fmap sort . columnsOf st) badgeTables
map name names `shouldBe` ["20261013_names", "20261022_drop_taken_codes", "20261022_name_balances", "20261022_name_late_wait", "20261023_name_terms", "20261027_name_invoiced_units"]
map name names `shouldBe` ["20261013_names", "20261022_drop_taken_codes", "20261022_name_balances", "20261022_name_late_wait", "20261023_name_terms", "20261027_name_invoiced_units", "20261029_name_record_changes"]
badgeBefore <- badgeColumns
code <- issue st 1 usable
placeCode st "r1" ownerA (order "alicebakery" 1) code `shouldReturn` Right ()
@@ -314,6 +328,35 @@ testInvoicedUnitsMigration = withServiceStore $ \st -> do
applied `shouldReturn` (False, False)
payments `shouldReturn` stored
testRecordChangesMigration :: IO ()
testRecordChangesMigration = withServiceStore $ \st -> do
let changesMigration = [m | m@Migration {name = "20261029_name_record_changes"} <- storeServiceSchemaMigrations]
editColumns = sort <$> columnsOf st "sx_badge_service_name_record_edits"
oldEdits :: IO [(Int64, Maybe Text, Maybe Text, Int64)]
oldEdits = withTransaction st $ \db -> DB.query_ db "SELECT nonce, record_key, record_value, deadline FROM sx_badge_service_name_record_edits ORDER BY nonce"
length changesMigration `shouldBe` 1
runMigrations st $ MTRDown (mapMaybe toDownMigration changesMigration)
columnsOf st "sx_badge_service_name_record_changes" `shouldReturn` []
oldColumns <- editColumns
withTransaction st $ \db ->
forM_ [(4 :: Int64, Just ("simplex.channel" :: Text), Just ("https://smp9.simplex.im/c#abc" :: Text), 1 :: Word8), (7, Nothing, Nothing, 2)] $ \(nonce, key, value, n) ->
DB.execute
db
"INSERT INTO sx_badge_service_name_record_edits (label_hash, owner, nonce, record_key, record_value, deadline, signature, body_hash, state, created_at) VALUES (?,?,?,?,?,1792832400,?,?,'pending',?)"
((DB.Binary $ unLabelHash $ labelHash "alicebakery", DB.Binary $ unAddress ownerA, nonce, key, value) :. (DB.Binary $ serializeSignature signature, DB.Binary $ digestFixture n, t0))
stored <- oldEdits
runMigrations st $ MTRUp changesMigration
editColumns `shouldReturn` sort (filter (`notElem` ["record_key", "record_value", "deadline", "signature"]) oldColumns)
Just setEdit <- withTransaction st $ \db -> getRecordEditByBody db (digestFixture 1)
reChanges setEdit `shouldBe` signedAt 4 setChannel :| []
Just clearEdit <- withTransaction st $ \db -> getRecordEditByBody db (digestFixture 2)
reChanges clearEdit `shouldBe` signedAt 7 RCClear :| []
runMigrations st $ MTRDown (mapMaybe toDownMigration changesMigration)
editColumns `shouldReturn` oldColumns
oldEdits `shouldReturn` stored
where
unLabelHash (LabelHash h) = h
-- | A registration row as the code before the balances wrote it, paid by the invoice or the code given.
insertOldRegistration :: DB.Connection -> Text -> Word8 -> Text -> Int -> Maybe Int64 -> Maybe Text -> IO ()
insertOldRegistration db rid n phase cents codeId invId = do
@@ -604,6 +647,59 @@ testLatePayment = withServiceStore $ \st -> do
(nrPhase &&& nrLive) <$> reg st "r2" `shouldReturn` (PUnpaid, True)
write st r1 {nrVersion = 1, nrPhase = PQueued} `shouldReturn` VersionChanged
testWriteMeetsLiveOrder :: IO ()
testWriteMeetsLiveOrder = withServiceStore $ \st -> do
let held = order "bobsbakery" 2
placePaid st "r1" ownerA (order "alicebakery" 1) (at 60) `shouldReturn` Right ()
placePaid st "r2" ownerA held (at 60) `shouldReturn` Right ()
placePaid st "r3" ownerB (order "carolsbakery" 3) (at 60) `shouldReturn` Right ()
r1 <- reg st "r1"
write st r1 {nrPhase = PFailed} `shouldReturn` Written 2
failed <- reg st "r1"
let retarget o = withTransaction st $ \db -> retargetRegistration db failed o 10000 (at 6)
retarget held {ofCommitment = digestFixture 4} `shouldReturn` LiveOrderExists
r3 <- reg st "r3"
retarget (order "carolsbakery" 5) {ofCommitment = nrCommitment r3} `shouldReturn` LiveOrderExists
reg st "r1" `shouldReturn` failed
retarget (order "davesbakery" 6) `shouldReturn` Written 3
testRetarget :: IO ()
testRetarget = withServiceStore $ \st -> do
let o = order "alicebakery" 1
o' = (order "alicebakers" 2) {ofAgreedTerms = termsVersion <> "/community"}
placePaid st "r1" ownerA o (at 60) `shouldReturn` Right ()
r <- reg st "r1"
let failed =
r
{ nrPhase = PFailed,
nrReveal = Just reveal,
nrCommitTx = Just (TxHash $ digestFixture 8),
nrCommitBlock = Just 100,
nrRegisterTx = Just (TxHash $ digestFixture 9),
nrRegisterBlock = Just 120,
nrRevealAfter = Just 1,
nrRevealBefore = Just 2,
nrLinksRefusedAt = Just (at 4),
nrFailedAt = Just (at 5),
nrError = Just "failed"
}
write st failed `shouldReturn` Written 2
withTransaction st (\db -> retargetRegistration db failed {nrVersion = 2} o' 10000 (at 6)) `shouldReturn` Written 3
r' <- reg st "r1"
r'
`shouldBe` r
{ nrVersion = 3,
nrLabelHash = ofLabelHash o',
nrCommitment = ofCommitment o',
nrSealed = ofSealed o',
nrAgreedTerms = ofAgreedTerms o',
nrPrice = 10000,
nrPhase = PQueued,
nrMoves = 1,
nrUpdatedAt = at 6
}
withTransaction st (\db -> retargetRegistration db failed {nrVersion = 2} o 10000 (at 7)) `shouldReturn` VersionChanged
testFind :: IO ()
testFind = withServiceStore $ \st -> do
forM_ [1 .. 52 :: Int] $ \i -> withTransaction st $ \db -> do
@@ -789,27 +885,51 @@ testRevoke = withServiceStore $ \st -> do
held <- withTransaction st $ \db -> getPrepaidCodeById db (pcId reserved)
(pcReservedBy =<< held, pcRevokedAt =<< held) `shouldBe` (Just (RegistrationId "r1"), Just (at 1))
-- | An edit of one change at nonce 4.
newEdit :: Address -> Word8 -> RecordChange -> NewRecordEdit
newEdit owner n change =
NewRecordEdit
{ nreLabelHash = labelHash "alicebakery",
nreOwner = owner,
nreChanges = signedAt 4 change :| [],
nreBodyHash = digestFixture n
}
-- | The edit with its one change at this nonce.
atNonce :: Word64 -> NewRecordEdit -> NewRecordEdit
atNonce nonce edit@NewRecordEdit {nreChanges = change :| _} = edit {nreChanges = change {scNonce = nonce} :| []}
signedAt :: Word64 -> RecordChange -> SignedChange
signedAt scNonce scChange = SignedChange {scChange, scNonce, scDeadline = 1792832400, scSignature = signature}
setChannel, setContact :: RecordChange
setChannel = RCSetText "simplex.channel" "https://smp9.simplex.im/c#abc"
setContact = RCSetText "simplex.contact" "https://smp8.simplex.im/a#abc"
testTransactions :: IO ()
testTransactions = withServiceStore $ \st -> do
code <- issue st 1 usable
placeCode st "r1" ownerA (order "alicebakery" 1) code `shouldReturn` Right ()
Just editId <- withTransaction st $ \db -> insertRecordEdit db (newEdit ownerA 20 setChannel) t0
let r1 = RegistrationId "r1"
tx :: Word8 -> NewTransaction
tx n = NewTransaction {ntxRaw = digestFixture (n + 100), ntxHash = TxHash $ digestFixture n, ntxNonce = fromIntegral n}
[commitId, registerId] <- withTransaction st $ \db ->
sequence [insertTransaction db (TxCommit r1) (tx 2) (at 1), insertTransaction db (TxRegister r1) (tx 3) (at 3)]
[commitId, _, registerId] <- withTransaction st $ \db ->
sequence [insertTransaction db (TxCommit r1) (tx 2) (at 1), insertTransaction db (TxEdit editId) (tx 1) (at 2), insertTransaction db (TxRegister r1) (tx 3) (at 3)]
unsettled <- withTransaction st pendingTransactions
map (\NameTransaction {ntFor, ntNonce, ntStatus} -> (ntFor, ntNonce, ntStatus)) unsettled
`shouldBe` [(TxCommit r1, 2, TSPending), (TxRegister r1, 3, TSPending)]
map ntRaw unsettled `shouldBe` map (\n -> digestFixture (n + 100)) [2, 3]
`shouldBe` [(TxEdit editId, 1, TSPending), (TxCommit r1, 2, TSPending), (TxRegister r1, 3, TSPending)]
map ntRaw unsettled `shouldBe` map (\n -> digestFixture (n + 100)) [1, 2, 3]
let outcome n from status block = withTransaction st $ \db -> recordTransactionOutcome db (TxHash $ digestFixture n) from status block
outcome 2 TSPending TSMined (Just 77) `shouldReturn` True
outcome 1 TSPending TSReverted (Just 78) `shouldReturn` True
outcome 50 TSPending TSMined (Just 79) `shouldReturn` False
outcome 3 TSMined TSPending Nothing `shouldReturn` False
map ntFor <$> withTransaction st pendingTransactions `shouldReturn` [TxRegister r1]
ofRegistration <- withTransaction st $ \db -> registrationTransactions db r1
map (\NameTransaction {ntId, ntFor, ntMinedBlock, ntStatus, ntSentAt} -> (ntId, ntFor, ntMinedBlock, ntStatus, ntSentAt)) ofRegistration
`shouldBe` [(commitId, TxCommit r1, Just 77, TSMined, at 1), (registerId, TxRegister r1, Nothing, TSPending, at 3)]
map ntStatus <$> withTransaction st (\db -> editTransactions db editId) `shouldReturn` [TSReverted]
testTransactionFromStatus :: IO ()
testTransactionFromStatus = withServiceStore $ \st -> do
@@ -823,3 +943,84 @@ testTransactionFromStatus = withServiceStore $ \st -> do
current `shouldReturn` [(TSMined, Just 77)]
outcome TSMined TSPending Nothing `shouldReturn` True
current `shouldReturn` [(TSPending, Nothing)]
testEditNonceUnique :: IO ()
testEditNonceUnique = withServiceStore $ \st -> do
let run action = withTransaction st action
Just first <- run $ \db -> insertRecordEdit db (newEdit ownerA 1 setChannel) t0
run (\db -> insertRecordEdit db (newEdit ownerA 2 RCClear) t0) `shouldReturn` Nothing
Just other <- run $ \db -> insertRecordEdit db (newEdit ownerB 3 setChannel) t0
other `shouldNotBe` first
run (\db -> settleRecordEdit db first (ESReverted (Just "SignatureExpired"))) `shouldReturn` True
Just second <- run $ \db -> insertRecordEdit db (newEdit ownerA 2 RCClear) (at 1)
fmap reId <$> run (\db -> getRecordEditByNonce db ownerA 4) `shouldReturn` Just second
fmap reState <$> run (\db -> getRecordEditByBody db (digestFixture 1)) `shouldReturn` Just (ESReverted (Just "SignatureExpired"))
run (\db -> settleRecordEdit db second (ESMined Nothing)) `shouldReturn` True
run (\db -> insertRecordEdit db (newEdit ownerA 5 setChannel) (at 2)) `shouldReturn` Nothing
testSettleEdit :: IO ()
testSettleEdit = withServiceStore $ \st -> do
Just editId <- withTransaction st $ \db -> insertRecordEdit db (newEdit ownerA 1 setChannel) t0
withTransaction st (\db -> settleRecordEdit db editId (ESMined (Just $ TxHash $ digestFixture 9))) `shouldReturn` True
withTransaction st (\db -> settleRecordEdit db editId (ESReverted Nothing)) `shouldReturn` False
edit <- withTransaction st $ \db -> getRecordEdit db editId
edit
`shouldBe` Just
RecordEdit
{ reId = editId,
reLabelHash = labelHash "alicebakery",
reOwner = ownerA,
reChanges = signedAt 4 setChannel :| [],
reBodyHash = digestFixture 1,
reState = ESMined (Just $ TxHash $ digestFixture 9),
reCreatedAt = t0
}
testClearEdit :: IO ()
testClearEdit = withServiceStore $ \st -> do
Just editId <- withTransaction st $ \db -> insertRecordEdit db (newEdit ownerA 1 RCClear) t0
fmap (\RecordEdit {reChanges, reState} -> (reChanges, reState)) <$> withTransaction st (\db -> getRecordEdit db editId)
`shouldReturn` Just (signedAt 4 RCClear :| [], ESPending)
testTwoChangeEdit :: IO ()
testTwoChangeEdit = withServiceStore $ \st -> do
let run action = withTransaction st action
changes = signedAt 4 setContact :| [(signedAt 5 setChannel) {scDeadline = 1792832460}]
Just editId <- run $ \db -> insertRecordEdit db (newEdit ownerA 1 setContact) {nreChanges = changes} t0
fmap reChanges <$> run (\db -> getRecordEdit db editId) `shouldReturn` Just changes
fmap reId <$> run (\db -> getRecordEditByNonce db ownerA 4) `shouldReturn` Just editId
fmap reId <$> run (\db -> getRecordEditByNonce db ownerA 5) `shouldReturn` Just editId
fmap reChanges <$> run (\db -> getRecordEditByBody db (digestFixture 1)) `shouldReturn` Just changes
-- the first nonce is the edit's: another edit starting there waits for it to settle
run (\db -> insertRecordEdit db (newEdit ownerA 2 setChannel) t0) `shouldReturn` Nothing
changeRows st `shouldReturn` 2
testDeleteUnsentChanges :: IO ()
testDeleteUnsentChanges = withServiceStore $ \st -> do
let changes = signedAt 4 setContact :| [signedAt 5 setChannel]
Just editId <- withTransaction st $ \db -> insertRecordEdit db (newEdit ownerA 1 setContact) {nreChanges = changes} t0
withTransaction st $ \db -> deleteUnsentEdit db editId
withTransaction st (\db -> getRecordEdit db editId) `shouldReturn` Nothing
changeRows st `shouldReturn` 0
changeRows :: DBStore -> IO Int
changeRows st = withTransaction st $ \db -> do
[Only n] <- DB.query_ db "SELECT count(*) FROM sx_badge_service_name_record_changes"
pure n
testRelayedEditTimes :: IO ()
testRelayedEditTimes = withServiceStore $ \st -> do
forM_ (zip [1 ..] [0, 10, 20]) $ \(n, m) ->
withTransaction st $ \db -> void $ insertRecordEdit db (atNonce (fromIntegral n) $ newEdit ownerA n setChannel) (at m)
withTransaction st (\db -> void $ insertRecordEdit db (atNonce 9 $ newEdit ownerA 9 setChannel) {nreLabelHash = labelHash "bobsbakery"} (at 15))
withTransaction st (\db -> relayedEditTimes db (labelHash "alicebakery") (at 5)) `shouldReturn` [at 10, at 20]
testCountedEditTimes :: IO ()
testCountedEditTimes = withServiceStore $ \st -> do
[_, Just minedId, Just revertedId, _] <- forM (zip [1 ..] [0, 10, 20, 30]) $ \(n, m) ->
withTransaction st $ \db -> insertRecordEdit db (atNonce (fromIntegral n) $ newEdit ownerA n setChannel) (at m)
withTransaction st $ \db -> do
settleRecordEdit db minedId (ESMined Nothing) `shouldReturn` True
settleRecordEdit db revertedId (ESReverted Nothing) `shouldReturn` True
withTransaction st (\db -> void $ insertRecordEdit db (atNonce 9 $ newEdit ownerA 9 setChannel) {nreLabelHash = labelHash "bobsbakery"} (at 15))
withTransaction st (\db -> countedEditTimes db (labelHash "alicebakery") (at 5)) `shouldReturn` [at 10, at 30]
+1 -1
View File
@@ -423,7 +423,7 @@ testMigrationOrder = do
[(a, b) | (a, b) <- zip declared (drop 1 declared), a >= b] `shouldBe` []
let (badges, ours) = span (`elem` badgeMigrations) (map name storeServiceSchemaMigrations)
badges `shouldBe` badgeMigrations
ours `shouldBe` ["20261013_names", "20261022_drop_taken_codes", "20261022_name_balances", "20261022_name_late_wait", "20261023_name_terms", "20261027_name_invoiced_units"]
ours `shouldBe` ["20261013_names", "20261022_drop_taken_codes", "20261022_name_balances", "20261022_name_late_wait", "20261023_name_terms", "20261027_name_invoiced_units", "20261029_name_record_changes"]
where
badgeMigrations = ["20260915_badge_service_schema", "20260918_badge_group_ops", "20260925_badge_store_receipts", "20261012_badge_subscriptions"]
+4
View File
@@ -19,8 +19,10 @@ import Bots.StoreService.NamesContractsTests
import Bots.StoreService.NamesLabelTests
import Bots.StoreService.NamesLinksTests
import Bots.StoreService.NamesOrdersTests
import Bots.StoreService.NamesOwnerTests
import Bots.StoreService.NamesPhasesTests
import Bots.StoreService.NamesProfilesTests
import Bots.StoreService.NamesRecordsTests
import Bots.StoreService.NamesRevealTests
import Bots.StoreService.NamesSearchTests
import Bots.StoreService.NamesSenderTests
@@ -117,8 +119,10 @@ main = do
namesLabelTests
namesLinksTests
namesOrdersTests
namesOwnerTests
namesPhasesTests
namesProfilesTests
namesRecordsTests
namesRevealTests
namesSearchTests
namesSenderTests