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>
174 lines
8.5 KiB
Haskell
174 lines
8.5 KiB
Haskell
{-# LANGUAGE LambdaCase #-}
|
|
{-# LANGUAGE NamedFieldPuns #-}
|
|
{-# LANGUAGE OverloadedStrings #-}
|
|
{-# LANGUAGE TupleSections #-}
|
|
|
|
module StoreService.Names.Codes
|
|
( CodeState (..),
|
|
codeState,
|
|
codeStateText,
|
|
CodeRefusal (..),
|
|
codeRefusal,
|
|
codeRefusalTag,
|
|
reserveRefusal,
|
|
readPrepaidCode,
|
|
reserveCode,
|
|
releaseCode,
|
|
spendLandedCode,
|
|
issueNameCode,
|
|
revokeNameCode,
|
|
)
|
|
where
|
|
|
|
import Control.Applicative ((<|>))
|
|
import qualified Control.Exception as E
|
|
import Data.ByteString (ByteString)
|
|
import Data.Functor ((<&>))
|
|
import Data.Int (Int64)
|
|
import Data.Maybe (fromMaybe, isJust)
|
|
import Data.Text (Text)
|
|
import Data.Time.Clock (UTCTime, getCurrentTime)
|
|
import Simplex.Chat.Badges.Code (NamePrepaidCode, maxNameLength, minNameLength, namePrepaidCodeHash, randomNamePrepaidCode)
|
|
import Simplex.Chat.Badges.Types (BadgeCodePaymentStatus (..))
|
|
import Simplex.Chat.Bot.Store (withDB')
|
|
import Simplex.Chat.Controller (ChatController (..))
|
|
import Simplex.Messaging.Agent.Store.Common (DBStore, withTransaction)
|
|
import qualified Simplex.Messaging.Agent.Store.DB as DB
|
|
import StoreService.Config (minNameYears)
|
|
import StoreService.Group.Command (maxNameYears)
|
|
import StoreService.Names.Phases (RegistrationId)
|
|
import StoreService.Names.Store (CodeHashTaken (..), NewPrepaidCode (..), PrepaidCode (..), getPrepaidCode, getPrepaidCodeById, insertPrepaidCode, releasePrepaidCode, reservePrepaidCode, revokePrepaidCode, spendLandedPrepaidCode)
|
|
import StoreService.Names.Turns (Turns, withCodeTurn)
|
|
import StoreService.Store (RevokeResult (..))
|
|
|
|
data CodeState = CSUnused | CSReserved | CSUsed | CSRevoked | CSExpired | CSUnpaid
|
|
deriving (Eq, Show, Enum, Bounded)
|
|
|
|
-- | A code revoked while its order held it can still be spent by that order, so a spent code reads as used.
|
|
codeState :: UTCTime -> PrepaidCode -> CodeState
|
|
codeState now PrepaidCode {pcReservedBy, pcSpentAt, pcRevokedAt, pcPaymentStatus, pcExpiresAt}
|
|
| isJust pcSpentAt = CSUsed
|
|
| isJust pcRevokedAt = CSRevoked
|
|
| isJust pcReservedBy = CSReserved
|
|
| CPSUnpaid <- pcPaymentStatus = CSUnpaid
|
|
| maybe False (<= now) pcExpiresAt = CSExpired
|
|
| otherwise = CSUnused
|
|
|
|
codeStateText :: CodeState -> Text
|
|
codeStateText = \case
|
|
CSUnused -> "unused"
|
|
CSReserved -> "reserved"
|
|
CSUsed -> "used"
|
|
CSRevoked -> "revoked"
|
|
CSExpired -> "expired"
|
|
CSUnpaid -> "unpaid"
|
|
|
|
data CodeRefusal = CRInvalid | CRUsed | CRReserved | CRExpired | CRPaymentPending | CRNotCovering
|
|
deriving (Eq, Show)
|
|
|
|
codeRefusalTag :: CodeRefusal -> Text
|
|
codeRefusalTag = \case
|
|
CRInvalid -> "code_invalid"
|
|
CRUsed -> "code_used"
|
|
CRReserved -> "code_reserved"
|
|
CRExpired -> "code_expired"
|
|
CRPaymentPending -> "payment_pending"
|
|
CRNotCovering -> "code_not_covering"
|
|
|
|
-- | Why the code cannot pay for the registration's name of this length. A code the registration
|
|
-- already holds stays good for it until spent, even if revoked or expired since.
|
|
codeRefusal :: UTCTime -> RegistrationId -> Int -> PrepaidCode -> Maybe CodeRefusal
|
|
codeRefusal now rid len code@PrepaidCode {pcReservedBy, pcSpentAt, pcMinLength}
|
|
| isJust pcSpentAt = Just CRUsed
|
|
| pcReservedBy == Just rid = covering
|
|
| otherwise = stateRefusal (codeState now code) <|> covering
|
|
where
|
|
covering
|
|
| len < pcMinLength = Just CRNotCovering
|
|
| otherwise = Nothing
|
|
|
|
stateRefusal :: CodeState -> Maybe CodeRefusal
|
|
stateRefusal = \case
|
|
CSUnused -> Nothing
|
|
CSReserved -> Just CRReserved
|
|
CSUsed -> Just CRUsed
|
|
CSRevoked -> Just CRInvalid
|
|
CSExpired -> Just CRExpired
|
|
CSUnpaid -> Just CRPaymentPending
|
|
|
|
-- | Why a conditional reservation of the code refused it, as the code reads now.
|
|
reserveRefusal :: DB.Connection -> UTCTime -> ByteString -> RegistrationId -> Int -> IO CodeRefusal
|
|
reserveRefusal db now codeHash rid len = maybe CRInvalid (fromMaybe CRReserved . codeRefusal now rid len) <$> getPrepaidCode db codeHash
|
|
|
|
readPrepaidCode :: DBStore -> NamePrepaidCode -> IO (Maybe PrepaidCode)
|
|
readPrepaidCode st code = withTransaction st (`getPrepaidCode` namePrepaidCodeHash code)
|
|
|
|
newtype ReservationRefused = ReservationRefused CodeRefusal
|
|
deriving (Show)
|
|
|
|
instance E.Exception ReservationRefused
|
|
|
|
-- | In the code's turn and one transaction, the code is checked, the write runs, then the code is reserved for the
|
|
-- registration, so the registration's row is locked before the code's. A refused reservation rolls the write back.
|
|
reserveCode :: Turns -> DBStore -> UTCTime -> ByteString -> RegistrationId -> Int -> (DB.Connection -> IO (Either e a)) -> IO (Either CodeRefusal (Either e a))
|
|
reserveCode turns st now codeHash rid len write =
|
|
withCodeTurn turns codeHash $ either (\(ReservationRefused refusal) -> Left refusal) id <$> E.try (withTransaction st reserve)
|
|
where
|
|
reserve db =
|
|
getPrepaidCode db codeHash >>= \case
|
|
Nothing -> pure $ Left CRInvalid
|
|
Just code@PrepaidCode {pcId, pcReservedBy}
|
|
| Just refusal <- codeRefusal now rid len code -> pure $ Left refusal
|
|
| otherwise ->
|
|
write db >>= \case
|
|
written@(Right _)
|
|
| pcReservedBy /= Just rid ->
|
|
reservePrepaidCode db pcId rid now >>= \case
|
|
True -> pure $ Right written
|
|
-- Only a writer outside this process, which takes no turn here, can refuse it.
|
|
False -> E.throwIO . ReservationRefused =<< reserveRefusal db now codeHash rid len
|
|
written -> pure $ Right written
|
|
|
|
-- | The write runs first, and the code is released only if it succeeds. False when the registration did not hold the code.
|
|
releaseCode :: Turns -> DBStore -> Int64 -> RegistrationId -> (DB.Connection -> IO (Either e a)) -> IO (Either e (a, Bool))
|
|
releaseCode turns st codeId rid = afterWrite turns st codeId (\db -> releasePrepaidCode db codeId rid)
|
|
|
|
-- | The write runs first, and the code is spent only if it succeeds: the code the registration holds, or one it no longer holds
|
|
-- while still usable, as its register went through. False when the code was released and then spent, revoked or expired meanwhile.
|
|
spendLandedCode :: Turns -> DBStore -> UTCTime -> Int64 -> RegistrationId -> (DB.Connection -> IO (Either e a)) -> IO (Either e (a, Bool))
|
|
spendLandedCode turns st now codeId rid = afterWrite turns st codeId (\db -> spendLandedPrepaidCode db codeId rid now)
|
|
|
|
afterWrite :: Turns -> DBStore -> Int64 -> (DB.Connection -> IO Bool) -> (DB.Connection -> IO (Either e a)) -> IO (Either e (a, Bool))
|
|
afterWrite turns st codeId change write = do
|
|
codeHash_ <- withTransaction st $ \db -> fmap pcCodeHash <$> getPrepaidCodeById db codeId
|
|
let run = withTransaction st $ \db -> write db >>= traverse (\a -> (a,) <$> change db)
|
|
maybe run (\codeHash -> withCodeTurn turns codeHash run) codeHash_
|
|
|
|
-- | The code table keeps only the hash, so the caller must deliver the code.
|
|
issueNameCode :: ChatController -> Int -> Int -> BadgeCodePaymentStatus -> IO (Either String NamePrepaidCode)
|
|
issueNameCode cc len years paymentStatus
|
|
| len < minNameLength || len > maxNameLength = pure $ Left $ "name code length " <> show len <> " is outside " <> show minNameLength <> "-" <> show maxNameLength
|
|
| years < minNameYears || years > maxNameYears = pure $ Left $ "name code years " <> show years <> " is outside " <> show minNameYears <> "-" <> show maxNameYears
|
|
| otherwise = do
|
|
code <- randomNamePrepaidCode (random cc) len
|
|
now <- getCurrentTime
|
|
let new = NewPrepaidCode {npcCodeHash = namePrepaidCodeHash code, npcMinLength = len, npcYears = years, npcPaymentStatus = paymentStatus, npcExpiresAt = Nothing}
|
|
withDB' "issueNameCode" cc (\db -> insertPrepaidCode db new now) <&> \case
|
|
Right (Right _) -> Right code
|
|
Right (Left CodeHashTaken) -> Left "prepaid code hash taken"
|
|
Left e -> Left e
|
|
|
|
-- | Left is a refusal or a failure; both sides are the text to show the operator.
|
|
revokeNameCode :: Turns -> ChatController -> NamePrepaidCode -> IO (Either Text Text)
|
|
revokeNameCode turns cc code = withCodeTurn turns codeHash $ do
|
|
now <- getCurrentTime
|
|
withDB' "revokeNameCode" cc (\db -> (,) <$> revokePrepaidCode db codeHash now <*> getPrepaidCode db codeHash) <&> \case
|
|
Right (Revoked _, Just PrepaidCode {pcReservedBy = Just _}) -> Right "Revoked. The order holding it keeps it."
|
|
Right (Revoked _, _) -> Right "Revoked."
|
|
Right (AlreadyRevoked _, _) -> Right "Already revoked."
|
|
Right (AlreadyRedeemed, _) -> Left "Already used. It cannot be revoked."
|
|
Right (NoSuchCode, _) -> Left "No such code."
|
|
Left _ -> Left "The code could not be revoked."
|
|
where
|
|
codeHash = namePrepaidCodeHash code
|