mirror of
https://github.com/simplex-chat/simplex-chat.git
synced 2026-11-22 05:47:39 +00:00
* core: add prepaid name codes and length bounds * store: run the names migration after badges * store: issue and revoke prepaid name codes * store: document issuing prepaid name codes * store: move the ABI helpers to Names.Abi * store: read the [names] and [chain] settings * store: add the names chain client and reads * store: refuse group name codes while names are off * store: search names and preview links * store: serve each site on its own port * scripts: deploy the badges and names sites * store: document search and the two sites * store: add the drop_taken_codes migration * store: read the names codes_only setting * store: add the names store and order signatures * store: take name orders by card, crypto or code * store: document name orders and codes-only * store: add the names transaction sender * store: commit and register queued orders * store: reveal and retry an owner's order * store: document the gas key * store: add the name balance migrations * store: read crypto units, rates and confirmations * store: keep a taken order's money as a balance * store: spend a balance on another name * store: record refunds with //refund * store: document balances and refunds * store: add the agreed terms migration * store: read the terms and community names * store: answer community and terms in search * store: sign and store the agreed terms * store: document the terms and community names * store: add the invoiced units migration * store: read the crypto an invoice asks * store: credit late and overpaid crypto by share * store: document crediting late crypto by share * store: add the record changes migration * store: find an owner's orders and move one * store: relay owners' link edits on chain * store: document link edits * store: move isLoopbackHost to Config * store: trust dev issuer keys on the local chain * scripts: build the names site from a submodule * scripts: add the dev setup and contract run * store: document the dev setup and names image * store: send a Stripe idempotency key for names * tests: wait until a relay lets go of its edit * store: refuse a link edit deadline under 10 min * store: count reverted link edits in the year limit * store: require https for a remote chain node * store: refuse zero chain confirmations * store: set up the dev stack from the names branch * store: rerun a failed unpaid cleanup next pass * store: never replace a succeeded Stripe intent * store: refuse an ini setting written as key: value * store: note the webapp submodule's pinned branch * store: document confirmLanded judging by ownerOf * store: update the names webapp submodule * store-service: register names under the name policy, every name accepting its terms on chain (#7889) * store: accept each name's terms on chain under the name policy * ci: run the reduced build on sh/names-deploy * store: address review: policy re-read, terms reads and startup log * store: never credit an unconfirmed extra * store: alert money sent to a paid name invoice * store: refuse to start on another chain's node * store: keep orders while the allowance is used up * store: replace a stalled transaction after 3 blocks * store: judge a name taken at confirmation depth * store: bind the template's listener to loopback * store: scan only the ids of active name orders * store: refuse unknown [names] and [chain] settings * store: fetch the webapp submodule in upgrade steps * store: delete definitions only tests use * store: lock only name invoices at settlement * store: retry an unexpired commitment as usual * store: share the helpers defined twice * store: test route limits on the running service * store: fix tests that could not fail * ci: test the store service on Postgres * store: count IPv6 clients by their /64 * store: sweep invoices read alone past a list cap * store: cap checkouts of all clients together * store: cap the long polls held at once * store: stop the old badge project at upgrade * store: keep search lookups free of previews * store: read the ini as UTF-8 in any locale * ci: run Postgres store tests in a UTF-8 locale * store: cap the transactions one order sends * store: cancel a card intent after three declines * store: refuse a name price under a cent * store: send each transaction with gas headroom * store: cap searches and read terms once per block * store: never log the group join link * store: mask the database password at startup * store: run one instance per database * store: limit name codes to admins, 100 a day * store: refuse HighSpeed settlement with names * store: no unverified receipts with a trusted key * store: cap the log lines of refused webhooks * store: check Apple certificates at the signed date * store: refuse a malformed Stripe publishable key * store: check the owner before a refund * store: fold the names migrations into one * store: read onion name links through the proxy * store: refund money after paid once confirmed * store: limit the allowance wait to a dry run * store: bind loopback when upgrading * ci: cache and widen the store Postgres job * store: fix stale and duplicate names tests * store: fix the submodule path in the upgrade * store: refuse unpaid name codes on the CLI * store: apply the review's names test list * store: finish the review's names test list * store: restore the base registration tests * store: pass link hosts that do not resolve here * store: refuse a move once its sends are used up * store: take the shared checkout at the provider * store: hold a search slot for chain reads only * store: state which refunds are safe on a reference * store: check a failed order's name before refusing its move (#8060) * store: test and document the shared checkout cap for name orders * store: check a failed order's name on chain before refusing its move * store: test name links whose host lookup fails * store: test that a search holds its slot through the chain reads only * store: restore the signed transaction check in the chain tests * store: remove the chain tests' copy of the signed transaction check * store: correct the search slot texts and the README's balance endpoints * docs: system and sequence diagrams of the names service (#8068) --------- Co-authored-by: sh-agents <350651734+sh-agents@users.noreply.github.com> Co-authored-by: Evgeny Poberezkin <evgeny@poberezkin.com> Co-authored-by: brenzi-agent <brenzi-agent@brenzi.ch> Co-authored-by: Evgeny @ SimpleX Chat <259188159+evgeny-simplex@users.noreply.github.com>
171 lines
9.3 KiB
Haskell
171 lines
9.3 KiB
Haskell
{-# LANGUAGE LambdaCase #-}
|
|
{-# LANGUAGE NamedFieldPuns #-}
|
|
{-# LANGUAGE OverloadedStrings #-}
|
|
{-# LANGUAGE TupleSections #-}
|
|
|
|
module StoreService.Web.Names.Registration
|
|
( registrationHandler,
|
|
revealHandler,
|
|
retryHandler,
|
|
registrationChangedResponse,
|
|
registrationRefusalResponse,
|
|
heldFor,
|
|
versionParam,
|
|
)
|
|
where
|
|
|
|
import Control.Concurrent.STM (atomically)
|
|
import Control.Logger.Simple (logNote)
|
|
import Control.Monad (join)
|
|
import Control.Monad.Except (ExceptT (..), runExceptT)
|
|
import Data.Aeson ((.=))
|
|
import qualified Data.Aeson as J
|
|
import qualified Data.ByteString.Char8 as B
|
|
import Data.Char (isDigit)
|
|
import Data.Int (Int64)
|
|
import Data.Maybe (isJust, maybeToList)
|
|
import Data.Text (Text)
|
|
import Data.Time.Clock (UTCTime, diffUTCTime)
|
|
import Network.HTTP.Types (status200, status409)
|
|
import Network.Wai (Request, Response, ResponseReceived, queryString)
|
|
import Simplex.Messaging.Agent.Store.Common (withTransaction)
|
|
import Simplex.Messaging.Util (tshow)
|
|
import StoreService.Names.Orders (OrdersEnv (..))
|
|
import StoreService.Names.Phases (RegistrationId (..), awaitChange, publish)
|
|
import StoreService.Names.Registration (RegisterIntent (..))
|
|
import StoreService.Names.Reveal (RevealFields (..), RevealRefusal (..), SignedLabel (..), checkAcceptance, checkIntent, committedRegistration, isRepeat, linksValid, parseRevealFields, parseSignedLabel, revealOf)
|
|
import StoreService.Names.Store (NamePhase (..), NameRegistration (..), VersionWrite (..), getRegistration, updateRegistration)
|
|
import StoreService.Names.Turns (withLabelTurn)
|
|
import StoreService.Names.View (lapseMoment, registrationAt, registrationVersion, registrationView)
|
|
import StoreService.Names.Worker (Retried (..), RetryRefusal (..), retryRegistration)
|
|
import StoreService.Web.Http (HttpEnv, Respond, badRequest, holdsFull, invalidLink, jsonResponse, nameBodyBytes, notFound, providerUnavailable, readBoundedBody, withHoldSlot)
|
|
import StoreService.Web.Names.Codes (codeRefusalResponse)
|
|
import Text.Read (readMaybe)
|
|
|
|
-- | GET /api/registration/:id, held while its version is seenVersion.
|
|
registrationHandler :: OrdersEnv -> HttpEnv -> Int -> Text -> Request -> Respond -> IO ResponseReceived
|
|
registrationHandler OrdersEnv {oeStore, oeConfig, oeContracts, oePhases, oeNow} http hold ridText req respond =
|
|
readNow >>= \case
|
|
Nothing -> respond notFound
|
|
Just (now, r@NameRegistration {nrVersion})
|
|
| versionParam req == Just nrVersion ->
|
|
withHoldSlot http (awaitChange oePhases rid (registrationVersion oeStore rid) nrVersion (heldFor hold now $ maybeToList $ lapseMoment r))
|
|
>>= maybe (respond holdsFull) (const $ readNow >>= maybe (respond notFound) answer)
|
|
| otherwise -> answer (now, r)
|
|
where
|
|
rid = RegistrationId ridText
|
|
readNow = oeNow >>= \now -> fmap (now,) <$> withTransaction oeStore (`getRegistration` rid)
|
|
answer (now, r) = respond . jsonResponse status200 =<< registrationView oeStore oeConfig oeContracts now (registrationAt now r)
|
|
|
|
-- | What a reveal decided in the name's turn, with the version it wrote; the publish and the answer come after the turn.
|
|
data RevealDecision
|
|
= RDAccepted (Maybe Int64)
|
|
| RDRefused RevealRefusal (Maybe Int64)
|
|
| RDChanged
|
|
| RDGone
|
|
|
|
-- | POST /api/registration/:id/reveal, its checks in the contract's order, from the stored commitment in the name's turn.
|
|
revealHandler :: OrdersEnv -> Text -> Request -> Respond -> IO ResponseReceived
|
|
revealHandler env@OrdersEnv {oeStore, oeConfig, oeContracts, oeTurns, oePhases, oeNow} ridText req respond =
|
|
withTransaction oeStore (`getRegistration` rid) >>= \case
|
|
Nothing -> respond notFound
|
|
Just NameRegistration {nrLabelHash} ->
|
|
readBoundedBody nameBodyBytes req >>= \case
|
|
Just body | Just (J.Object o) <- J.decode body, Just signed <- parseSignedLabel o -> withLabelTurn oeTurns nrLabelHash (decide nrLabelHash o signed) >>= answer
|
|
_ -> answer $ RDRefused RVBadRequest Nothing
|
|
where
|
|
rid = RegistrationId ridText
|
|
decide turnHash o signed = do
|
|
now <- oeNow
|
|
withTransaction oeStore (`getRegistration` rid) >>= \case
|
|
Nothing -> pure RDGone
|
|
Just r@NameRegistration {nrLabelHash, nrReveal}
|
|
-- moved to another name while this request waited for the turn
|
|
| nrLabelHash /= turnHash -> pure RDChanged
|
|
| Just stored <- nrReveal -> pure $ if isRepeat signed stored then RDAccepted Nothing else RDRefused RVBadRequest Nothing
|
|
| nrPhase (registrationAt now r) /= PCommitted -> pure $ RDRefused RVBadRequest Nothing
|
|
| otherwise -> case parseRevealFields o of
|
|
Nothing -> pure $ RDRefused RVBadRequest Nothing
|
|
Just fields -> either (\refusal -> pure $ RDRefused refusal Nothing) (signedReveal now r signed fields) $ committedRegistration oeConfig r signed fields
|
|
signedReveal now r SignedLabel {slSignature} RevealFields {rfNonce, rfDeadline, rfAcceptance} registration = do
|
|
let intent = RegisterIntent {riRegistration = registration, riNonce = rfNonce, riDeadline = rfDeadline, riSignature = slSignature}
|
|
runExceptT (ExceptT (checkIntent oeConfig oeContracts now (nrRevealBefore r) intent) >> ExceptT (checkAcceptance oeConfig oeContracts r rfDeadline rfAcceptance)) >>= \case
|
|
Left refusal -> pure $ RDRefused refusal Nothing
|
|
Right ()
|
|
| linksValid registration -> write now (RDAccepted . Just) r {nrReveal = Just $ revealOf intent rfAcceptance}
|
|
| isJust (nrLinksRefusedAt r) -> pure $ RDRefused RVInvalidLink Nothing
|
|
| otherwise -> write now (RDRefused RVInvalidLink . Just) r {nrLinksRefusedAt = Just now}
|
|
write now decided r =
|
|
withTransaction oeStore (\db -> updateRegistration db r now) >>= \case
|
|
Written v -> pure $ decided v
|
|
_ -> pure RDChanged
|
|
answer = \case
|
|
RDAccepted v -> published v >> respond (jsonResponse status200 $ J.object [])
|
|
RDRefused refusal v -> do
|
|
published v
|
|
logNote ("POST /api/registration/:id/reveal refused: " <> tshow refusal)
|
|
respond $ case refusal of
|
|
RVBadRequest -> badRequest
|
|
RVInvalidLink -> invalidLink
|
|
RVChainUnavailable -> providerUnavailable
|
|
RDChanged -> respond =<< registrationChangedResponse env rid
|
|
RDGone -> respond notFound
|
|
published = mapM_ (atomically . publish oePhases rid)
|
|
|
|
-- | POST /api/registration/:id/retry, Try again in the name's turn; the publish and the answer come after the turn.
|
|
retryHandler :: OrdersEnv -> Text -> Request -> Respond -> IO ResponseReceived
|
|
retryHandler env@OrdersEnv {oeStore, oeTurns, oePhases} ridText _ respond =
|
|
withTransaction oeStore (`getRegistration` rid) >>= \case
|
|
Nothing -> respond notFound
|
|
Just NameRegistration {nrLabelHash} -> withLabelTurn oeTurns nrLabelHash (decide nrLabelHash) >>= maybe (respond notFound) answer
|
|
where
|
|
rid = RegistrationId ridText
|
|
decide turnHash = withTransaction oeStore (`getRegistration` rid) >>= traverse (inTurn turnHash)
|
|
inTurn turnHash r
|
|
-- moved to another name while this request waited for the turn
|
|
| nrLabelHash r /= turnHash = pure RTChanged
|
|
| otherwise = retryRegistration env r
|
|
answer = \case
|
|
RTWritten v -> do
|
|
atomically $ publish oePhases rid v
|
|
respond . maybe notFound (jsonResponse status200) =<< currentView env rid
|
|
RTChanged -> respond =<< registrationChangedResponse env rid
|
|
RTRefused refusal -> do
|
|
logNote ("POST /api/registration/:id/retry refused: " <> tshow refusal)
|
|
respond $ case refusal of
|
|
RFNotFailed -> badRequest
|
|
RFLinksRefused -> badRequest
|
|
RFSendsUsedUp -> badRequest
|
|
RFCode code -> codeRefusalResponse code
|
|
RFUnread -> providerUnavailable
|
|
|
|
-- | The registration's current view, for a request that lost the race to change it.
|
|
registrationChangedResponse :: OrdersEnv -> RegistrationId -> IO Response
|
|
registrationChangedResponse env = registrationRefusalResponse env "registration_changed"
|
|
|
|
-- | A refusal with the registration's current view, so the page follows its state.
|
|
registrationRefusalResponse :: OrdersEnv -> Text -> RegistrationId -> IO Response
|
|
registrationRefusalResponse env tag rid = maybe notFound refusal <$> currentView env rid
|
|
where
|
|
refusal view = jsonResponse status409 $ J.object ["error" .= tag, "registration" .= view]
|
|
|
|
-- | The registration's view as it reads now.
|
|
currentView :: OrdersEnv -> RegistrationId -> IO (Maybe J.Value)
|
|
currentView OrdersEnv {oeStore, oeConfig, oeContracts, oeNow} rid =
|
|
withTransaction oeStore (`getRegistration` rid) >>= traverse (\r -> oeNow >>= \now -> registrationView oeStore oeConfig oeContracts now (registrationAt now r))
|
|
|
|
-- | The hold, cut to end just past the next moment at which the answer changes with time alone.
|
|
heldFor :: Int -> UTCTime -> [UTCTime] -> Int
|
|
heldFor hold now moments = fromInteger $ minimum $ toInteger hold : [ceiling (diffUTCTime moment now * microsPerSecond) + 1 | moment <- moments, moment >= now]
|
|
where
|
|
microsPerSecond = 1000000
|
|
|
|
-- | Nothing unless seenVersion is a decimal version, so any other value answers at once.
|
|
versionParam :: Request -> Maybe Int64
|
|
versionParam req = case join $ lookup "seenVersion" $ queryString req of
|
|
Just s | not (B.null s) && B.all isDigit s -> readMaybe (B.unpack s) >>= inRange
|
|
_ -> Nothing
|
|
where
|
|
inRange :: Integer -> Maybe Int64
|
|
inRange v = if v <= toInteger (maxBound :: Int64) then Just (fromInteger v) else Nothing
|