mirror of
https://github.com/simplex-chat/simplex-chat.git
synced 2026-11-22 05:47:39 +00:00
store: keep a taken order's money as a balance
This commit is contained in:
1 parent
468d6eb55f
commit
40e0dfcdc9
17 files changed
+2895
-183
No files matched your search
@@ -0,0 +1,106 @@
|
||||
{-# LANGUAGE LambdaCase #-}
|
||||
{-# LANGUAGE NamedFieldPuns #-}
|
||||
|
||||
module StoreService.Names.Balances
|
||||
( RefundRefusal (..),
|
||||
RefundRecord (..),
|
||||
recordRefund,
|
||||
Spend (..),
|
||||
spendTerms,
|
||||
checkSpendBalance,
|
||||
coveredOrderInsert,
|
||||
differenceOrderInsert,
|
||||
)
|
||||
where
|
||||
|
||||
import Data.Maybe (isNothing)
|
||||
import Data.Text (Text)
|
||||
import Data.Time.Clock (UTCTime)
|
||||
import Simplex.Chat.PaymentService.Types (ServicePaymentMethod)
|
||||
import Simplex.Messaging.Agent.Store.Common (DBStore, withTransaction)
|
||||
import qualified Simplex.Messaging.Agent.Store.DB as DB
|
||||
import StoreService.Names.Orders (OrderRefusal (..))
|
||||
import StoreService.Names.Phases (RegistrationId)
|
||||
import StoreService.Names.Store (Balance (..), BalanceHold, BalanceLink, NameRegistration, NewRegistration, OrderTerms (..), PaidOrder, RegistrationRefused (..), balanceByReference, balanceChain, createBalanceRegistration, createPaidRegistration, getBalance, heldBy, overdueHolder, refundBalance)
|
||||
import StoreService.Names.Turns (Turns, withBalanceTurn)
|
||||
|
||||
-- | RefundAmount: the balance's amount now, which is not the cents given. RefundHeld: an order holds it, overdue or not,
|
||||
-- since only the poller's sweep can close a holder and cancel its invoice at the provider.
|
||||
data RefundRefusal = RefundNoOrder | RefundNoBalance | RefundAmount Int | RefundHeld BalanceHold
|
||||
deriving (Eq, Show)
|
||||
|
||||
-- | The chain names every order the money came through, for support to pay it back by the methods that paid it.
|
||||
data RefundRecord = RefundRecord
|
||||
{ rdRegistration :: RegistrationId,
|
||||
rdCents :: Int,
|
||||
rdChain :: [BalanceLink]
|
||||
}
|
||||
deriving (Eq, Show)
|
||||
|
||||
-- | The reference is the order's registration id or its name invoice's id. In the balance's turn and one transaction.
|
||||
recordRefund :: Turns -> DBStore -> Text -> Int -> UTCTime -> IO (Either RefundRefusal RefundRecord)
|
||||
recordRefund turns st ref cents now =
|
||||
withTransaction st (\db -> balanceByReference db ref now) >>= \case
|
||||
Nothing -> pure $ Left RefundNoOrder
|
||||
Just (rid, _) -> withBalanceTurn turns rid $ withTransaction st (refund True)
|
||||
where
|
||||
refund retry db =
|
||||
balanceByReference db ref now >>= \case
|
||||
Nothing -> pure $ Left RefundNoOrder
|
||||
Just (rid, balance) -> case refusal balance of
|
||||
Just r -> pure $ Left r
|
||||
Nothing ->
|
||||
refundBalance db rid cents now >>= \case
|
||||
True -> Right . RefundRecord rid cents <$> balanceChain db rid
|
||||
-- only a writer outside the turn, as a late credit, changes the balance between the read and the write, so it is read again once
|
||||
False
|
||||
| retry -> refund False db
|
||||
| otherwise -> pure $ Left $ RefundAmount $ maybe 0 blAmount balance
|
||||
refusal :: Maybe Balance -> Maybe RefundRefusal
|
||||
refusal = \case
|
||||
Nothing -> Just RefundNoBalance
|
||||
Just Balance {blHold = Just hold} -> Just $ RefundHeld hold
|
||||
Just Balance {blAmount}
|
||||
| blAmount /= cents || blAmount <= 0 -> Just $ RefundAmount blAmount
|
||||
| otherwise -> Nothing
|
||||
|
||||
-- | A new order paid from a balance. Its hash covers the paying order, the price, the balance the page read,
|
||||
-- and the method, present exactly when the price is more than that balance.
|
||||
data Spend = Spend
|
||||
{ spSource :: RegistrationId,
|
||||
spPrice :: Int,
|
||||
spBalance :: Int,
|
||||
spMethod :: Maybe ServicePaymentMethod
|
||||
}
|
||||
|
||||
spendTerms :: Spend -> OrderTerms
|
||||
spendTerms Spend {spSource, spPrice, spBalance, spMethod} = OTBalance spSource spPrice spBalance spMethod
|
||||
|
||||
-- | The balance has the amount the page read and no open order holds it. A hold by an overdue order reads as none,
|
||||
-- and that order is returned for the new order's transaction to close.
|
||||
checkSpendBalance :: DBStore -> Spend -> UTCTime -> IO (Either OrderRefusal (Maybe NameRegistration))
|
||||
checkSpendBalance st Spend {spSource, spBalance} now =
|
||||
withTransaction st $ \db ->
|
||||
getBalance db spSource now >>= \case
|
||||
Just balance@Balance {blAmount}
|
||||
| blAmount == spBalance && isNothing (heldBy balance) -> Right <$> overdueHolder db spSource now
|
||||
balance -> pure $ Left $ ORBalanceChanged balance
|
||||
|
||||
-- | The order queued, its price spent from the balance read.
|
||||
coveredOrderInsert :: Spend -> NewRegistration -> DB.Connection -> UTCTime -> IO (Either OrderRefusal ())
|
||||
coveredOrderInsert Spend {spSource, spPrice, spBalance} new db now =
|
||||
balanceRefusal db spSource now =<< createBalanceRegistration db new spSource spPrice spBalance now
|
||||
|
||||
-- | The order unpaid with its invoice for the difference, holding all of the balance read.
|
||||
differenceOrderInsert :: Spend -> NewRegistration -> PaidOrder -> DB.Connection -> UTCTime -> IO (Either OrderRefusal ())
|
||||
differenceOrderInsert spend@Spend {spSource} new paid db now =
|
||||
balanceRefusal db spSource now =<< createPaidRegistration db new (spendTerms spend) paid now
|
||||
|
||||
-- | A write refused at the balance answers with the balance as this transaction reads it.
|
||||
balanceRefusal :: DB.Connection -> RegistrationId -> UTCTime -> Either RegistrationRefused () -> IO (Either OrderRefusal ())
|
||||
balanceRefusal db source now = \case
|
||||
Right () -> pure $ Right ()
|
||||
Left RRBalanceChanged -> Left . ORBalanceChanged <$> getBalance db source now
|
||||
Left RRLiveOrder -> pure $ Left OROrderExists
|
||||
-- a spend reserves no code
|
||||
Left RRCodeNotReservable -> pure $ Left OROrderExists
|
||||
@@ -0,0 +1,96 @@
|
||||
{-# LANGUAGE LambdaCase #-}
|
||||
{-# LANGUAGE NamedFieldPuns #-}
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
{-# LANGUAGE TupleSections #-}
|
||||
|
||||
-- | The credit of a closed order's late money to its balance: only confirmed money not yet credited, crypto at the lower
|
||||
-- of the invoice's rate and the current one. The rate is read outside any transaction, so the credit runs after the
|
||||
-- settlement that recorded the money commits, and again from the poller's pass for whatever is still not credited.
|
||||
module StoreService.Names.LateCredits
|
||||
( CreditOutcome (..),
|
||||
minCurrentRateFraction,
|
||||
creditLateInvoice,
|
||||
lateCreditOf,
|
||||
)
|
||||
where
|
||||
|
||||
import Data.Ratio ((%))
|
||||
import Data.Scientific (Scientific)
|
||||
import Data.Text (Text)
|
||||
import qualified Data.Text as T
|
||||
import Data.Time.Clock (UTCTime)
|
||||
import Simplex.Chat.PaymentService.Types (CryptoCurrency, InvoiceId)
|
||||
import Simplex.Messaging.Agent.Store.Common (DBStore, withTransaction)
|
||||
import StoreService.Names.Store (LateCredit (..), LateCreditState (..), LateSupport (..), NamePhase (..), creditLatePayment, lateCreditState, setLateSupport)
|
||||
import StoreService.Providers (ProviderError (..), Rate (..), unitDecimals)
|
||||
import StoreService.Store.Invoices (lockInvoice)
|
||||
import Text.Read (readMaybe)
|
||||
|
||||
-- | A current rate below this fraction of the invoice's is not used: it may be a glitch or a real fall, which the owner decides on.
|
||||
minCurrentRateFraction :: Rational
|
||||
minCurrentRateFraction = 1 % 2
|
||||
|
||||
-- | CONoInvoiceRate: crypto due with no invoice rate recorded to credit it at. CORefused: the credit's number was taken meanwhile,
|
||||
-- which the invoice's lock rules out.
|
||||
data CreditOutcome
|
||||
= CONothingDue
|
||||
| COCredited LateCredit
|
||||
| CONoInvoiceRate
|
||||
| CORateFailed ProviderError
|
||||
| CORateFloor Text Rate
|
||||
| CORefused
|
||||
deriving (Eq, Show)
|
||||
|
||||
creditLateInvoice :: DBStore -> (CryptoCurrency -> IO (Either ProviderError Rate)) -> InvoiceId -> UTCTime -> IO CreditOutcome
|
||||
creditLateInvoice st readRate invId now =
|
||||
withTransaction st (`lateCreditState` invId) >>= \case
|
||||
Just s | creditable s && moneyDue s -> case lsCoin s of
|
||||
Nothing -> credit Nothing
|
||||
Just coin -> case invoiceRate s of
|
||||
Nothing -> pure CONoInvoiceRate
|
||||
Just (invoiceText, invoiceValue) ->
|
||||
readRate coin >>= \case
|
||||
Left e -> pure $ CORateFailed e
|
||||
Right rate
|
||||
| toRational (rateValue rate) < minCurrentRateFraction * toRational invoiceValue ->
|
||||
CORateFloor invoiceText rate <$ withTransaction st (\db -> setLateSupport db invId LSRateFloor)
|
||||
| otherwise -> credit (Just rate)
|
||||
_ -> pure CONothingDue
|
||||
where
|
||||
credit rate = withTransaction st $ \db -> do
|
||||
lockInvoice db invId now
|
||||
lateCreditState db invId >>= \case
|
||||
Just s | creditable s, Just c <- lateCreditOf s rate -> do
|
||||
applied <- creditLatePayment db c now
|
||||
pure $ if applied then COCredited c else CORefused
|
||||
_ -> pure CONothingDue
|
||||
|
||||
-- | A closed order's money, unless a rate below the floor sent it to support for good, so a later recovery cannot credit money refunded by hand.
|
||||
creditable :: LateCreditState -> Bool
|
||||
creditable LateCreditState {lsPhase, lsLive, lsSupport} = lsPhase == PUnpaid && not lsLive && lsSupport /= Just LSRateFloor
|
||||
|
||||
moneyDue :: LateCreditState -> Bool
|
||||
moneyDue s@LateCreditState {lsConfirmedCents, lsCreditedCents} = case lsCoin s of
|
||||
Nothing -> lsConfirmedCents > lsCreditedCents
|
||||
Just _ -> unitsDue s > 0
|
||||
|
||||
unitsDue :: LateCreditState -> Integer
|
||||
unitsDue LateCreditState {lsConfirmedUnits, lsCreditedUnits} = maybe 0 toInteger lsConfirmedUnits - toInteger lsCreditedUnits
|
||||
|
||||
invoiceRate :: LateCreditState -> Maybe (Text, Scientific)
|
||||
invoiceRate LateCreditState {lsInvoiceRate} = lsInvoiceRate >>= \t -> (t,) <$> readMaybe (T.unpack t)
|
||||
|
||||
-- | The next credit of the money not yet credited: card cents as they are, crypto units at the lower rate, rounded down to the cent.
|
||||
lateCreditOf :: LateCreditState -> Maybe Rate -> Maybe LateCredit
|
||||
lateCreditOf s@LateCreditState {lsInvoice, lsRegistration, lsCredits, lsConfirmedCents, lsCreditedCents} rate = case (lsCoin s, rate, invoiceRate s) of
|
||||
(Nothing, _, _)
|
||||
| lsConfirmedCents > lsCreditedCents -> Just (credit Nothing Nothing Nothing Nothing (lsConfirmedCents - lsCreditedCents))
|
||||
(Just coin, Just Rate {rateText, rateValue}, Just (invoiceText, invoiceValue))
|
||||
| unitsDue s > 0 ->
|
||||
let (usedText, usedValue) = if rateValue < invoiceValue then (rateText, rateValue) else (invoiceText, invoiceValue)
|
||||
cents = floor (fromInteger (unitsDue s) * toRational usedValue * 100 / 10 ^ unitDecimals coin)
|
||||
in Just (credit (Just $ fromInteger $ unitsDue s) (Just invoiceText) (Just rateText) (Just usedText) cents)
|
||||
_ -> Nothing
|
||||
where
|
||||
credit lcUnits lcInvoiceRate lcCurrentRate lcRateUsed lcCents =
|
||||
LateCredit {lcInvoice = lsInvoice, lcCreditNo = lsCredits + 1, lcRegistration = lsRegistration, lcUnits, lcInvoiceRate, lcCurrentRate, lcRateUsed, lcCents}
|
||||
@@ -43,6 +43,7 @@ import qualified Data.Aeson.KeyMap as KM
|
||||
import Data.Bifunctor (first)
|
||||
import Data.ByteString (ByteString)
|
||||
import Data.Int (Int64)
|
||||
import Data.Maybe (catMaybes)
|
||||
import Data.Scientific (toBoundedInteger)
|
||||
import Data.Text (Text)
|
||||
import qualified Data.Text as T
|
||||
@@ -64,7 +65,7 @@ import StoreService.Names.Env (NamesEnv (..))
|
||||
import StoreService.Names.Phases (Phases, RegistrationId (..))
|
||||
import StoreService.Names.Abi (bytes32FromHex, hex)
|
||||
import StoreService.Names.Signatures (OrderFields (..), orderMessage, parseChecksumAddress, parseSignature, personalDigest)
|
||||
import StoreService.Names.Store (LiveOrder (..), NamePhase (..), NameRegistration (..), NewRegistration (..), PrepaidCode (..), RegistrationPayment (..), RegistrationRefused (..), NameTransaction (..), TxFor (..), TxStatus (..), VersionWrite (..), closeOverdue, createCodeRegistration, getLiveOrders, getPrepaidCode, getPrepaidCodeById, getRegistrationByOrderHash, isLabelRegistering, registrationTransactions, updateRegistration)
|
||||
import StoreService.Names.Store (Balance, LiveOrder (..), NamePhase (..), NameRegistration (..), NewRegistration (..), PrepaidCode (..), RegistrationPayment (..), RegistrationRefused (..), NameTransaction (..), TxFor (..), TxStatus (..), VersionWrite (..), closeOverdue, createCodeRegistration, getBalance, getLiveOrders, getPrepaidCode, getPrepaidCodeById, getRegistration, getRegistrationByOrderHash, isLabelRegistering, registrationTransactions, updateRegistration)
|
||||
import StoreService.Names.Turns (Turns, withCodeTurn)
|
||||
|
||||
data OrdersEnv = OrdersEnv
|
||||
@@ -96,6 +97,7 @@ data OrderRefusal
|
||||
| ORNameCheckUnavailable
|
||||
| ORCatalogChanged Int
|
||||
| ORCode CodeRefusal
|
||||
| ORBalanceChanged (Maybe Balance)
|
||||
| ORCodesOnly
|
||||
deriving (Eq, Show)
|
||||
|
||||
@@ -187,10 +189,11 @@ overdueOrdersMet db OrderRequest {orOwner, orFields = OrderFields {ofLabelHash,
|
||||
closable LiveOrder {loRegistration = NameRegistration {nrOwner, nrLabelHash}, loOverdue} =
|
||||
loOverdue && nrOwner == orOwner && nrLabelHash == ofLabelHash
|
||||
|
||||
-- | In one transaction, the overdue orders the request meets are closed, then the order is inserted.
|
||||
-- | In one transaction, the overdue orders the request meets and the balance holders the caller names are closed, then the order is inserted.
|
||||
-- A named holder no longer live is skipped, and one still live that cannot be closed refuses with the balance it holds.
|
||||
-- Refused, changing nothing, when it meets an order it cannot close, or the insert refuses.
|
||||
placeOrder :: OrdersEnv -> OrderRequest -> (DB.Connection -> UTCTime -> IO (Either OrderRefusal ())) -> IO (Either OrderRefusal [ClosedOrder])
|
||||
placeOrder OrdersEnv {oeStore, oeNow} req insert = do
|
||||
placeOrder :: OrdersEnv -> OrderRequest -> [NameRegistration] -> (DB.Connection -> UTCTime -> IO (Either OrderRefusal ())) -> IO (Either OrderRefusal [ClosedOrder])
|
||||
placeOrder OrdersEnv {oeStore, oeNow} req holders insert = do
|
||||
now <- oeNow
|
||||
first (\(OrderRefused refusal) -> refusal) <$> E.try (withTransaction oeStore $ \db -> transaction db now)
|
||||
where
|
||||
@@ -198,12 +201,21 @@ placeOrder OrdersEnv {oeStore, oeNow} req insert = do
|
||||
overdueOrdersMet db req now >>= \case
|
||||
Just overdue -> do
|
||||
closed <- mapM (close db now) overdue
|
||||
insert db now >>= either (E.throwIO . OrderRefused) (const $ pure closed)
|
||||
closedHolders <- catMaybes <$> mapM (closeHolder db now) holders
|
||||
insert db now >>= either (E.throwIO . OrderRefused) (const $ pure $ closed <> closedHolders)
|
||||
Nothing -> E.throwIO $ OrderRefused OROrderExists
|
||||
close db now r =
|
||||
closeOverdue db r now >>= \case
|
||||
Just v -> pure ClosedOrder {coRegistration = r, coVersion = v}
|
||||
Nothing -> E.throwIO $ OrderRefused OROrderExists
|
||||
-- read again here, since another order of its own name may have closed it meanwhile
|
||||
closeHolder db now NameRegistration {nrId} =
|
||||
getRegistration db nrId >>= \case
|
||||
Just holder@NameRegistration {nrLive = True, nrBalanceSource} ->
|
||||
closeOverdue db holder now >>= \case
|
||||
Just v -> pure $ Just ClosedOrder {coRegistration = holder, coVersion = v}
|
||||
Nothing -> E.throwIO . OrderRefused . ORBalanceChanged =<< maybe (pure Nothing) (\source -> getBalance db source now) nrBalanceSource
|
||||
_ -> pure Nothing
|
||||
|
||||
-- | In the code's turn, the code as it reads there must pay for the name; the order's insert then reserves it.
|
||||
placeCodeOrder :: OrdersEnv -> OrderRequest -> RegistrationId -> PrepaidCode -> IO (Either OrderRefusal [ClosedOrder])
|
||||
@@ -214,7 +226,7 @@ placeCodeOrder env@OrdersEnv {oeStore, oeTurns, oeNow} req@OrderRequest {orOwner
|
||||
Nothing -> pure $ Left $ ORCode CRInvalid
|
||||
Just code
|
||||
| Just refusal <- codeRefusal now rid ofLength code -> pure $ Left $ ORCode refusal
|
||||
| otherwise -> placeOrder env req $ codeOrderInsert NewRegistration {nrgId = rid, nrgOwner = orOwner, nrgOrder = fields, nrgYears = pcYears} code
|
||||
| otherwise -> placeOrder env req [] $ codeOrderInsert NewRegistration {nrgId = rid, nrgOwner = orOwner, nrgOrder = fields, nrgYears = pcYears} code
|
||||
|
||||
-- | The code was checked in its turn, so only a writer outside this process can make its reservation fail.
|
||||
codeOrderInsert :: NewRegistration -> PrepaidCode -> DB.Connection -> UTCTime -> IO (Either OrderRefusal ())
|
||||
@@ -223,6 +235,8 @@ codeOrderInsert new@NewRegistration {nrgId, nrgOrder = OrderFields {ofLength}} c
|
||||
Right () -> pure $ Right ()
|
||||
Left RRLiveOrder -> pure $ Left OROrderExists
|
||||
Left RRCodeNotReservable -> Left . ORCode <$> reserveRefusal db now pcCodeHash nrgId ofLength
|
||||
-- a code order holds no balance
|
||||
Left RRBalanceChanged -> pure $ Left OROrderExists
|
||||
|
||||
checkTimestamp :: UTCTime -> Word64 -> Either OrderRefusal ()
|
||||
checkTimestamp now timestamp =
|
||||
@@ -298,6 +312,7 @@ confirmLanded OrdersEnv {oeStore, oeContracts, oeTurns, oeNow} r@NameRegistratio
|
||||
write db = versionWritten <$> updateRegistration db registered now
|
||||
case nrPayment of
|
||||
RPInvoice {} -> withTransaction oeStore write
|
||||
RPBalance -> withTransaction oeStore write
|
||||
RPCode codeId -> spendLandedCode oeTurns oeStore now codeId nrId write >>= traverse (paidWith codeId)
|
||||
paidWith codeId (v, spent) = do
|
||||
unless spent $ do
|
||||
|
||||
@@ -8,6 +8,7 @@ module StoreService.Names.Signatures
|
||||
parseSignature,
|
||||
personalDigest,
|
||||
orderMessage,
|
||||
spendMessage,
|
||||
parseChecksumAddress,
|
||||
parseAnyCaseAddress,
|
||||
)
|
||||
@@ -33,6 +34,7 @@ import Simplex.Messaging.Eth.Address (Address)
|
||||
import Simplex.Messaging.SimplexName (LabelHash (..))
|
||||
import Simplex.Messaging.Util (tshow)
|
||||
import StoreService.Names.Abi (hex)
|
||||
import StoreService.Names.Phases (RegistrationId (..))
|
||||
|
||||
data SignatureError
|
||||
= SEFormat
|
||||
@@ -90,6 +92,10 @@ personalDigest msg = keccak256 $ "\x19\&Ethereum Signed Message:\n" <> BC.pack (
|
||||
orderMessage :: OrderFields -> Word64 -> ByteString
|
||||
orderMessage order timestamp = message $ ["order"] <> orderWords order <> [tshow timestamp]
|
||||
|
||||
-- | The registration id is the order whose balance pays; the fields are the new order's.
|
||||
spendMessage :: RegistrationId -> OrderFields -> Word64 -> ByteString
|
||||
spendMessage (RegistrationId rid) order timestamp = message $ ["spend", rid] <> orderWords order <> [tshow timestamp]
|
||||
|
||||
message :: [Text] -> ByteString
|
||||
message = encodeUtf8 . T.unwords . ("simplex.domains" :)
|
||||
|
||||
|
||||
@@ -16,6 +16,16 @@ module StoreService.Names.Store
|
||||
VersionWrite (..),
|
||||
LiveOrder (..),
|
||||
OrderTerms (..),
|
||||
Balance (..),
|
||||
BalanceHold (..),
|
||||
BalanceLink (..),
|
||||
LateCredit (..),
|
||||
LateCreditState (..),
|
||||
LatePending (..),
|
||||
LateAlert (..),
|
||||
LateSupport (..),
|
||||
LateWait (..),
|
||||
CleanupKept (..),
|
||||
PrepaidCode (..),
|
||||
NewPrepaidCode (..),
|
||||
CodeHashTaken (..),
|
||||
@@ -31,6 +41,7 @@ module StoreService.Names.Store
|
||||
textMethod,
|
||||
createPaidRegistration,
|
||||
createCodeRegistration,
|
||||
createBalanceRegistration,
|
||||
getRegistration,
|
||||
getRegistrationByOrderHash,
|
||||
getLiveOrders,
|
||||
@@ -42,6 +53,23 @@ module StoreService.Names.Store
|
||||
unpaidCleanupCandidates,
|
||||
deleteUnpaidRegistration,
|
||||
failedCodeOrdersBefore,
|
||||
heldBy,
|
||||
getBalance,
|
||||
overdueHolder,
|
||||
balanceByReference,
|
||||
balanceChain,
|
||||
creditBalance,
|
||||
spendHeldBalance,
|
||||
releaseHeldBalance,
|
||||
refundBalance,
|
||||
lateCreditState,
|
||||
creditLatePayment,
|
||||
latePending,
|
||||
uncreditedLateInvoices,
|
||||
lateAlertDue,
|
||||
claimLateAlert,
|
||||
setLateSupport,
|
||||
lateWait,
|
||||
insertPrepaidCode,
|
||||
getPrepaidCode,
|
||||
getPrepaidCodeById,
|
||||
@@ -64,9 +92,10 @@ import Data.ByteArray.Encoding (Base (Base16), convertToBase)
|
||||
import Data.ByteString (ByteString)
|
||||
import qualified Data.ByteString as B
|
||||
import Data.Int (Int64)
|
||||
import Data.Functor ((<&>))
|
||||
import Data.Maybe (isJust, listToMaybe)
|
||||
import Data.String (fromString)
|
||||
import Data.Text (Text)
|
||||
import qualified Data.Text as T
|
||||
import Data.Text.Encoding (encodeUtf8)
|
||||
import Data.Time.Clock (UTCTime)
|
||||
import Data.Word (Word64)
|
||||
@@ -87,7 +116,7 @@ import StoreService.Names.Chain (TxHash (..))
|
||||
import StoreService.Names.Phases (RegistrationId (..))
|
||||
import StoreService.Names.Signatures (OrderFields (..), parseSignature)
|
||||
import StoreService.Store (RevokeResult (..))
|
||||
import StoreService.Store.Invoices (StoreDecodeError (..), executeChanging, invoiceStatusText, lockInvoice, newInvoiceId, truncateToSecond, unfundedQuery)
|
||||
import StoreService.Store.Invoices (StoreDecodeError (..), executeChanging, invoiceStatusText, lockInvoice, newInvoiceId, textToCryptoCurrency, truncateToSecond, unfundedQuery)
|
||||
|
||||
#if defined(dbPostgres)
|
||||
import Database.PostgreSQL.Simple (Only (..), Query, (:.) (..))
|
||||
@@ -124,9 +153,11 @@ instance FromField NamePhase where fromField = fromTextField_ textDecode
|
||||
|
||||
instance ToField NamePhase where toField = toField . textEncode
|
||||
|
||||
-- | RPBalance: an order paid wholly from another order's balance, with neither invoice nor code.
|
||||
data RegistrationPayment
|
||||
= RPInvoice ServicePaymentMethod InvoiceId
|
||||
| RPCode Int64
|
||||
| RPBalance
|
||||
deriving (Eq, Show)
|
||||
|
||||
-- | The name, links and owner's intent, all set by an accepted reveal and cleared together.
|
||||
@@ -154,6 +185,8 @@ data NameRegistration = NameRegistration
|
||||
nrYears :: Int,
|
||||
nrPrice :: Int,
|
||||
nrPayment :: RegistrationPayment,
|
||||
nrBalanceSource :: Maybe RegistrationId,
|
||||
nrBalanceUsed :: Int,
|
||||
nrReveal :: Maybe NameReveal,
|
||||
nrCommitTx :: Maybe TxHash,
|
||||
nrCommitBlock :: Maybe Word64,
|
||||
@@ -189,7 +222,8 @@ data PaidOrder = PaidOrder
|
||||
poProviderRef :: Text
|
||||
}
|
||||
|
||||
data RegistrationRefused = RRLiveOrder | RRCodeNotReservable
|
||||
-- | RRBalanceChanged: the source's balance no longer has the amount seen, or another order holds it.
|
||||
data RegistrationRefused = RRLiveOrder | RRCodeNotReservable | RRBalanceChanged
|
||||
deriving (Eq, Show)
|
||||
|
||||
-- | NotLive: the write would make a closed order live. LiveOrderExists: another live order holds its commitment, or its owner and label hash.
|
||||
@@ -203,8 +237,125 @@ data LiveOrder = LiveOrder
|
||||
}
|
||||
deriving (Eq, Show)
|
||||
|
||||
-- | What an order pays with, as its hash covers it.
|
||||
data OrderTerms = OTInvoice ServicePaymentMethod Int | OTCode ByteString
|
||||
-- | What an order pays with, as its hash covers it. OTBalance: the paying order, the price, the balance seen, and the method of a difference.
|
||||
data OrderTerms = OTInvoice ServicePaymentMethod Int | OTCode ByteString | OTBalance RegistrationId Int Int (Maybe ServicePaymentMethod)
|
||||
|
||||
-- | Cents left to spend, and over the balance's life the cents credited and refunded.
|
||||
data Balance = Balance
|
||||
{ blRegistration :: RegistrationId,
|
||||
blAmount :: Int,
|
||||
blCredited :: Int,
|
||||
blRefunded :: Int,
|
||||
blHold :: Maybe BalanceHold,
|
||||
blRefundedAt :: Maybe UTCTime
|
||||
}
|
||||
deriving (Eq, Show)
|
||||
|
||||
-- | The order whose open invoice holds a balance, until that invoice expires; overdue past it with no money received.
|
||||
-- Funded once money reached it: it then holds until its payment settles or the provider closes it, whatever the time.
|
||||
data BalanceHold = BalanceHold
|
||||
{ bhHolder :: RegistrationId,
|
||||
bhUntil :: UTCTime,
|
||||
bhOverdue :: Bool,
|
||||
bhFunded :: Bool
|
||||
}
|
||||
deriving (Eq, Show)
|
||||
|
||||
-- | An order the money of a balance came through. lkPaid and lkFromBalance count only an order that went past unpaid,
|
||||
-- since closing an unpaid one released its source's balance.
|
||||
data BalanceLink = BalanceLink
|
||||
{ lkRegistration :: RegistrationId,
|
||||
lkPayment :: RegistrationPayment,
|
||||
lkPaid :: Int,
|
||||
lkFromBalance :: Int,
|
||||
lkLateCredits :: [LateCredit]
|
||||
}
|
||||
deriving (Eq, Show)
|
||||
|
||||
-- | Money paid on a name invoice after its order closed, credited to that order's balance. Rates are decimal text; card money has no units or rates.
|
||||
data LateCredit = LateCredit
|
||||
{ lcInvoice :: InvoiceId,
|
||||
lcCreditNo :: Int,
|
||||
lcRegistration :: RegistrationId,
|
||||
lcUnits :: Maybe Int64,
|
||||
lcInvoiceRate :: Maybe Text,
|
||||
lcCurrentRate :: Maybe Text,
|
||||
lcRateUsed :: Maybe Text,
|
||||
lcCents :: Int
|
||||
}
|
||||
deriving (Eq, Show)
|
||||
|
||||
-- | A name invoice's payment figures, what was credited from it, and its order's phase and live flag. Card money (no coin) is counted in cents,
|
||||
-- crypto in units. lsSupport: why its money will not be credited by itself, once known.
|
||||
data LateCreditState = LateCreditState
|
||||
{ lsInvoice :: InvoiceId,
|
||||
lsRegistration :: RegistrationId,
|
||||
lsPhase :: NamePhase,
|
||||
lsLive :: Bool,
|
||||
lsCoin :: Maybe CryptoCurrency,
|
||||
lsSupport :: Maybe LateSupport,
|
||||
lsReceivedCents :: Int,
|
||||
lsConfirmedCents :: Int,
|
||||
lsReceivedUnits :: Maybe Int64,
|
||||
lsConfirmedUnits :: Maybe Int64,
|
||||
lsInvoiceRate :: Maybe Text,
|
||||
lsCreditedUnits :: Int64,
|
||||
lsCreditedCents :: Int,
|
||||
lsCredits :: Int,
|
||||
lsPaymentCreatedAt :: UTCTime
|
||||
}
|
||||
deriving (Eq, Show)
|
||||
|
||||
-- | Why a closed order's money is not all credited: Monero confirming with a zero figure, confirmed money not credited yet,
|
||||
-- money received and not confirmed, or crypto received that could not be counted in units.
|
||||
data LatePending = LPConfirming | LPUncredited | LPUnconfirmed | LPUncounted
|
||||
deriving (Eq, Show, Enum, Bounded)
|
||||
|
||||
instance TextEncoding LatePending where
|
||||
textEncode = \case
|
||||
LPConfirming -> "confirming"
|
||||
LPUncredited -> "uncredited"
|
||||
LPUnconfirmed -> "unconfirmed"
|
||||
LPUncounted -> "uncounted"
|
||||
textDecode t = lookup t [(textEncode p, p) | p <- [minBound .. maxBound]]
|
||||
|
||||
instance FromField LatePending where fromField = fromTextField_ textDecode
|
||||
|
||||
-- | What a closed order's late money waits on, for the view: confirmation, the credit, or support.
|
||||
data LateWait = LWConfirming | LWCrediting | LWSupport
|
||||
deriving (Eq, Show)
|
||||
|
||||
-- | Why a closed order's money will not be credited by itself: an invoice made under HighSpeed, an amount that could not be counted in units,
|
||||
-- a current rate below the floor, unconfirmed money alerted past the read window, or money the provider shows no confirmation of.
|
||||
data LateSupport = LSHighSpeed | LSUnits | LSRateFloor | LSUnconfirmed | LSNoConfirmation
|
||||
deriving (Eq, Show, Enum, Bounded)
|
||||
|
||||
instance TextEncoding LateSupport where
|
||||
textEncode = \case
|
||||
LSHighSpeed -> "high_speed"
|
||||
LSUnits -> "units"
|
||||
LSRateFloor -> "rate_floor"
|
||||
LSUnconfirmed -> "unconfirmed"
|
||||
LSNoConfirmation -> "no_confirmation"
|
||||
textDecode t = lookup t [(textEncode s, s) | s <- [minBound .. maxBound]]
|
||||
|
||||
instance FromField LateSupport where fromField = fromTextField_ textDecode
|
||||
|
||||
instance ToField LateSupport where toField = toField . textEncode
|
||||
|
||||
-- | A closed order's pending money to alert on, with the received figure the alert names and the one the last alert named.
|
||||
data LateAlert = LateAlert
|
||||
{ laState :: LateCreditState,
|
||||
laPending :: LatePending,
|
||||
laReceived :: Maybe Int64,
|
||||
laAlertedAt :: Maybe UTCTime,
|
||||
laAlertedReceived :: Maybe Int64
|
||||
}
|
||||
deriving (Eq, Show)
|
||||
|
||||
-- | Why the cleanup keeps an unpaid order: a payment was recorded for it, or it holds the balance of the given order.
|
||||
data CleanupKept = CKPaid | CKHolder RegistrationId
|
||||
deriving (Eq, Show)
|
||||
|
||||
data PrepaidCode = PrepaidCode
|
||||
{ pcId :: Int64,
|
||||
@@ -286,6 +437,7 @@ orderHash owner OrderFields {ofLabelHash = LabelHash lh, ofLength, ofDuration, o
|
||||
(tag, payment) = case terms of
|
||||
OTInvoice method price -> ("name-invoice", [encodeUtf8 $ methodText method, num price])
|
||||
OTCode codeHash -> ("name-code", [codeHash])
|
||||
OTBalance (RegistrationId source) price seen method -> ("name-balance", [encodeUtf8 source, num price, num seen, maybe "" (encodeUtf8 . methodText) method])
|
||||
field bs = i2ospOf_ orderHashFieldBytes (toInteger $ B.length bs) <> bs
|
||||
num :: Show a => a -> ByteString
|
||||
num = encodeUtf8 . tshow
|
||||
@@ -302,47 +454,70 @@ methodText = \case
|
||||
textMethod :: Text -> Maybe ServicePaymentMethod
|
||||
textMethod t = lookup t [(methodText m, m) | m <- [SPMCard CPStripe, SPMCrypto CCBtc, SPMCrypto CCXmr]]
|
||||
|
||||
createPaidRegistration :: DB.Connection -> NewRegistration -> PaidOrder -> UTCTime -> IO (Either RegistrationRefused ())
|
||||
createPaidRegistration db new@NewRegistration {nrgId = RegistrationId rid, nrgOwner, nrgOrder} PaidOrder {poMethod, poPrice, poInvoiceId = InvoiceId invId, poProviderRef} now' = do
|
||||
-- | A difference order (OTBalance) holds all of the balance seen while its invoice is open. The hold is written after the registration,
|
||||
-- so the registration's row is locked before the balance's.
|
||||
createPaidRegistration :: DB.Connection -> NewRegistration -> OrderTerms -> PaidOrder -> UTCTime -> IO (Either RegistrationRefused ())
|
||||
createPaidRegistration db new@NewRegistration {nrgId = regId@(RegistrationId rid), nrgOwner, nrgOrder} terms PaidOrder {poMethod, poPrice, poInvoiceId = InvoiceId invId, poProviderRef} now' = do
|
||||
let now = truncateToSecond now'
|
||||
hash = orderHash nrgOwner nrgOrder (OTInvoice poMethod poPrice)
|
||||
inserted <- insertRegistration db new PUnpaid poPrice (Just poMethod) Nothing hash now
|
||||
when inserted $
|
||||
DB.execute
|
||||
db
|
||||
"INSERT INTO sx_badge_service_name_invoices (invoice_id, registration_id, provider_ref, created_at) VALUES (?,?,?,?)"
|
||||
(invId, rid, poProviderRef, now)
|
||||
pure $ if inserted then Right () else Left RRLiveOrder
|
||||
held = case terms of
|
||||
OTBalance source _ seen _ -> Just (source, seen)
|
||||
OTInvoice {} -> Nothing
|
||||
OTCode _ -> Nothing
|
||||
inserted <- insertRegistration db new PUnpaid poPrice (Just poMethod) Nothing held (orderHash nrgOwner nrgOrder terms) now
|
||||
if not inserted
|
||||
then pure $ Left RRLiveOrder
|
||||
else do
|
||||
DB.execute
|
||||
db
|
||||
"INSERT INTO sx_badge_service_name_invoices (invoice_id, registration_id, provider_ref, created_at) VALUES (?,?,?,?)"
|
||||
(invId, rid, poProviderRef, now)
|
||||
held' <- maybe (pure True) (\(source, seen) -> holdBalance db source seen regId now) held
|
||||
if held' then pure $ Right () else Left RRBalanceChanged <$ deleteRegistration db regId
|
||||
|
||||
-- | Reserving the code is the conditional update of the transaction that creates the registration.
|
||||
createCodeRegistration :: DB.Connection -> NewRegistration -> PrepaidCode -> UTCTime -> IO (Either RegistrationRefused ())
|
||||
createCodeRegistration db new@NewRegistration {nrgId = regId@(RegistrationId rid), nrgOwner, nrgOrder} PrepaidCode {pcId, pcCodeHash} now' = do
|
||||
createCodeRegistration db new@NewRegistration {nrgId = regId, nrgOwner, nrgOrder} PrepaidCode {pcId, pcCodeHash} now' = do
|
||||
let now = truncateToSecond now'
|
||||
inserted <- insertRegistration db new PQueued 0 Nothing (Just pcId) (orderHash nrgOwner nrgOrder (OTCode pcCodeHash)) now
|
||||
inserted <- insertRegistration db new PQueued 0 Nothing (Just pcId) Nothing (orderHash nrgOwner nrgOrder (OTCode pcCodeHash)) now
|
||||
if not inserted
|
||||
then pure $ Left RRLiveOrder
|
||||
else
|
||||
reservePrepaidCode db pcId regId now >>= \case
|
||||
True -> pure $ Right ()
|
||||
False -> do
|
||||
DB.execute db "DELETE FROM sx_badge_service_name_registrations WHERE registration_id = ?" (Only rid)
|
||||
pure $ Left RRCodeNotReservable
|
||||
False -> Left RRCodeNotReservable <$ deleteRegistration db regId
|
||||
|
||||
-- | A queued order whose price is spent from the source's balance in the same transaction, where its amount is the one seen and nothing holds it.
|
||||
createBalanceRegistration :: DB.Connection -> NewRegistration -> RegistrationId -> Int -> Int -> UTCTime -> IO (Either RegistrationRefused ())
|
||||
createBalanceRegistration db new@NewRegistration {nrgId, nrgOwner, nrgOrder} source price seen now' = do
|
||||
let now = truncateToSecond now'
|
||||
inserted <- insertRegistration db new PQueued price Nothing Nothing (Just (source, price)) (orderHash nrgOwner nrgOrder (OTBalance source price seen Nothing)) now
|
||||
if not inserted
|
||||
then pure $ Left RRLiveOrder
|
||||
else
|
||||
spendBalance db source price seen now >>= \case
|
||||
True -> pure $ Right ()
|
||||
False -> Left RRBalanceChanged <$ deleteRegistration db nrgId
|
||||
|
||||
-- | The name invoice row goes with it.
|
||||
deleteRegistration :: DB.Connection -> RegistrationId -> IO ()
|
||||
deleteRegistration db (RegistrationId rid) = DB.execute db "DELETE FROM sx_badge_service_name_registrations WHERE registration_id = ?" (Only rid)
|
||||
|
||||
-- | False when the registration would be a second live one for its commitment, or for its owner and label hash.
|
||||
insertRegistration :: DB.Connection -> NewRegistration -> NamePhase -> Int -> Maybe ServicePaymentMethod -> Maybe Int64 -> ByteString -> UTCTime -> IO Bool
|
||||
insertRegistration db NewRegistration {nrgId = RegistrationId rid, nrgOwner, nrgOrder, nrgYears} phase price method codeId hash now =
|
||||
-- fromBalance: the order whose balance pays, and the cents it pays.
|
||||
insertRegistration :: DB.Connection -> NewRegistration -> NamePhase -> Int -> Maybe ServicePaymentMethod -> Maybe Int64 -> Maybe (RegistrationId, Int) -> ByteString -> UTCTime -> IO Bool
|
||||
insertRegistration db NewRegistration {nrgId = RegistrationId rid, nrgOwner, nrgOrder, nrgYears} phase price method codeId fromBalance hash now =
|
||||
(> 0)
|
||||
<$> executeChanging
|
||||
db
|
||||
[sql|
|
||||
INSERT INTO sx_badge_service_name_registrations
|
||||
(registration_id, version, label_hash, length, duration, owner, commitment, sealed, phase, years,
|
||||
price, method, name_prepaid_code_id, live, order_hash, moves, created_at, updated_at)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?, ?,?,?,?,?,?,?,?)
|
||||
price, method, name_prepaid_code_id, live, order_hash, moves, created_at, updated_at, balance_source, balance_used)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?, ?,?,?,?,?,?,?,?,?,?)
|
||||
ON CONFLICT DO NOTHING
|
||||
|]
|
||||
( (rid, initialVersion, Binary lh, ofLength, int64 ofDuration, Binary $ unAddress nrgOwner, Binary ofCommitment, ofSealed, phase, nrgYears)
|
||||
:. (price, methodText <$> method, codeId, BI True, Binary hash, 0 :: Int, now, now)
|
||||
:. (price, methodText <$> method, codeId, BI True, Binary hash, 0 :: Int, now, now, (\(RegistrationId s, _) -> s) <$> fromBalance, maybe 0 snd fromBalance)
|
||||
)
|
||||
where
|
||||
OrderFields {ofLabelHash = LabelHash lh, ofLength, ofDuration, ofCommitment, ofSealed} = nrgOrder
|
||||
@@ -353,7 +528,7 @@ registrationColumns =
|
||||
SELECT r.registration_id, r.version, r.label_hash, r.length, r.duration, r.owner, r.commitment, r.sealed, r.phase, r.years,
|
||||
r.price, r.method, ni.invoice_id, r.name_prepaid_code_id, r.label, r.secret, r.contact_link, r.channel_link, r.intent_nonce, r.intent_deadline,
|
||||
r.intent_signature, r.commit_tx, r.commit_block, r.register_tx, r.register_block, r.reveal_after, r.reveal_before, r.expires_at, r.registered_at,
|
||||
r.failed_at, r.error, r.live, r.order_hash, r.moves, r.links_refused_at, r.created_at, r.updated_at
|
||||
r.failed_at, r.error, r.live, r.order_hash, r.moves, r.links_refused_at, r.created_at, r.updated_at, r.balance_source, r.balance_used
|
||||
|]
|
||||
|
||||
registrationFrom :: Query
|
||||
@@ -371,19 +546,20 @@ type RegistrationRow =
|
||||
(Text, Int64, Binary ByteString, Int, Int64, Binary ByteString, Binary ByteString, Text, NamePhase, Int)
|
||||
:. (Int, Maybe Text, Maybe Text, Maybe Int64, Maybe Text, Maybe (Binary ByteString), Maybe Text, Maybe Text, Maybe Int64, Maybe Int64)
|
||||
:. (Maybe (Binary ByteString), Maybe (Binary ByteString), Maybe Int64, Maybe (Binary ByteString), Maybe Int64, Maybe Int64, Maybe Int64, Maybe Int64, Maybe UTCTime)
|
||||
:. (Maybe UTCTime, Maybe Text, BoolInt, Binary ByteString, Int, Maybe UTCTime, UTCTime, UTCTime)
|
||||
:. (Maybe UTCTime, Maybe Text, BoolInt, Binary ByteString, Int, Maybe UTCTime, UTCTime, UTCTime, Maybe Text, Int)
|
||||
|
||||
toRegistration :: RegistrationRow -> Either Text NameRegistration
|
||||
toRegistration
|
||||
( (rid, nrVersion, Binary lh, nrLength, duration, Binary owner, Binary nrCommitment, nrSealed, nrPhase, nrYears)
|
||||
:. (nrPrice, method_, invoiceId_, codeId_, label_, secret_, nrContactLink, nrChannelLink, nonce_, deadline_)
|
||||
:. (signature_, commitTx, commitBlock, registerTx, registerBlock, revealAfter, revealBefore, expiresAt, nrRegisteredAt)
|
||||
:. (nrFailedAt, nrError, BI nrLive, Binary nrOrderHash, nrMoves, nrLinksRefusedAt, nrCreatedAt, nrUpdatedAt)
|
||||
:. (nrFailedAt, nrError, BI nrLive, Binary nrOrderHash, nrMoves, nrLinksRefusedAt, nrCreatedAt, nrUpdatedAt, source_, nrBalanceUsed)
|
||||
) = do
|
||||
nrOwner <- decodeAddress owner
|
||||
nrPayment <- case (method_, invoiceId_, codeId_) of
|
||||
(Just m, Just invId, Nothing) -> (`RPInvoice` InvoiceId invId) <$> note ("name_registrations.method: " <> m) (textMethod m)
|
||||
(Nothing, Nothing, Just codeId) -> Right $ RPCode codeId
|
||||
(Nothing, Nothing, Nothing) | isJust source_ -> Right RPBalance
|
||||
_ -> Left $ "name_registrations payment: " <> rid
|
||||
nrReveal <- case (label_, secret_, nonce_, deadline_, signature_) of
|
||||
(Nothing, Nothing, Nothing, Nothing, Nothing) -> Right Nothing
|
||||
@@ -405,6 +581,8 @@ toRegistration
|
||||
nrYears,
|
||||
nrPrice,
|
||||
nrPayment,
|
||||
nrBalanceSource = RegistrationId <$> source_,
|
||||
nrBalanceUsed,
|
||||
nrReveal,
|
||||
nrCommitTx = txHash <$> commitTx,
|
||||
nrCommitBlock = word64 <$> commitBlock,
|
||||
@@ -458,13 +636,14 @@ unfunded = unfundedQuery "i.invoice_id"
|
||||
|
||||
-- | Run in the transaction that inserts the next order, so the unique constraints let it in; the registration's new version.
|
||||
-- Nothing when the order changed since it was read, or its invoice is no longer open, not past its expiry, or holds money: the caller rolls back,
|
||||
-- since the invoice is written before the registration, as settlement, cancel and the sweep write them.
|
||||
-- since the invoice is written before the registration, as settlement, cancel and the sweep write them. A balance it held is released.
|
||||
closeOverdue :: DB.Connection -> NameRegistration -> UTCTime -> IO (Maybe Int64)
|
||||
closeOverdue db r@NameRegistration {nrId = RegistrationId rid, nrVersion, nrPayment} now = do
|
||||
closeOverdue db r@NameRegistration {nrId = regId@(RegistrationId rid), nrVersion, nrPayment} now = do
|
||||
-- locked first, so the funding check below, a later statement, sees a payment a concurrent settlement committed
|
||||
mapM_ (\invId -> lockInvoice db invId now) $ case nrPayment of
|
||||
RPInvoice _ invId -> Just invId
|
||||
RPCode _ -> Nothing
|
||||
RPBalance -> Nothing
|
||||
expired <-
|
||||
executeChanging
|
||||
db
|
||||
@@ -482,14 +661,14 @@ closeOverdue db r@NameRegistration {nrId = RegistrationId rid, nrVersion, nrPaym
|
||||
(invoiceStatusText ISExpired, truncateToSecond now, invoiceStatusText ISOpen, rid, nrVersion, truncateToSecond now)
|
||||
if expired > 0
|
||||
then
|
||||
updateRegistration db r {nrLive = False} now <&> \case
|
||||
Written v -> Just v
|
||||
_ -> Nothing
|
||||
updateRegistration db r {nrLive = False} now >>= \case
|
||||
Written v -> Just v <$ releaseHeldBalance db regId now
|
||||
_ -> pure Nothing
|
||||
else pure Nothing
|
||||
|
||||
-- | Whether an order can still progress to a registration for its name. The unique live indexes allow one such order per commitment,
|
||||
-- and one per owner and label hash, so a wallet can order a name again once its registration is done.
|
||||
-- An unpaid order is live while its invoice is open, which nrLive carries; a taken order is final.
|
||||
-- An unpaid order is live while its invoice is open, which nrLive carries; a taken order is final, its worth kept as a balance.
|
||||
orderLive :: NameRegistration -> Bool
|
||||
orderLive NameRegistration {nrPhase, nrLive} = case nrPhase of
|
||||
PUnpaid -> nrLive
|
||||
@@ -537,11 +716,29 @@ updateRegistration db r now = do
|
||||
[(version, BI storedLive)] | version == nrVersion -> pure $ if storedLive then LiveOrderExists else NotLive
|
||||
_ -> pure VersionChanged
|
||||
|
||||
-- | Newest first, at most findLimit.
|
||||
findRegistrations :: DB.Connection -> Address -> IO [NameRegistration]
|
||||
findRegistrations db owner =
|
||||
DB.query db (selectRegistrations <> " WHERE r.owner = ? ORDER BY r.created_at DESC, r.registration_id DESC LIMIT ?") (Binary $ unAddress owner, findLimit)
|
||||
>>= decodeAll toRegistration
|
||||
-- | 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)]
|
||||
findRegistrations db owner now = do
|
||||
newest <- DB.query db (selectHeld <> " WHERE r.owner = ?" <> newestFirst <> " LIMIT ?") (holdParams :. (Binary $ unAddress owner, findLimit)) >>= decodeAll found
|
||||
holding <- DB.query db (selectHeld <> " WHERE r.owner = ?" <> withBalance <> newestFirst) (holdParams :. Only (Binary $ unAddress owner)) >>= decodeAll found
|
||||
pure $ newest <> filter ((`notElem` map (nrId . fst) newest) . nrId . fst) holding
|
||||
where
|
||||
selectHeld =
|
||||
registrationColumns
|
||||
<> ", (SELECT b.reserved_by FROM sx_badge_service_name_balances b"
|
||||
<> " JOIN sx_badge_service_name_registrations h ON h.registration_id = b.reserved_by"
|
||||
<> " JOIN sx_badge_service_name_invoices hni ON hni.registration_id = b.reserved_by"
|
||||
<> " JOIN sx_badge_service_invoices i ON i.invoice_id = hni.invoice_id"
|
||||
<> " WHERE b.registration_id = r.registration_id AND NOT ("
|
||||
<> holdOverdue
|
||||
<> "))"
|
||||
<> registrationFrom
|
||||
holdParams = (PUnpaid, invoiceStatusText ISPaid, truncateToSecond now)
|
||||
found :: RegistrationRow :. Only (Maybe Text) -> Either Text (NameRegistration, Maybe RegistrationId)
|
||||
found (row :. Only holder) = (\r -> (r, RegistrationId <$> holder)) <$> toRegistration row
|
||||
newestFirst = " ORDER BY r.created_at DESC, r.registration_id DESC"
|
||||
withBalance = " AND EXISTS (SELECT 1 FROM sx_badge_service_name_balances b WHERE b.registration_id = r.registration_id AND b.amount > 0)"
|
||||
|
||||
isLabelRegistering :: DB.Connection -> LabelHash -> IO Bool
|
||||
isLabelRegistering db (LabelHash lh) =
|
||||
@@ -573,26 +770,29 @@ unpaidCleanupCandidates db expiredBefore =
|
||||
|]
|
||||
(PUnpaid, truncateToSecond expiredBefore)
|
||||
|
||||
-- | Deletes an unpaid registration and its invoice, unless a payment was recorded for it.
|
||||
deleteUnpaidRegistration :: DB.Connection -> RegistrationId -> IO Bool
|
||||
deleteUnpaidRegistration db (RegistrationId rid) = do
|
||||
invoiceIds <- DB.query db "SELECT invoice_id FROM sx_badge_service_name_invoices WHERE registration_id = ?" (Only rid)
|
||||
deleted <-
|
||||
executeChanging
|
||||
db
|
||||
[sql|
|
||||
DELETE FROM sx_badge_service_name_registrations
|
||||
WHERE registration_id = ? AND phase = ?
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM sx_badge_service_name_invoices ni
|
||||
JOIN sx_badge_service_payments p ON p.invoice_id = ni.invoice_id
|
||||
WHERE ni.registration_id = ?
|
||||
)
|
||||
|]
|
||||
(rid, PUnpaid, rid)
|
||||
when (deleted > 0) $
|
||||
mapM_ (DB.execute db "DELETE FROM sx_badge_service_invoices WHERE invoice_id = ?" . Only . fromOnly) (invoiceIds :: [Only Text])
|
||||
pure $ deleted > 0
|
||||
-- | Deletes an unpaid registration and its invoice, unless a payment was recorded for it or it holds a balance.
|
||||
deleteUnpaidRegistration :: DB.Connection -> RegistrationId -> IO (Either CleanupKept ())
|
||||
deleteUnpaidRegistration db (RegistrationId rid) =
|
||||
DB.query db "SELECT registration_id FROM sx_badge_service_name_balances WHERE reserved_by = ?" (Only rid) >>= \case
|
||||
Only source : _ -> pure $ Left $ CKHolder $ RegistrationId source
|
||||
[] -> do
|
||||
invoiceIds <- DB.query db "SELECT invoice_id FROM sx_badge_service_name_invoices WHERE registration_id = ?" (Only rid)
|
||||
deleted <-
|
||||
executeChanging
|
||||
db
|
||||
[sql|
|
||||
DELETE FROM sx_badge_service_name_registrations
|
||||
WHERE registration_id = ? AND phase = ?
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM sx_badge_service_name_invoices ni
|
||||
JOIN sx_badge_service_payments p ON p.invoice_id = ni.invoice_id
|
||||
WHERE ni.registration_id = ?
|
||||
)
|
||||
|]
|
||||
(rid, PUnpaid, rid)
|
||||
if deleted > 0
|
||||
then Right () <$ mapM_ (DB.execute db "DELETE FROM sx_badge_service_invoices WHERE invoice_id = ?" . Only . fromOnly) (invoiceIds :: [Only Text])
|
||||
else pure $ Left CKPaid
|
||||
|
||||
-- | Code orders failed before the cutoff that still hold their unspent code.
|
||||
failedCodeOrdersBefore :: DB.Connection -> UTCTime -> IO [(RegistrationId, Int64)]
|
||||
@@ -609,6 +809,335 @@ failedCodeOrdersBefore db cutoff =
|
||||
|]
|
||||
(PFailed, truncateToSecond cutoff)
|
||||
|
||||
-- | The hold, unless it is overdue, which reads as none.
|
||||
heldBy :: Balance -> Maybe BalanceHold
|
||||
heldBy Balance {blHold} = case blHold of
|
||||
Just BalanceHold {bhOverdue = False} -> blHold
|
||||
_ -> Nothing
|
||||
|
||||
-- | A holder h with invoice i is overdue as getLiveOrders reads an order overdue: its invoice past its expiry, not paid, and holding no money.
|
||||
-- Takes the unpaid phase, the paid status and the time.
|
||||
holdOverdue :: Query
|
||||
holdOverdue = " h.phase = ? AND i.status <> ? AND i.expires_at < ?" <> unfunded
|
||||
|
||||
getBalance :: DB.Connection -> RegistrationId -> UTCTime -> IO (Maybe Balance)
|
||||
getBalance db (RegistrationId rid) now =
|
||||
firstDecoded toBalance $
|
||||
DB.query
|
||||
db
|
||||
( "SELECT b.registration_id, b.amount, b.credited, b.refunded, b.reserved_by, i.expires_at,"
|
||||
<> " CASE WHEN"
|
||||
<> holdOverdue
|
||||
<> " THEN 1 ELSE 0 END, CASE WHEN i.invoice_id IS NOT NULL"
|
||||
<> unfunded
|
||||
<> " THEN 0 ELSE 1 END, b.refunded_at"
|
||||
<> " FROM sx_badge_service_name_balances b"
|
||||
<> " LEFT JOIN sx_badge_service_name_registrations h ON h.registration_id = b.reserved_by"
|
||||
<> " LEFT JOIN sx_badge_service_name_invoices ni ON ni.registration_id = b.reserved_by"
|
||||
<> " LEFT JOIN sx_badge_service_invoices i ON i.invoice_id = ni.invoice_id"
|
||||
<> " WHERE b.registration_id = ?"
|
||||
)
|
||||
(PUnpaid, invoiceStatusText ISPaid, truncateToSecond now, rid)
|
||||
|
||||
toBalance :: (Text, Int, Int, Int, Maybe Text, Maybe UTCTime, BoolInt, BoolInt, Maybe UTCTime) -> Either Text Balance
|
||||
toBalance (rid, blAmount, blCredited, blRefunded, holder_, until_, BI bhOverdue, BI bhFunded, blRefundedAt) = do
|
||||
blHold <- case (holder_, until_) of
|
||||
(Nothing, _) -> Right Nothing
|
||||
(Just holder, Just bhUntil) -> Right $ Just BalanceHold {bhHolder = RegistrationId holder, bhUntil, bhOverdue, bhFunded}
|
||||
(Just _, Nothing) -> Left $ "name_balances holder without an invoice: " <> rid
|
||||
pure Balance {blRegistration = RegistrationId rid, blAmount, blCredited, blRefunded, blHold, blRefundedAt}
|
||||
|
||||
-- | The order holding the balance, when its hold is overdue, for the next spend to close.
|
||||
overdueHolder :: DB.Connection -> RegistrationId -> UTCTime -> IO (Maybe NameRegistration)
|
||||
overdueHolder db rid now =
|
||||
getBalance db rid now >>= \case
|
||||
Just Balance {blHold = Just BalanceHold {bhHolder, bhOverdue = True}} -> getRegistration db bhHolder
|
||||
_ -> pure Nothing
|
||||
|
||||
-- | The order a support reference names, by its registration id or its name invoice's id, with its balance.
|
||||
balanceByReference :: DB.Connection -> Text -> UTCTime -> IO (Maybe (RegistrationId, Maybe Balance))
|
||||
balanceByReference db ref now =
|
||||
DB.query
|
||||
db
|
||||
"SELECT registration_id FROM sx_badge_service_name_registrations WHERE registration_id = ? UNION ALL SELECT registration_id FROM sx_badge_service_name_invoices WHERE invoice_id = ?"
|
||||
(ref, ref)
|
||||
>>= \case
|
||||
Only rid : _ -> (\balance -> Just (RegistrationId rid, balance)) <$> getBalance db (RegistrationId rid) now
|
||||
[] -> pure Nothing
|
||||
|
||||
-- | From the order back along balance_source to the first, following it only from orders past unpaid.
|
||||
balanceChain :: DB.Connection -> RegistrationId -> IO [BalanceLink]
|
||||
balanceChain db rid =
|
||||
getRegistration db rid >>= \case
|
||||
Nothing -> pure []
|
||||
Just NameRegistration {nrPhase, nrPayment, nrBalanceSource, nrBalanceUsed} -> do
|
||||
let pastUnpaid = nrPhase /= PUnpaid
|
||||
lkPaid <- case nrPayment of
|
||||
RPInvoice _ (InvoiceId invId) | pastUnpaid -> maybe 0 fromOnly . listToMaybe <$> (DB.query db "SELECT amount FROM sx_badge_service_invoices WHERE invoice_id = ?" (Only invId) :: IO [Only Int])
|
||||
_ -> pure 0
|
||||
lkLateCredits <- case nrPayment of
|
||||
RPInvoice _ invId -> lateCredits db invId
|
||||
_ -> pure []
|
||||
let link = BalanceLink {lkRegistration = rid, lkPayment = nrPayment, lkPaid, lkFromBalance = if pastUnpaid then nrBalanceUsed else 0, lkLateCredits}
|
||||
(link :) <$> maybe (pure []) (balanceChain db) (if pastUnpaid then nrBalanceSource else Nothing)
|
||||
|
||||
lateCredits :: DB.Connection -> InvoiceId -> IO [LateCredit]
|
||||
lateCredits db (InvoiceId invId) =
|
||||
map toLateCredit
|
||||
<$> DB.query
|
||||
db
|
||||
"SELECT invoice_id, credit_no, registration_id, units, invoice_rate, current_rate, rate_used, cents FROM sx_badge_service_name_late_credits WHERE invoice_id = ? ORDER BY credit_no"
|
||||
(Only invId)
|
||||
where
|
||||
toLateCredit (inv, lcCreditNo, reg, lcUnits, lcInvoiceRate, lcCurrentRate, lcRateUsed, lcCents) =
|
||||
LateCredit {lcInvoice = InvoiceId inv, lcCreditNo, lcRegistration = RegistrationId reg, lcUnits, lcInvoiceRate, lcCurrentRate, lcRateUsed, lcCents}
|
||||
|
||||
-- | Adds to the order's balance, making it on its first credit.
|
||||
creditBalance :: DB.Connection -> RegistrationId -> Int -> UTCTime -> IO ()
|
||||
creditBalance db (RegistrationId rid) cents now' =
|
||||
DB.execute
|
||||
db
|
||||
[sql|
|
||||
INSERT INTO sx_badge_service_name_balances (registration_id, amount, credited, refunded, created_at, updated_at)
|
||||
VALUES (?,?,?,0,?,?)
|
||||
ON CONFLICT (registration_id) DO UPDATE SET
|
||||
amount = sx_badge_service_name_balances.amount + excluded.amount,
|
||||
credited = sx_badge_service_name_balances.credited + excluded.credited,
|
||||
updated_at = excluded.updated_at
|
||||
|]
|
||||
(rid, cents, cents, now, now)
|
||||
where
|
||||
now = truncateToSecond now'
|
||||
|
||||
-- | The price, above 0, spent at once, where the amount is the one seen and nothing holds it.
|
||||
spendBalance :: DB.Connection -> RegistrationId -> Int -> Int -> UTCTime -> IO Bool
|
||||
spendBalance db (RegistrationId rid) price seen now =
|
||||
(> 0)
|
||||
<$> executeChanging
|
||||
db
|
||||
"UPDATE sx_badge_service_name_balances SET amount = amount - ?, updated_at = ? WHERE registration_id = ? AND amount = ? AND amount >= ? AND ? > 0 AND reserved_by IS NULL"
|
||||
(price, now, rid, seen, price, price)
|
||||
|
||||
-- | Held by a difference order, where the amount is the one seen, above 0, and nothing holds it.
|
||||
holdBalance :: DB.Connection -> RegistrationId -> Int -> RegistrationId -> UTCTime -> IO Bool
|
||||
holdBalance db (RegistrationId rid) seen (RegistrationId holder) now =
|
||||
(> 0)
|
||||
<$> executeChanging
|
||||
db
|
||||
"UPDATE sx_badge_service_name_balances SET reserved_by = ?, updated_at = ? WHERE registration_id = ? AND amount = ? AND ? > 0 AND reserved_by IS NULL"
|
||||
(holder, now, rid, seen, seen)
|
||||
|
||||
-- | The holder's hold spent and cleared, where this holder holds the balance and it still has the cents, above 0.
|
||||
spendHeldBalance :: DB.Connection -> RegistrationId -> Int -> UTCTime -> IO Bool
|
||||
spendHeldBalance db (RegistrationId holder) used now =
|
||||
(> 0)
|
||||
<$> executeChanging
|
||||
db
|
||||
"UPDATE sx_badge_service_name_balances SET amount = amount - ?, reserved_by = NULL, updated_at = ? WHERE reserved_by = ? AND amount >= ? AND ? > 0"
|
||||
(used, truncateToSecond now, holder, used, used)
|
||||
|
||||
releaseHeldBalance :: DB.Connection -> RegistrationId -> UTCTime -> IO Bool
|
||||
releaseHeldBalance db (RegistrationId holder) now =
|
||||
(> 0)
|
||||
<$> executeChanging
|
||||
db
|
||||
"UPDATE sx_badge_service_name_balances SET reserved_by = NULL, updated_at = ? WHERE reserved_by = ?"
|
||||
(truncateToSecond now, holder)
|
||||
|
||||
-- | All of the balance, where it is the cents given, above 0, and nothing holds it; refunded counts every refund.
|
||||
refundBalance :: DB.Connection -> RegistrationId -> Int -> UTCTime -> IO Bool
|
||||
refundBalance db (RegistrationId rid) cents now' =
|
||||
(> 0)
|
||||
<$> executeChanging
|
||||
db
|
||||
[sql|
|
||||
UPDATE sx_badge_service_name_balances SET amount = 0, refunded = refunded + ?, refunded_at = ?, updated_at = ?
|
||||
WHERE registration_id = ? AND amount = ? AND amount > 0 AND reserved_by IS NULL
|
||||
|]
|
||||
(cents, now, now, rid, cents)
|
||||
where
|
||||
now = truncateToSecond now'
|
||||
|
||||
-- | A name invoice with its order, its invoice row and its payment row.
|
||||
lateFrom :: Query
|
||||
lateFrom =
|
||||
" FROM sx_badge_service_name_invoices ni"
|
||||
<> " JOIN sx_badge_service_name_registrations r ON r.registration_id = ni.registration_id"
|
||||
<> " JOIN sx_badge_service_invoices i ON i.invoice_id = ni.invoice_id"
|
||||
<> " JOIN sx_badge_service_payments p ON p.invoice_id = ni.invoice_id"
|
||||
|
||||
-- | Its order closed unpaid, whatever the invoice's status, since settlement queues only a live order; takes the unpaid phase.
|
||||
closedUnpaid :: Query
|
||||
closedUnpaid = " r.phase = ? AND r.live = 0"
|
||||
|
||||
cardInvoice :: Query
|
||||
cardInvoice = " i.payment_crypto_currency IS NULL"
|
||||
|
||||
cryptoInvoice :: Query
|
||||
cryptoInvoice = " i.payment_crypto_currency IS NOT NULL"
|
||||
|
||||
-- | No credit rows sum to 0, not NULL.
|
||||
creditedTotal :: Query -> Query
|
||||
creditedTotal column = " (SELECT " <> integerSum ("COALESCE(SUM(c." <> column <> "), 0)") <> " FROM sx_badge_service_name_late_credits c WHERE c.invoice_id = ni.invoice_id)"
|
||||
|
||||
integerSum :: Query -> Query
|
||||
#if defined(dbPostgres)
|
||||
-- Postgres sums a BIGINT as NUMERIC, which does not decode into an integer
|
||||
integerSum s = "CAST(" <> s <> " AS BIGINT)"
|
||||
#else
|
||||
integerSum = id
|
||||
#endif
|
||||
|
||||
-- | The first alert's old marks are NULL, which = never matches.
|
||||
notDistinctFrom :: Query
|
||||
#if defined(dbPostgres)
|
||||
notDistinctFrom = " IS NOT DISTINCT FROM "
|
||||
#else
|
||||
notDistinctFrom = " IS "
|
||||
#endif
|
||||
|
||||
-- | Confirmed money not all credited: cents for card, units for crypto.
|
||||
uncreditedMoney :: Query
|
||||
uncreditedMoney =
|
||||
" ((" <> cardInvoice <> " AND p.confirmed_amount >" <> creditedTotal "cents" <> ")"
|
||||
<> " OR (" <> cryptoInvoice <> " AND p.confirmed_units >" <> creditedTotal "units" <> "))"
|
||||
|
||||
-- | Why a closed order's money is not all credited, by the first case that holds, else NULL.
|
||||
-- Confirmed money waiting comes first, so its alert never asks for a refund by hand.
|
||||
pendingCase :: Query
|
||||
pendingCase =
|
||||
" CASE WHEN" <> uncreditedMoney <> " THEN " <> literal LPUncredited
|
||||
<> " WHEN COALESCE(p.amount, 0) = 0 AND (p.crypto_paid IS NOT NULL OR p.paid_in_full = 1) THEN " <> literal LPConfirming
|
||||
<> " WHEN" <> cardInvoice <> " AND COALESCE(p.amount, 0) > p.confirmed_amount THEN " <> literal LPUnconfirmed
|
||||
<> " WHEN p.received_units > COALESCE(p.confirmed_units, 0) THEN " <> literal LPUnconfirmed
|
||||
<> " WHEN" <> cryptoInvoice <> " AND p.received_units IS NULL AND COALESCE(p.amount, 0) > 0 THEN " <> literal LPUncounted
|
||||
<> " END"
|
||||
where
|
||||
literal p = fromString $ "'" <> T.unpack (textEncode p) <> "'"
|
||||
|
||||
-- | What an alert names as received: units for crypto, and cents for card or for crypto that could not be counted in units.
|
||||
receivedFigure :: Query
|
||||
receivedFigure = " CASE WHEN" <> cardInvoice <> " THEN p.amount ELSE COALESCE(p.received_units, p.amount) END"
|
||||
|
||||
lateColumns :: Query
|
||||
lateColumns =
|
||||
"SELECT ni.invoice_id, ni.registration_id, r.phase, r.live, i.payment_crypto_currency, ni.late_support, COALESCE(p.amount, 0), p.confirmed_amount,"
|
||||
<> " p.received_units, p.confirmed_units, p.invoice_rate,"
|
||||
<> creditedTotal "units"
|
||||
<> ","
|
||||
<> creditedTotal "cents"
|
||||
<> ", (SELECT COUNT(*) FROM sx_badge_service_name_late_credits c WHERE c.invoice_id = ni.invoice_id), p.created_at"
|
||||
|
||||
type LateRow = (Text, Text, NamePhase, BoolInt, Maybe Text, Maybe LateSupport, Int, Int, Maybe Int64, Maybe Int64) :. (Maybe Text, Int64, Int, Int, UTCTime)
|
||||
|
||||
toLateState :: LateRow -> Either Text LateCreditState
|
||||
toLateState
|
||||
( (inv, reg, lsPhase, BI lsLive, coin_, lsSupport, lsReceivedCents, lsConfirmedCents, lsReceivedUnits, lsConfirmedUnits)
|
||||
:. (lsInvoiceRate, lsCreditedUnits, lsCreditedCents, lsCredits, lsPaymentCreatedAt)
|
||||
) = do
|
||||
lsCoin <- traverse (\c -> note ("invoices.payment_crypto_currency: " <> c) (textToCryptoCurrency c)) coin_
|
||||
pure LateCreditState {lsInvoice = InvoiceId inv, lsRegistration = RegistrationId reg, lsPhase, lsLive, lsCoin, lsSupport, lsReceivedCents, lsConfirmedCents, lsReceivedUnits, lsConfirmedUnits, lsInvoiceRate, lsCreditedUnits, lsCreditedCents, lsCredits, lsPaymentCreatedAt}
|
||||
|
||||
-- | Nothing without a payment row.
|
||||
lateCreditState :: DB.Connection -> InvoiceId -> IO (Maybe LateCreditState)
|
||||
lateCreditState db (InvoiceId invId) = firstDecoded toLateState $ DB.query db (lateColumns <> lateFrom <> " WHERE ni.invoice_id = ?") (Only invId)
|
||||
|
||||
-- | Run after the invoice's lock. The order's balance is credited only when the credit's row is new, so a taken credit number changes neither.
|
||||
creditLatePayment :: DB.Connection -> LateCredit -> UTCTime -> IO Bool
|
||||
creditLatePayment db LateCredit {lcInvoice = InvoiceId invId, lcCreditNo, lcRegistration = regId@(RegistrationId rid), lcUnits, lcInvoiceRate, lcCurrentRate, lcRateUsed, lcCents} now' = do
|
||||
inserted <-
|
||||
executeChanging
|
||||
db
|
||||
[sql|
|
||||
INSERT INTO sx_badge_service_name_late_credits (invoice_id, credit_no, registration_id, units, invoice_rate, current_rate, rate_used, cents, created_at)
|
||||
VALUES (?,?,?,?,?,?,?,?,?)
|
||||
ON CONFLICT DO NOTHING
|
||||
|]
|
||||
(invId, lcCreditNo, rid, lcUnits, lcInvoiceRate, lcCurrentRate, lcRateUsed, lcCents, now)
|
||||
when (inserted > 0) $ creditBalance db regId lcCents now
|
||||
pure $ inserted > 0
|
||||
where
|
||||
now = truncateToSecond now'
|
||||
|
||||
-- | Why the closed order's money on the invoice is not all credited; the one rule of the pending log and the alert.
|
||||
latePending :: DB.Connection -> InvoiceId -> IO (Maybe LatePending)
|
||||
latePending db (InvoiceId invId) =
|
||||
maybe Nothing fromOnly . listToMaybe
|
||||
<$> DB.query db ("SELECT" <> pendingCase <> lateFrom <> " WHERE ni.invoice_id = ? AND" <> closedUnpaid) (invId, PUnpaid)
|
||||
|
||||
-- | Nothing once all of the closed order's money is credited, whatever support reason was given before.
|
||||
lateWait :: DB.Connection -> InvoiceId -> IO (Maybe LateWait)
|
||||
lateWait db (InvoiceId invId) =
|
||||
maybe Nothing waitOf . listToMaybe
|
||||
<$> DB.query db ("SELECT" <> pendingCase <> ", ni.late_support" <> lateFrom <> " WHERE ni.invoice_id = ? AND" <> closedUnpaid) (invId, PUnpaid)
|
||||
where
|
||||
waitOf :: (Maybe LatePending, Maybe LateSupport) -> Maybe LateWait
|
||||
waitOf = \case
|
||||
(Nothing, _) -> Nothing
|
||||
(Just _, Just _) -> Just LWSupport
|
||||
(Just LPUncounted, Nothing) -> Just LWSupport
|
||||
(Just LPUncredited, Nothing) -> Just LWCrediting
|
||||
(Just LPConfirming, Nothing) -> Just LWConfirming
|
||||
(Just LPUnconfirmed, Nothing) -> Just LWConfirming
|
||||
|
||||
-- | Closed orders' invoices with confirmed money not all credited, for the poller's credit pass; none a rate below the floor sent to support.
|
||||
uncreditedLateInvoices :: DB.Connection -> IO [InvoiceId]
|
||||
uncreditedLateInvoices db =
|
||||
map (InvoiceId . fromOnly)
|
||||
<$> DB.query
|
||||
db
|
||||
("SELECT ni.invoice_id" <> lateFrom <> " WHERE" <> closedUnpaid <> " AND" <> uncreditedMoney <> " AND (ni.late_support IS NULL OR ni.late_support <> ?) ORDER BY p.created_at, ni.invoice_id")
|
||||
(PUnpaid, LSRateFloor)
|
||||
|
||||
-- | Pending money whose payment row was created before the cutoff, never alerted, or alerted for less money than now received.
|
||||
lateAlertDue :: DB.Connection -> UTCTime -> IO [LateAlert]
|
||||
lateAlertDue db cutoff =
|
||||
DB.query
|
||||
db
|
||||
( lateColumns
|
||||
<> ","
|
||||
<> pendingCase
|
||||
<> ","
|
||||
<> receivedFigure
|
||||
<> ", ni.late_alerted_at, ni.late_alerted_units"
|
||||
<> lateFrom
|
||||
<> " WHERE"
|
||||
<> closedUnpaid
|
||||
<> " AND p.created_at < ? AND"
|
||||
<> pendingCase
|
||||
<> " IS NOT NULL AND (ni.late_alerted_at IS NULL OR"
|
||||
<> receivedFigure
|
||||
<> " > COALESCE(ni.late_alerted_units, -1)) ORDER BY p.created_at, ni.invoice_id"
|
||||
)
|
||||
(PUnpaid, truncateToSecond cutoff)
|
||||
>>= decodeAll toAlert
|
||||
where
|
||||
toAlert :: LateRow :. (Maybe LatePending, Maybe Int64, Maybe UTCTime, Maybe Int64) -> Either Text LateAlert
|
||||
toAlert (row :. (pending_, laReceived, laAlertedAt, laAlertedReceived)) = case pending_ of
|
||||
Just laPending -> (\laState -> LateAlert {laState, laPending, laReceived, laAlertedAt, laAlertedReceived}) <$> toLateState row
|
||||
Nothing -> Left "name invoice alert without pending money"
|
||||
|
||||
-- | Marks the alert sent, with the support reason it gives unless one is set, unless another instance marked it since it was read;
|
||||
-- only the instance that marks it logs it.
|
||||
claimLateAlert :: DB.Connection -> LateAlert -> Maybe LateSupport -> UTCTime -> IO Bool
|
||||
claimLateAlert db LateAlert {laState = LateCreditState {lsInvoice = InvoiceId invId}, laReceived, laAlertedAt, laAlertedReceived} support now =
|
||||
(> 0)
|
||||
<$> executeChanging
|
||||
db
|
||||
( "UPDATE sx_badge_service_name_invoices SET late_alerted_at = ?, late_alerted_units = ?, late_support = COALESCE(late_support, ?)"
|
||||
<> " WHERE invoice_id = ? AND late_alerted_at"
|
||||
<> notDistinctFrom
|
||||
<> "? AND late_alerted_units"
|
||||
<> notDistinctFrom
|
||||
<> "?"
|
||||
)
|
||||
(truncateToSecond now, laReceived, support, invId, laAlertedAt, laAlertedReceived)
|
||||
|
||||
-- | The first reason given stays.
|
||||
setLateSupport :: DB.Connection -> InvoiceId -> LateSupport -> IO ()
|
||||
setLateSupport db (InvoiceId invId) support =
|
||||
DB.execute db "UPDATE sx_badge_service_name_invoices SET late_support = COALESCE(late_support, ?) WHERE invoice_id = ?" (support, invId)
|
||||
|
||||
insertPrepaidCode :: DB.Connection -> NewPrepaidCode -> UTCTime -> IO (Either CodeHashTaken Int64)
|
||||
insertPrepaidCode db NewPrepaidCode {npcCodeHash, npcMinLength, npcYears, npcPaymentStatus, npcExpiresAt} now = do
|
||||
inserted <-
|
||||
|
||||
@@ -1,29 +1,32 @@
|
||||
{-# LANGUAGE NamedFieldPuns #-}
|
||||
|
||||
-- | A thread that takes a turn it already holds waits forever. Label turns are taken before a code turn.
|
||||
module StoreService.Names.Turns (Turns, newTurns, withLabelTurn, withCodeTurn, turnsCount, labelTurnCount) where
|
||||
-- | A thread that takes a turn it already holds waits forever. Label turns are taken before a code turn or a balance turn,
|
||||
-- and a balance turn is never taken with a code turn.
|
||||
module StoreService.Names.Turns (Turns, newTurns, withLabelTurn, withCodeTurn, withBalanceTurn, turnsCount, labelTurnCount, balanceTurnCount) where
|
||||
|
||||
import Control.Concurrent.STM
|
||||
import Control.Exception (bracket, bracket_)
|
||||
import Data.ByteString (ByteString)
|
||||
import Data.Map.Strict (Map)
|
||||
import qualified Data.Map.Strict as Map
|
||||
import Data.Text.Encoding (encodeUtf8)
|
||||
import Simplex.Messaging.SimplexName (LabelHash (..))
|
||||
import StoreService.Names.Phases (RegistrationId (..))
|
||||
|
||||
-- | Each lock counts the requests holding or waiting for it, and its entry goes when none are left.
|
||||
type TurnLocks = TVar (Map ByteString (TMVar (), Int))
|
||||
|
||||
data Turns = Turns {labelTurns :: TurnLocks, codeTurns :: TurnLocks}
|
||||
data Turns = Turns {labelTurns :: TurnLocks, codeTurns :: TurnLocks, balanceTurns :: TurnLocks}
|
||||
|
||||
newTurns :: IO Turns
|
||||
newTurns = Turns <$> newTVarIO Map.empty <*> newTVarIO Map.empty
|
||||
newTurns = Turns <$> newTVarIO Map.empty <*> newTVarIO Map.empty <*> newTVarIO Map.empty
|
||||
|
||||
withLabelTurn :: Turns -> LabelHash -> IO a -> IO a
|
||||
withLabelTurn Turns {labelTurns} (LabelHash h) = withTurn labelTurns h
|
||||
|
||||
-- | The label and code hashes with a holder or a waiter.
|
||||
-- | The label hashes, code hashes and balances with a holder or a waiter.
|
||||
turnsCount :: Turns -> IO Int
|
||||
turnsCount Turns {labelTurns, codeTurns} = atomically $ (+) <$> (Map.size <$> readTVar labelTurns) <*> (Map.size <$> readTVar codeTurns)
|
||||
turnsCount Turns {labelTurns, codeTurns, balanceTurns} = atomically $ sum <$> mapM (fmap Map.size . readTVar) [labelTurns, codeTurns, balanceTurns]
|
||||
|
||||
-- | The requests holding or waiting for the label hash's turn.
|
||||
labelTurnCount :: Turns -> LabelHash -> STM Int
|
||||
@@ -33,6 +36,17 @@ labelTurnCount Turns {labelTurns} (LabelHash h) = maybe 0 snd . Map.lookup h <$>
|
||||
withCodeTurn :: Turns -> ByteString -> IO a -> IO a
|
||||
withCodeTurn Turns {codeTurns} = withTurn codeTurns
|
||||
|
||||
-- | Keyed by the order the balance belongs to.
|
||||
withBalanceTurn :: Turns -> RegistrationId -> IO a -> IO a
|
||||
withBalanceTurn Turns {balanceTurns} = withTurn balanceTurns . balanceKey
|
||||
|
||||
-- | The requests holding or waiting for the balance's turn.
|
||||
balanceTurnCount :: Turns -> RegistrationId -> STM Int
|
||||
balanceTurnCount Turns {balanceTurns} rid = maybe 0 snd . Map.lookup (balanceKey rid) <$> readTVar balanceTurns
|
||||
|
||||
balanceKey :: RegistrationId -> ByteString
|
||||
balanceKey (RegistrationId rid) = encodeUtf8 rid
|
||||
|
||||
withTurn :: TurnLocks -> ByteString -> IO a -> IO a
|
||||
withTurn locks key action =
|
||||
bracket (atomically enter) (const $ atomically leave) $ \lock ->
|
||||
|
||||
@@ -7,6 +7,7 @@ module StoreService.Names.View
|
||||
registrationView,
|
||||
readViewChain,
|
||||
viewJSON,
|
||||
balanceJSON,
|
||||
addressText,
|
||||
tldText,
|
||||
registrationAt,
|
||||
@@ -35,7 +36,7 @@ import StoreService.Names.Abi (hex)
|
||||
import StoreService.Names.Chain (TxHash (..))
|
||||
import StoreService.Names.Contracts (Contracts, sponsorNonce)
|
||||
import StoreService.Names.Phases (RegistrationId (..))
|
||||
import StoreService.Names.Store (NamePhase (..), NameRegistration (..), NameReveal (..), getRegistration)
|
||||
import StoreService.Names.Store (Balance (..), BalanceHold (..), LateWait (..), NamePhase (..), NameRegistration (..), NameReveal (..), RegistrationPayment (..), getBalance, getRegistration, heldBy, lateWait)
|
||||
|
||||
-- | The view's chain reads; a field whose read failed is null and named in vrUnread.
|
||||
data ViewReads = ViewReads
|
||||
@@ -44,8 +45,16 @@ data ViewReads = ViewReads
|
||||
}
|
||||
deriving (Eq, Show)
|
||||
|
||||
registrationView :: DBStore -> NamesConfig -> Contracts -> NameRegistration -> IO J.Value
|
||||
registrationView _ cfg ct r = viewJSON cfg r <$> readViewChain ct r
|
||||
-- | The balance as it reads at the given time, when a hold may have become overdue, and what a closed order's late money waits on.
|
||||
registrationView :: DBStore -> NamesConfig -> Contracts -> UTCTime -> NameRegistration -> IO J.Value
|
||||
registrationView st cfg ct now r = do
|
||||
(balance, late) <- withTransaction st $ \db -> do
|
||||
balance <- getBalance db (nrId r) now
|
||||
late <- case nrPayment r of
|
||||
RPInvoice _ invId -> lateWait db invId
|
||||
_ -> pure Nothing
|
||||
pure (balance, late)
|
||||
viewJSON cfg r balance late <$> readViewChain ct r
|
||||
|
||||
-- | The intent nonce only in committed.
|
||||
readViewChain :: Contracts -> NameRegistration -> IO ViewReads
|
||||
@@ -57,8 +66,8 @@ readViewChain ct NameRegistration {nrPhase, nrOwner} = case nrPhase of
|
||||
where
|
||||
none = ViewReads {vrIntentNonce = Nothing, vrUnread = []}
|
||||
|
||||
viewJSON :: NamesConfig -> NameRegistration -> ViewReads -> J.Value
|
||||
viewJSON NamesConfig {nTLD, nChain = ChainConfig {cChainId, cResolver, cSponsor}} r ViewReads {vrIntentNonce, vrUnread} =
|
||||
viewJSON :: NamesConfig -> NameRegistration -> Maybe Balance -> Maybe LateWait -> ViewReads -> J.Value
|
||||
viewJSON NamesConfig {nTLD, nChain = ChainConfig {cChainId, cResolver, cSponsor}} r balance late ViewReads {vrIntentNonce, vrUnread} =
|
||||
J.object
|
||||
[ "id" .= rid,
|
||||
"version" .= nrVersion,
|
||||
@@ -77,6 +86,9 @@ viewJSON NamesConfig {nTLD, nChain = ChainConfig {cChainId, cResolver, cSponsor}
|
||||
"years" .= nrYears,
|
||||
"duration" .= nrDuration,
|
||||
"price" .= nrPrice,
|
||||
"fromBalance" .= nrBalanceUsed,
|
||||
"balance" .= (balanceJSON <$> balance),
|
||||
"latePayment" .= ((\w -> J.object ["waiting" .= waitingText w]) <$> late),
|
||||
"commitTx" .= (txText <$> nrCommitTx),
|
||||
"registerTx" .= (txText <$> nrRegisterTx),
|
||||
"revealAfter" .= nrRevealAfter,
|
||||
@@ -88,8 +100,21 @@ viewJSON NamesConfig {nTLD, nChain = ChainConfig {cChainId, cResolver, cSponsor}
|
||||
]
|
||||
where
|
||||
NameRegistration {nrId = RegistrationId rid, nrVersion, nrMoves, nrLinksRefusedAt, nrPhase, nrLabelHash = LabelHash lh, nrReveal, nrOwner, nrCommitment, nrSealed} = r
|
||||
NameRegistration {nrYears, nrDuration, nrPrice, nrCommitTx, nrRegisterTx, nrRevealAfter, nrRevealBefore, nrExpiresAt, nrError} = r
|
||||
NameRegistration {nrYears, nrDuration, nrPrice, nrBalanceUsed, nrCommitTx, nrRegisterTx, nrRevealAfter, nrRevealBefore, nrExpiresAt, nrError} = r
|
||||
txText (TxHash h) = hex h
|
||||
waitingText :: LateWait -> Text
|
||||
waitingText = \case
|
||||
LWConfirming -> "confirming"
|
||||
LWCrediting -> "crediting"
|
||||
LWSupport -> "support"
|
||||
|
||||
-- | The holder is not named, so an order's link discloses no other order. A funded hold has no end time.
|
||||
balanceJSON :: Balance -> J.Value
|
||||
balanceJSON b@Balance {blAmount, blRefunded} =
|
||||
J.object ["amount" .= blAmount, "held" .= isJust hold, "heldUntil" .= (bhUntil <$> (hold >>= unfunded)), "refunded" .= blRefunded]
|
||||
where
|
||||
hold = heldBy b
|
||||
unfunded h@BalanceHold {bhFunded} = if bhFunded then Nothing else Just h
|
||||
|
||||
-- | EIP-55, as the page compares owners.
|
||||
addressText :: Address -> Text
|
||||
|
||||
@@ -49,7 +49,7 @@ import StoreService.Names.Reveal (intentOf)
|
||||
import StoreService.Names.Revert (RevertName (..))
|
||||
import StoreService.Names.Sender (PendingTx, SendError (..), Sender, awaitOutcome, inFlightTransaction, ptHash, submitTransaction)
|
||||
import StoreService.Names.Store
|
||||
import StoreService.Names.Turns (withLabelTurn)
|
||||
import StoreService.Names.Turns (withBalanceTurn, withLabelTurn)
|
||||
import StoreService.Names.View (lapseMoment, notSignedInTime, registrationAt, registrationVersion)
|
||||
|
||||
data Worker = Worker
|
||||
@@ -323,13 +323,16 @@ judge w@Worker {wkOrders = oe@OrdersEnv {oeContracts}} now r@NameRegistration {n
|
||||
| otherwise -> failed w now r reason
|
||||
Nothing -> failed w now r reason
|
||||
|
||||
-- | The payment is kept, and a code order's code released.
|
||||
-- | A paid order keeps its whole price as a balance of its own, credited in the taken write's transaction, registration before balance,
|
||||
-- in the balance's turn after the name's; a code order's code is released.
|
||||
taken :: Worker -> UTCTime -> NameRegistration -> IO (Maybe Int64, Next)
|
||||
taken Worker {wkOrders = OrdersEnv {oeStore, oeTurns}} now r@NameRegistration {nrId, nrPayment} = case nrPayment of
|
||||
RPInvoice {} -> written r <$> withTransaction oeStore write
|
||||
taken Worker {wkOrders = OrdersEnv {oeStore, oeTurns}} now r@NameRegistration {nrId, nrPayment, nrPrice} = case nrPayment of
|
||||
RPInvoice {} -> credited
|
||||
RPBalance -> credited
|
||||
RPCode codeId -> written r . fmap fst <$> releaseCode oeTurns oeStore codeId nrId write
|
||||
where
|
||||
write db = versionWritten <$> updateRegistration db r {nrPhase = PTaken, nrError = Nothing} now
|
||||
credited = written r <$> withBalanceTurn oeTurns nrId (withTransaction oeStore $ \db -> write db >>= traverse (\v -> v <$ creditBalance db nrId nrPrice now))
|
||||
|
||||
-- | A code order keeps its code for Try again.
|
||||
failed :: Worker -> UTCTime -> NameRegistration -> Maybe RevertName -> IO (Maybe Int64, Next)
|
||||
@@ -396,6 +399,7 @@ retryRegistration oe@OrdersEnv {oeNow} current = do
|
||||
retryCode :: OrdersEnv -> UTCTime -> NameRegistration -> IO (Either CodeRefusal (Maybe PrepaidCode))
|
||||
retryCode OrdersEnv {oeStore} now NameRegistration {nrId, nrLength, nrPayment} = case nrPayment of
|
||||
RPInvoice {} -> pure $ Right Nothing
|
||||
RPBalance -> pure $ Right Nothing
|
||||
RPCode codeId ->
|
||||
withTransaction oeStore (`getPrepaidCodeById` codeId) <&> \case
|
||||
Just code -> maybe (Right $ Just code) Left $ codeRefusal now nrId nrLength code
|
||||
|
||||
@@ -14,11 +14,11 @@ module StoreService.Orders
|
||||
)
|
||||
where
|
||||
|
||||
import StoreService.Log (logError, safelyWith)
|
||||
import StoreService.Log (logError, logInfo, safelyWith)
|
||||
import StoreService.Names.Phases (Phases, RegistrationId (..))
|
||||
import qualified StoreService.Names.Phases as Phases
|
||||
import StoreService.Names.Store (NamePhase (..), NameRegistration (..), VersionWrite (..), getRegistration, updateRegistration)
|
||||
import StoreService.Providers (Funded (..), PaymentSignal (..), Received (..))
|
||||
import StoreService.Names.Store (LateSupport (..), NamePhase (..), NameRegistration (..), VersionWrite (..), getRegistration, releaseHeldBalance, setLateSupport, spendHeldBalance, updateRegistration)
|
||||
import StoreService.Providers (Confirmed (..), Funded (..), PaymentSignal (..), Received (..), Uncreditable (..))
|
||||
import StoreService.Store.Invoices (InvoicePayment (..), InvoiceProduct (..), InvoiceRow (..), expireOverdueInvoice, lockInvoice, markCodePaid, paymentHolds, paymentStatusText, settlementCodeHash, settlementInvoice, truncateToSecond, updateInvoiceStatus, upsertPayment)
|
||||
import StoreService.Waiters (Waiters, publish, publishPayment)
|
||||
import Control.Concurrent.STM (STM, atomically)
|
||||
@@ -85,8 +85,10 @@ data Published = PubNothing | PubStatus InvoiceStatus | PubPayment
|
||||
-- | What the invoice pays for, read before any write.
|
||||
data Product = PBadge (Maybe ByteString) | PName NameRegistration
|
||||
|
||||
-- | A name order's change at settlement: its new version, or money received after it closed, which stays unpaid.
|
||||
data NameOutcome = NOWritten RegistrationId Int64 | NOLate RegistrationId
|
||||
-- | A name order's change at settlement: its new version; money received after it closed, which stays unpaid and is credited to its balance;
|
||||
-- a holder queued whose held balance could not be spent (the holder, then the balance's order); or an order closed because another live order
|
||||
-- holds its commitment, or its owner and name.
|
||||
data NameOutcome = NOWritten RegistrationId Int64 | NOLate RegistrationId | NOHoldNotSpent RegistrationId RegistrationId | NOLiveOrderExists RegistrationId
|
||||
|
||||
settleOrder :: DBStore -> Waiters -> Maybe Phases -> InvoiceId -> PaymentSignal -> UTCTime -> IO (Either Text InvoiceStatus)
|
||||
settleOrder st waiters phases invId signal now' = do
|
||||
@@ -110,9 +112,11 @@ settleOrder st waiters phases invId signal now' = do
|
||||
PubNothing -> pure ()
|
||||
forM_ name $ \case
|
||||
NOWritten rid v -> publishRegistration phases (rid, v)
|
||||
NOLate _ -> pure ()
|
||||
_ -> pure ()
|
||||
forM_ name $ \case
|
||||
NOLate rid -> latePayment invId rid
|
||||
NOHoldNotSpent holder source -> holdNotSpent invId holder source
|
||||
NOLiveOrderExists rid -> liveOrderExists invId rid
|
||||
NOWritten {} -> pure ()
|
||||
pure (Right status)
|
||||
where
|
||||
@@ -131,27 +135,34 @@ settleOrder st waiters phases invId signal now' = do
|
||||
| otherwise -> maybe (Left "settled invoice has no code hash") (Right . PBadge . Just) <$> settlementCodeHash db invId
|
||||
IPName rid -> maybe (Left "name invoice has no registration") (Right . PName) <$> getRegistration db rid
|
||||
newPayment :: InvoiceRow -> Write -> Bool
|
||||
-- A rise of the confirmed money is a new payment with the totals unchanged, so a late payment that confirms is credited.
|
||||
newPayment InvoiceRow {irPayment} Write {wPayment}
|
||||
-- Monero reports an invoice as confirming while its figures are still zero, so a funded verdict earns a row
|
||||
| not (paidInFull signal) && rcvCrypto == Nothing && rcvAmount == CurrencyAmount 0 = False
|
||||
| otherwise = case irPayment of
|
||||
Nothing -> True
|
||||
-- the write is monotonic, so a lower figure or withdrawn verdict is not a new payment
|
||||
Just InvoicePayment {ipAmount, ipCryptoPaid, ipPaidInFull, ipStatus}
|
||||
Just InvoicePayment {ipAmount, ipCryptoPaid, ipPaidInFull, ipStatus, ipConfirmed = Confirmed {cfCents = CurrencyAmount heldCents, cfUnits = heldUnits}}
|
||||
| ipStatus == paymentStatusText PSSettled -> False
|
||||
| otherwise ->
|
||||
maybe True (\(CurrencyAmount held) -> held < minor) ipAmount
|
||||
|| (ipCryptoPaid == Nothing && rcvCrypto /= Nothing)
|
||||
|| (paidInFull signal && not ipPaidInFull)
|
||||
|| ipStatus /= paymentStatusText wPayment
|
||||
|| confirmedCents > heldCents
|
||||
|| maybe False (> fromMaybe 0 heldUnits) confirmedUnits
|
||||
where
|
||||
Received {rcvAmount, rcvCrypto} = received signal
|
||||
Received {rcvAmount, rcvCrypto, rcvConfirmed = Confirmed {cfCents = CurrencyAmount confirmedCents, cfUnits = confirmedUnits}} = received signal
|
||||
CurrencyAmount minor = rcvAmount
|
||||
settle :: DB.Connection -> InvoiceRow -> Write -> Product -> IO (Either Text (InvoiceStatus, Published, [NameOutcome]))
|
||||
settle db row@InvoiceRow {irStatus} w@Write {wStatus, wPayment} sold = do
|
||||
let Received {rcvAmount, rcvCrypto, rcvDue} = received signal
|
||||
let money@Received {rcvUncreditable} = received signal
|
||||
wrotePayment = newPayment row w
|
||||
when wrotePayment $ upsertPayment db row wPayment rcvAmount rcvCrypto rcvDue (paidInFull signal) at
|
||||
when wrotePayment $ do
|
||||
upsertPayment db row wPayment money (paidInFull signal) at
|
||||
case sold of
|
||||
PName _ -> mapM_ (setLateSupport db invId . lateSupportOf) rcvUncreditable
|
||||
PBadge _ -> pure ()
|
||||
moved <- maybe (pure True) (\new -> updateInvoiceStatus db invId irStatus new at) wStatus
|
||||
if moved
|
||||
then do
|
||||
@@ -169,28 +180,34 @@ settleOrder st waiters phases invId signal now' = do
|
||||
-- BTCPay reports money paid into a closed invoice as Expired or Invalid, not Settled, so a new payment figure
|
||||
-- on a closed invoice is late too; the monotonic payment write reports each figure once.
|
||||
nameSettled :: DB.Connection -> InvoiceStatus -> Maybe InvoiceStatus -> Bool -> Bool -> NameRegistration -> UTCTime -> IO [NameOutcome]
|
||||
nameSettled db before after wrotePayment holdsMoney r@NameRegistration {nrId, nrPhase} now
|
||||
nameSettled db before after wrotePayment holdsMoney r@NameRegistration {nrId, nrPhase, nrBalanceSource, nrBalanceUsed} now
|
||||
| nrPhase /= PUnpaid = pure []
|
||||
| otherwise = case after of
|
||||
Just ISPaid
|
||||
| before /= ISOpen -> pure [NOLate nrId]
|
||||
| otherwise ->
|
||||
updateRegistration db r {nrPhase = PQueued} now >>= \case
|
||||
Written v -> pure [NOWritten nrId v]
|
||||
Written v -> (NOWritten nrId v :) <$> spendHold
|
||||
NotLive -> pure [NOLate nrId]
|
||||
-- not expected while this order is live; kept so the payment is still recorded
|
||||
LiveOrderExists -> pure [NOLate nrId]
|
||||
-- an invariant broke; left live, the order would keep its hold for ever, as no sweep closes a paid invoice
|
||||
LiveOrderExists -> (<> [NOLate nrId, NOLiveOrderExists nrId]) <$> closed
|
||||
_ -> E.throwIO (RegistrationChanged nrId)
|
||||
Just ISExpired -> (<> [NOLate nrId | holdsMoney]) . maybe [] (\(rid, v) -> [NOWritten rid v]) <$> closeOrder db r now
|
||||
Just ISExpired -> (<> [NOLate nrId | holdsMoney]) <$> closed
|
||||
_ -> pure [NOLate nrId | before /= ISOpen, wrotePayment]
|
||||
where
|
||||
closed = maybe [] (\(rid, v) -> [NOWritten rid v]) <$> closeOrder db r now
|
||||
-- the buyer paid the difference, so the order stays queued even when its hold cannot be spent
|
||||
spendHold = case nrBalanceSource of
|
||||
Just source -> (\spent -> [NOHoldNotSpent nrId source | not spent]) <$> spendHeldBalance db nrId nrBalanceUsed now
|
||||
Nothing -> pure []
|
||||
|
||||
-- | Clears a live unpaid order's live flag, as its invoice closes in the same transaction.
|
||||
-- | Clears a live unpaid order's live flag, as its invoice closes in the same transaction, and releases a balance it held.
|
||||
closeOrder :: DB.Connection -> NameRegistration -> UTCTime -> IO (Maybe (RegistrationId, Int64))
|
||||
closeOrder db r@NameRegistration {nrId, nrPhase, nrLive} now
|
||||
| nrPhase /= PUnpaid || not nrLive = pure Nothing
|
||||
| otherwise =
|
||||
updateRegistration db r {nrLive = False} now >>= \case
|
||||
Written v -> pure (Just (nrId, v))
|
||||
Written v -> Just (nrId, v) <$ releaseHeldBalance db nrId now
|
||||
_ -> E.throwIO (RegistrationChanged nrId)
|
||||
|
||||
-- | The order of a name invoice whose status this transaction moved to expired.
|
||||
@@ -200,9 +217,27 @@ closeInvoiceOrder db invId now =
|
||||
Just InvoiceRow {irProduct = IPName rid} -> getRegistration db rid >>= maybe (pure Nothing) (\r -> closeOrder db r now)
|
||||
_ -> pure Nothing
|
||||
|
||||
lateSupportOf :: Uncreditable -> LateSupport
|
||||
lateSupportOf = \case
|
||||
UCHighSpeed -> LSHighSpeed
|
||||
UCUncounted -> LSUnits
|
||||
UCNoConfirmationShown -> LSNoConfirmation
|
||||
|
||||
latePayment :: InvoiceId -> RegistrationId -> IO ()
|
||||
latePayment (InvoiceId invText) (RegistrationId rid) =
|
||||
logError ("names: invoice " <> invText <> " was paid after its order closed, so registration " <> rid <> " stays unpaid; refund the payment")
|
||||
logInfo ("names: invoice " <> invText <> " received money after registration " <> rid <> " closed; it stays unpaid, and its money is credited to its balance once confirmed, else alerted")
|
||||
|
||||
holdNotSpent :: InvoiceId -> RegistrationId -> RegistrationId -> IO ()
|
||||
holdNotSpent (InvoiceId invText) (RegistrationId holder) (RegistrationId source) =
|
||||
logError $
|
||||
"names: invoice " <> invText <> " queued registration " <> holder <> " as paid, but the balance of registration " <> source
|
||||
<> " it held could not be spent; check that balance and release or spend its hold by hand"
|
||||
|
||||
liveOrderExists :: InvoiceId -> RegistrationId -> IO ()
|
||||
liveOrderExists (InvoiceId invText) (RegistrationId rid) =
|
||||
logError $
|
||||
"names: invoice " <> invText <> " was paid while another live order held the commitment, or the owner and name, of registration " <> rid
|
||||
<> "; it was closed and its money is credited to its balance; the unique live indexes should have prevented this"
|
||||
|
||||
-- | False when the invoice was no longer open. Throws RegistrationChanged, changing nothing, when its order changed meanwhile.
|
||||
-- The provider has taken the cancel, so a name invoice a payment landed on meanwhile expires too, and its payment is late.
|
||||
|
||||
@@ -28,15 +28,18 @@ module StoreService.Poller
|
||||
cleanupReadsPerPass,
|
||||
unpaidRetention,
|
||||
cleanupUnpaid,
|
||||
creditPass,
|
||||
forgetRates,
|
||||
)
|
||||
where
|
||||
|
||||
import StoreService.Config (PollConfig (..))
|
||||
import StoreService.Names.LateCredits (CreditOutcome (..), creditLateInvoice)
|
||||
import StoreService.Names.Phases (Phases, RegistrationId (..))
|
||||
import StoreService.Names.Store (deleteUnpaidRegistration, unpaidCleanupCandidates)
|
||||
import StoreService.Names.Store (CleanupKept (..), LateAlert (..), LateCredit (..), LateCreditState (..), LatePending (..), LateSupport (..), claimLateAlert, deleteUnpaidRegistration, lateAlertDue, latePending, uncreditedLateInvoices, unpaidCleanupCandidates)
|
||||
import StoreService.Orders (decide, expireOverdue, settleOrder)
|
||||
import StoreService.Providers (ListPass (..), PaymentSignal (..), Provider (..), ProviderError (..), Received (..), expiresItself, settleWindow)
|
||||
import StoreService.Store.Invoices (InvoiceProduct (..), InvoiceRow (..), OverdueInvoice (..), getInvoice, getInvoiceByProviderRef, overdueInvoices, unpaidRefs)
|
||||
import StoreService.Providers (ListPass (..), PaymentSignal (..), Provider (..), ProviderError (..), Rate (..), Received (..), expiresItself, settleWindow, unitName)
|
||||
import StoreService.Store.Invoices (InvoiceProduct (..), InvoiceRow (..), OverdueInvoice (..), cryptoCurrencyText, getInvoice, getInvoiceByProviderRef, overdueInvoices, unpaidRefs)
|
||||
import StoreService.Waiters (Waiters, waitingCount, waitingCountSTM)
|
||||
import Control.Concurrent.STM
|
||||
import StoreService.Log (logError, logInfo, logWarn, safely, safelyWith)
|
||||
@@ -50,7 +53,7 @@ import qualified Data.Set as S
|
||||
import Data.Text (Text)
|
||||
import Data.Time.Clock (NominalDiffTime, UTCTime, addUTCTime, diffUTCTime, getCurrentTime)
|
||||
import Numeric.Natural (Natural)
|
||||
import Simplex.Chat.PaymentService.Types (InvoiceId (..), InvoiceStatus (..), PaymentProvider (..))
|
||||
import Simplex.Chat.PaymentService.Types (CryptoCurrency, InvoiceId (..), InvoiceStatus (..), PaymentProvider (..))
|
||||
import Simplex.Messaging.Agent.Store.Common (DBStore, withTransaction)
|
||||
import Simplex.Messaging.Encoding.String (textEncode)
|
||||
import Simplex.Messaging.Util (tshow)
|
||||
@@ -121,7 +124,10 @@ data PollerEnv = PollerEnv
|
||||
peCancelFailed :: TVar (Map Text UTCTime),
|
||||
peCleanedAt :: TVar (Maybe UTCTime),
|
||||
-- | The orders of the day's cleanup not read yet.
|
||||
peCleanupLeft :: TVar [(RegistrationId, InvoiceId)]
|
||||
peCleanupLeft :: TVar [(RegistrationId, InvoiceId)],
|
||||
peCreditedAt :: TVar (Maybe UTCTime),
|
||||
-- | The rates read in this pass or hinted read, by provider and coin.
|
||||
peRates :: TVar (Map (Text, Text) (Either ProviderError Rate))
|
||||
}
|
||||
|
||||
newPollerEnv :: DBStore -> Waiters -> Maybe Phases -> ReadHints -> [Provider] -> PollConfig -> IO PollerEnv
|
||||
@@ -131,13 +137,16 @@ newPollerEnv peStore peWaiters pePhases peHints peProviders pePoll = do
|
||||
peCancelFailed <- newTVarIO M.empty
|
||||
peCleanedAt <- newTVarIO Nothing
|
||||
peCleanupLeft <- newTVarIO []
|
||||
pure PollerEnv {peStore, peWaiters, pePhases, peHints, peProviders, pePoll, peSkipped, peListedAt, peStrayEvery = strayListInterval, peCancelFailed, peCleanedAt, peCleanupLeft}
|
||||
peCreditedAt <- newTVarIO Nothing
|
||||
peRates <- newTVarIO M.empty
|
||||
pure PollerEnv {peStore, peWaiters, pePhases, peHints, peProviders, pePoll, peSkipped, peListedAt, peStrayEvery = strayListInterval, peCancelFailed, peCleanedAt, peCleanupLeft, peCreditedAt, peRates}
|
||||
|
||||
-- | Read providers before the sweep, and leave out of the sweep every invoice whose read or settlement failed,
|
||||
-- so an invoice with money in it is never expired. A list that cannot account for every invoice skips the sweep.
|
||||
runOnePass :: PollerEnv -> IO ()
|
||||
runOnePass env@PollerEnv {peStore, peProviders} = do
|
||||
now <- getCurrentTime
|
||||
forgetRates env
|
||||
rows <- unpaidRefs peStore (addUTCTime (negate settleWindow) now)
|
||||
let bulk = length rows > readsPerPass
|
||||
listNow <- listDue env now bulk
|
||||
@@ -153,6 +162,7 @@ runOnePass env@PollerEnv {peStore, peProviders} = do
|
||||
pruneSkipLog env now
|
||||
-- the cleanup runs whatever the sweep met
|
||||
unless (null peProviders) $ forM_ missed $ \refs -> safely "badge poller: the sweep" (sweepExpired env now refs)
|
||||
void $ safely "names: the late credit pass" (creditPass env now)
|
||||
cleanupUnpaid env now
|
||||
|
||||
-- | The cases the stray list catches are rare and not urgent, so minutes, not the pass cadence.
|
||||
@@ -221,19 +231,27 @@ listPass env now p =
|
||||
skipWhat (ref, _) = "badge poller: reading the skipped " <> tshow (pProvider p) <> " invoice " <> fromMaybe "the provider did not name" ref
|
||||
|
||||
-- | provider_ref is unique table-wide, not per provider, so check the provider too.
|
||||
-- A name invoice's late money is credited after the settlement that recorded it commits.
|
||||
settleMoved :: PollerEnv -> PaymentProvider -> UTCTime -> (Text, PaymentSignal) -> IO ()
|
||||
settleMoved env@PollerEnv {peStore, peWaiters, pePhases} provider now (ref, signal) =
|
||||
settleMoved env@PollerEnv {peStore, peWaiters, pePhases, peProviders} provider now (ref, signal) =
|
||||
getInvoiceByProviderRef peStore ref >>= \case
|
||||
Just InvoiceRow {irInvoiceId, irStatus, irProvider, irProduct} | irProvider == provider ->
|
||||
when (isJust (decide irStatus signal)) $
|
||||
settleOrder peStore peWaiters pePhases irInvoiceId signal now >>= \case
|
||||
Left e -> logError ("badge poller: settling order " <> ref <> " failed: " <> e)
|
||||
Right status -> reportSettled irProduct irStatus status
|
||||
Right status -> do
|
||||
reportSettled irProduct irStatus status
|
||||
case (irProduct, find ((== provider) . pProvider) peProviders) of
|
||||
(IPName _, Just p) ->
|
||||
creditLate env p now irInvoiceId >>= \case
|
||||
CONothingDue -> pendingLate env irInvoiceId
|
||||
_ -> pure ()
|
||||
_ -> pure ()
|
||||
_ -> pure ()
|
||||
where
|
||||
reportSettled sold before after
|
||||
-- checked before the no-change case, so a refund still alerts when money lands after expiry;
|
||||
-- settlement itself alerts once for a name order's late payment
|
||||
-- a name order's late payment is credited to its balance instead
|
||||
| IPBadge {} <- sold, after == ISExpired, SigClosed Received {rcvCrypto = Just paid} _ <- signal = do
|
||||
let alert = "badge poller: order " <> ref <> " expired holding " <> paid <> ", which needs a refund"
|
||||
due <- dueToWarn env now alert
|
||||
@@ -244,6 +262,7 @@ settleMoved env@PollerEnv {peStore, peWaiters, pePhases} provider now (ref, sign
|
||||
serveHint :: PollerEnv -> Text -> IO ()
|
||||
serveHint env ref = do
|
||||
now <- getCurrentTime
|
||||
forgetRates env
|
||||
hintSafely env now ref
|
||||
|
||||
readHint :: PollerEnv -> UTCTime -> Text -> IO ()
|
||||
@@ -277,12 +296,14 @@ cleanupDue PollerEnv {peCleanedAt} now = atomically $ do
|
||||
pure due
|
||||
|
||||
-- | The poller reads an invoice only within settleWindow of its creation, so each order's invoice is read once more
|
||||
-- before the order goes: a payment whose webhook was lost is recorded then, and the order is kept for support.
|
||||
-- Each pass reads at most cleanupReadsPerPass of the day's orders.
|
||||
-- before the order goes: a payment whose webhook was lost is recorded then, and the order is kept with its balance.
|
||||
-- Each pass reads at most cleanupReadsPerPass of the day's orders. The day's alerts on late money go with it.
|
||||
cleanupUnpaid :: PollerEnv -> UTCTime -> IO ()
|
||||
cleanupUnpaid env@PollerEnv {peStore, peCleanupLeft} now = do
|
||||
due <- cleanupDue env now
|
||||
when due $ withTransaction peStore (`unpaidCleanupCandidates` addUTCTime (negate unpaidRetention) now) >>= atomically . writeTVar peCleanupLeft
|
||||
when due $ do
|
||||
withTransaction peStore (`unpaidCleanupCandidates` addUTCTime (negate unpaidRetention) now) >>= atomically . writeTVar peCleanupLeft
|
||||
void $ safely "names: the late payment alerts" (alertLatePayments env now)
|
||||
candidates <- atomically $ stateTVar peCleanupLeft (splitAt cleanupReadsPerPass)
|
||||
deleted <- filterM (\c@(RegistrationId rid, _) -> safelyWith ("names cleanup: registration " <> rid) False (cleanOne c)) candidates
|
||||
unless (null deleted) $ logInfo ("names cleanup: deleted " <> tshow (length deleted) <> " unpaid order(s)")
|
||||
@@ -297,12 +318,123 @@ cleanupUnpaid env@PollerEnv {peStore, peCleanupLeft} now = do
|
||||
Left (ProviderError e) -> keep ("reading invoice " <> invText <> " failed: " <> e)
|
||||
Right signal_ -> do
|
||||
mapM_ (\signal -> settleMoved env irProvider now (irProviderRef, signal)) signal_
|
||||
deleted <- withTransaction peStore (`deleteUnpaidRegistration` rid)
|
||||
unless deleted $ logError ("names cleanup: unpaid registration " <> ridText <> " is kept because invoice " <> invText <> " received a payment; refund it")
|
||||
pure deleted
|
||||
withTransaction peStore (`deleteUnpaidRegistration` rid) >>= \case
|
||||
Right () -> pure True
|
||||
Left CKPaid -> False <$ logInfo ("names cleanup: unpaid registration " <> ridText <> " is kept with its balance, because invoice " <> invText <> " received a payment")
|
||||
Left (CKHolder (RegistrationId source)) -> False <$ logError ("names cleanup: unpaid registration " <> ridText <> " is kept because it still holds the balance of registration " <> source)
|
||||
where
|
||||
keep why = False <$ logWarn ("names cleanup: unpaid registration " <> ridText <> " is kept until the next run, " <> why)
|
||||
|
||||
-- | At the idle cadence, so a failing rate read costs one read per coin per pass while browsers wait.
|
||||
creditDue :: PollerEnv -> UTCTime -> IO Bool
|
||||
creditDue PollerEnv {peCreditedAt, pePoll = PollConfig {pIdleSeconds}} now = atomically $ do
|
||||
due <- maybe True (\at -> diffUTCTime now at >= fromIntegral pIdleSeconds) <$> readTVar peCreditedAt
|
||||
when due $ writeTVar peCreditedAt (Just now)
|
||||
pure due
|
||||
|
||||
-- | Credits every closed order's confirmed money not all credited, so a crash or a failed rate read after a settlement loses nothing.
|
||||
creditPass :: PollerEnv -> UTCTime -> IO ()
|
||||
creditPass env@PollerEnv {peStore, peProviders} now = do
|
||||
due <- creditDue env now
|
||||
when due $ do
|
||||
invoices <- withTransaction peStore uncreditedLateInvoices
|
||||
forM_ invoices $ \invId@(InvoiceId invText) ->
|
||||
safely ("names: crediting invoice " <> invText) $
|
||||
getInvoice peStore invId >>= \case
|
||||
Just InvoiceRow {irProvider} | Just p <- find ((== irProvider) . pProvider) peProviders -> void $ creditLate env p now invId
|
||||
_ -> do
|
||||
due' <- dueToWarn env now ("no rate provider: " <> invText)
|
||||
when due' $ logWarn ("names: invoice " <> invText <> " has late money to credit, but no provider is configured to read its rate")
|
||||
|
||||
-- | The pass's rate of a coin at a provider, read at most once.
|
||||
cachedRate :: PollerEnv -> Provider -> CryptoCurrency -> IO (Either ProviderError Rate)
|
||||
cachedRate PollerEnv {peRates} Provider {pProvider, pCurrentRate} coin =
|
||||
M.lookup key <$> readTVarIO peRates >>= \case
|
||||
Just rate -> pure rate
|
||||
Nothing -> do
|
||||
rate <- maybe (pure $ Left $ ProviderError $ textEncode pProvider <> " offers no rates") ($ coin) pCurrentRate
|
||||
rate <$ atomically (modifyTVar' peRates (M.insert key rate))
|
||||
where
|
||||
key = (textEncode pProvider, cryptoCurrencyText coin)
|
||||
|
||||
-- | Each pass and hinted read reads the rates again.
|
||||
forgetRates :: PollerEnv -> IO ()
|
||||
forgetRates PollerEnv {peRates} = atomically $ writeTVar peRates M.empty
|
||||
|
||||
creditLate :: PollerEnv -> Provider -> UTCTime -> InvoiceId -> IO CreditOutcome
|
||||
creditLate env@PollerEnv {peStore} p now invId@(InvoiceId invText) = do
|
||||
outcome <- creditLateInvoice peStore (cachedRate env p) invId now
|
||||
case outcome of
|
||||
CONothingDue -> pure ()
|
||||
COCredited LateCredit {lcRegistration = RegistrationId rid, lcUnits, lcInvoiceRate, lcCurrentRate, lcRateUsed, lcCents} ->
|
||||
logInfo $
|
||||
"names: invoice " <> invText <> " credited " <> tshow lcCents <> " cents to the balance of registration " <> rid
|
||||
<> maybe "" (\units -> " for " <> tshow units <> " units at " <> fromMaybe "?" lcRateUsed <> " (invoice " <> fromMaybe "?" lcInvoiceRate <> ", current " <> fromMaybe "?" lcCurrentRate <> ")") lcUnits
|
||||
CONoInvoiceRate -> do
|
||||
due <- dueToWarn env now ("no invoice rate: " <> invText)
|
||||
when due $ logError ("names: invoice " <> invText <> " has confirmed late money, but no invoice rate was recorded to credit it at; check it at the provider")
|
||||
CORateFailed (ProviderError e) -> do
|
||||
due <- dueToWarn env now ("rate read failed: " <> tshow (pProvider p))
|
||||
when due $ logWarn ("names: late credits wait, as the current rate cannot be read; each pass tries again: " <> e)
|
||||
CORateFloor invoiceRate Rate {rateText} -> do
|
||||
due <- dueToWarn env now ("rate floor: " <> invText)
|
||||
when due $ logError ("names: invoice " <> invText <> " is not credited: the current rate " <> rateText <> " is below half its rate " <> invoiceRate <> "; it is never credited by itself, and support refunds it by hand")
|
||||
CORefused -> logError ("names: the credit of invoice " <> invText <> " was refused, its credit number taken meanwhile; the next pass tries again")
|
||||
pure outcome
|
||||
|
||||
-- | Money not yet confirmed waits for the settlement that confirms it.
|
||||
pendingLate :: PollerEnv -> InvoiceId -> IO ()
|
||||
pendingLate PollerEnv {peStore} invId@(InvoiceId invText) =
|
||||
withTransaction peStore (`latePending` invId) >>= \case
|
||||
Just pending | pending `elem` [LPConfirming, LPUnconfirmed] -> logInfo ("names: invoice " <> invText <> " holds money of its closed order not yet confirmed; it is credited once confirmed")
|
||||
_ -> pure ()
|
||||
|
||||
-- | Late money still not all credited when its payment row is older than the read window, once per invoice and again when more arrives;
|
||||
-- the claim keeps it to one instance.
|
||||
alertLatePayments :: PollerEnv -> UTCTime -> IO ()
|
||||
alertLatePayments env@PollerEnv {peStore} now = do
|
||||
due <- withTransaction peStore (`lateAlertDue` addUTCTime (negate settleWindow) now)
|
||||
forM_ due $ \alert@LateAlert {laState = LateCreditState {lsInvoice = InvoiceId invText}} ->
|
||||
safely ("names: the alert on invoice " <> invText) $ do
|
||||
(reason, support) <- lateReason env alert
|
||||
claimed <- withTransaction peStore $ \db -> claimLateAlert db alert support now
|
||||
when claimed $ logError (lateAlertText alert reason)
|
||||
|
||||
-- | Confirmed money waiting comes before a stored reason, as in pendingCase, so its alert never asks for a refund by hand.
|
||||
lateReason :: PollerEnv -> LateAlert -> IO (Text, Maybe LateSupport)
|
||||
lateReason env@PollerEnv {peStore, peProviders} LateAlert {laPending, laState = LateCreditState {lsInvoice, lsCoin, lsSupport, lsInvoiceRate}} = case laPending of
|
||||
LPUncounted -> pure (uncounted, Nothing)
|
||||
LPUncredited -> case lsCoin of
|
||||
Nothing -> pure (cardWaits, Nothing)
|
||||
Just coin
|
||||
| lsSupport == Just LSRateFloor ->
|
||||
getInvoice peStore lsInvoice >>= \case
|
||||
Just InvoiceRow {irProvider} | Just p <- find ((== irProvider) . pProvider) peProviders -> (\r -> (rateFloor (either (const "unread") rateText r), Nothing)) <$> cachedRate env p coin
|
||||
_ -> pure (rateFloor "unread", Nothing)
|
||||
| otherwise -> pure (rateRead, Nothing)
|
||||
_ | lsSupport == Just LSHighSpeed -> pure (highSpeed, Nothing)
|
||||
_ | lsSupport == Just LSNoConfirmation -> pure (noConfirmation, Nothing)
|
||||
_ -> pure (unconfirmed, Just LSUnconfirmed)
|
||||
where
|
||||
unconfirmed = "refund by hand only a transaction confirmed on chain that BTCPay no longer monitors; one still Processing there waits"
|
||||
highSpeed = "the invoice was made under HighSpeed, so its money is never credited by itself; refund by hand only a transaction confirmed on chain"
|
||||
noConfirmation = "the Monero plugin shows no confirmation of this money, so it is never credited by itself; refund by hand only a transaction confirmed on chain"
|
||||
rateRead = "confirmed, the credit waits on the rate read; do not refund; fix the rate read"
|
||||
cardWaits = "confirmed, the credit waits on the poller's credit pass; do not refund; check the service log"
|
||||
rateFloor current = "confirmed; the coin's price fell by more than half since the invoice (" <> fromMaybe "?" lsInvoiceRate <> ", " <> current <> "); it is never credited by itself; refund by hand only a transaction confirmed on chain"
|
||||
uncounted = "an amount BTCPay reported with more decimals than its unit; check it at the provider"
|
||||
|
||||
lateAlertText :: LateAlert -> Text -> Text
|
||||
lateAlertText LateAlert {laState = LateCreditState {lsInvoice = InvoiceId invText, lsRegistration = RegistrationId rid, lsCoin, lsReceivedCents, lsConfirmedCents, lsCreditedCents, lsReceivedUnits, lsConfirmedUnits, lsCreditedUnits}} reason =
|
||||
"names: invoice " <> invText <> " of order " <> rid <> ": " <> figures <> "; " <> reason
|
||||
where
|
||||
figures = case (lsCoin, lsReceivedUnits) of
|
||||
(Nothing, _) -> amounts "cents" (toInteger lsReceivedCents) (toInteger lsConfirmedCents) (toInteger lsCreditedCents)
|
||||
(Just coin, Just received) -> amounts (unitName coin) (toInteger received) (maybe 0 toInteger lsConfirmedUnits) (toInteger lsCreditedUnits)
|
||||
(Just _, Nothing) -> tshow lsReceivedCents <> " cents received at the invoice's rate, not counted in units"
|
||||
amounts unit received confirmed credited =
|
||||
tshow received <> " " <> unit <> " received, " <> tshow confirmed <> " " <> unit <> " confirmed, " <> tshow credited <> " " <> unit <> " credited"
|
||||
|
||||
-- | Cancel the order at the provider first, so the buyer can no longer pay it.
|
||||
closedAtProvider :: PollerEnv -> UTCTime -> OverdueInvoice -> IO Bool
|
||||
closedAtProvider env@PollerEnv {peProviders} now oi@OverdueInvoice {oiProvider, oiProviderRef = ref} =
|
||||
|
||||
@@ -0,0 +1,757 @@
|
||||
{-# LANGUAGE CPP #-}
|
||||
{-# LANGUAGE LambdaCase #-}
|
||||
{-# LANGUAGE NamedFieldPuns #-}
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
{-# LANGUAGE TupleSections #-}
|
||||
{-# LANGUAGE TypeOperators #-}
|
||||
|
||||
module Bots.StoreService.NamesBalancesTests (namesBalancesTests, cardPaid, coveredSpend, credit, creditLate, fieldsN, figures, holdPrice, holder, invariantHolds, lateCredit, payment, placeOrderRow, settleHolder, source) where
|
||||
|
||||
import Bots.StoreService.NamesOrdersTests (Ctx (..), withOrders)
|
||||
import Bots.StoreService.NamesStoreTests (at, btc, invoiceStatus, newReg, ownerA, ownerB, paidOrder, reg, signature, t0, write)
|
||||
import Bots.StoreService.WebTests (capturingStderr, rcv, withServiceStore, withServiceStores)
|
||||
import Control.Concurrent.Async (async, wait)
|
||||
import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar)
|
||||
import Control.Concurrent.STM (atomically, check)
|
||||
import Control.Monad (forM_)
|
||||
import Data.Bifunctor (first)
|
||||
import Data.Int (Int64)
|
||||
import Data.Text (Text)
|
||||
import qualified Data.Text as T
|
||||
import Data.Text.Encoding (encodeUtf8)
|
||||
import Data.Time.Clock (UTCTime, addUTCTime)
|
||||
import Simplex.Chat.PaymentService.Types (CardProvider (..), CryptoCurrency (..), InvoiceId (..), InvoiceStatus (..), ServicePaymentMethod (..))
|
||||
import Simplex.Messaging.Agent.Store.Common (DBStore, withTransaction)
|
||||
import qualified Simplex.Messaging.Agent.Store.DB as DB
|
||||
import qualified Simplex.Messaging.Crypto as C
|
||||
import Simplex.Messaging.SimplexName (labelHash)
|
||||
import StoreService.Config (ServiceConfig (..))
|
||||
import StoreService.Names.Balances
|
||||
import StoreService.Names.Orders (ClosedOrder (..), OrderRefusal (..), OrderRequest (..), OrdersEnv (..))
|
||||
import qualified StoreService.Names.Orders as Orders
|
||||
import StoreService.Names.Phases (RegistrationId (..))
|
||||
import StoreService.Names.Signatures (OrderFields (..))
|
||||
import StoreService.Names.Store
|
||||
import StoreService.Names.Turns (balanceTurnCount, newTurns, turnsCount, withBalanceTurn, withLabelTurn)
|
||||
import StoreService.Orders (cancelOpenInvoice, expireOverdue, settleOrder)
|
||||
import StoreService.Poller (cleanupUnpaid, newPollerEnv, unpaidRetention)
|
||||
import StoreService.Providers (Funded (..), PaymentSignal (..))
|
||||
import StoreService.Waiters (newWaiters)
|
||||
import StoreService.Web.Server (WebEnv (..))
|
||||
import System.Timeout (timeout)
|
||||
import Test.Hspec
|
||||
|
||||
#if defined(dbPostgres)
|
||||
import Control.Concurrent.Async (concurrently)
|
||||
import Control.Concurrent.STM (modifyTVar', newTVarIO, readTVar)
|
||||
import Data.Either (isRight)
|
||||
import Database.PostgreSQL.Simple (Only (..), (:.) (..))
|
||||
#else
|
||||
import Database.SQLite.Simple (Only (..), (:.) (..))
|
||||
#endif
|
||||
|
||||
namesBalancesTests :: Spec
|
||||
namesBalancesTests = describe "StoreService names: balances" $ do
|
||||
describe "store" $ do
|
||||
it "credits a balance, making it on the first credit" testCredit
|
||||
it "spends a covered price at once from the amount seen, refusing a stale amount, a dearer price or a held balance, changing nothing" testSpendAtOnce
|
||||
it "lets one of two difference orders hold a balance, the losing order not written" testTwoHolds
|
||||
it "spends a hold only for its holder and while the amount covers it, clearing the hold" testSpendHeld
|
||||
it "releases a hold only for its holder" testRelease
|
||||
it "refuses spends, holds and held spends of 0 or fewer cents, and negative credits, refunds and late credits" testNoNegativeCents
|
||||
it "refunds a balance only at its amount, above 0 and not held, refused while held and accepted once released" testRefund
|
||||
it "keeps amount = credited - spent - refunded over spends at once, a held spend, a released hold and a refund, spent counting orders past unpaid" testInvariant
|
||||
it "keeps the invariant over credit, refund, credit, refund, refunded the sum" testCreditRefundTwice
|
||||
it "reads a hold and a spend back through a new store connection" testRestart
|
||||
it "finds an order and its balance by the order's registration id or its invoice id" testByReference
|
||||
it "chains an order back along its balance sources over three orders, with each payment and its cents" testChain
|
||||
it "stops the chain of a closed difference order at itself, with its late credits" testChainOfClosed
|
||||
it "hashes a balance order over its fields, the paying order, price, balance and method, and stores it for a difference spend" testBalanceOrderHash
|
||||
it "returns the 50 newest orders and then every older one holding a balance above 0" testFindBalances
|
||||
describe "closes" $ do
|
||||
it "releases a hold at a cancel, the sweep's expiry, settlement's expiry and the next order's close" testClosesRelease
|
||||
it "reads an overdue holder's hold as none, and closes it in the transaction of the order placed" testOverdueHolderClosed
|
||||
it "skips a named holder no longer live, and refuses with the balance when a live one cannot be closed" testNamedHolders
|
||||
it "refuses with the balance a named holder whose invoice has not expired, leaving it open and holding" testNamedHolderNotDue
|
||||
it "keeps at the cleanup, and logs, an unpaid order still holding a balance" testCleanupKeepsHolder
|
||||
describe "refunds" $ do
|
||||
it "refuses no order, no balance, a balance held by an open or overdue holder, and another amount, then records one with its chain" testRecordRefund
|
||||
describe "late credits" $ do
|
||||
it "credits a late payment once per credit number, a taken number changing neither the rows nor the balance" testCreditLatePayment
|
||||
it "tells each case of pending money and selects confirmed money not all credited, by the order whatever the invoice's status" testLateScans
|
||||
it "leaves 0.1 and 0.2 BTC credited against 0.3 confirmed neither pending nor selected" testExactUnits
|
||||
it "tells confirmed money not credited as such while its cents still read 0, as Monero's can" testConfirmedBeforeCents
|
||||
it "reads crypto received with no confirmed figure as unconfirmed" testNoConfirmedFigure
|
||||
it "alerts on pending money past the cutoff once, again only when more arrives, claimed by one of two instances" testLateAlerts
|
||||
it "alerts again on money that could not be counted in units when more of it arrives" testUncountedAlertRepeats
|
||||
describe "turns" $ do
|
||||
it "runs two holders of one balance one after the other, and nests in a label turn" testBalanceTurn
|
||||
#if defined(dbPostgres)
|
||||
describe "two connections" $ do
|
||||
it "applies one of a spend and a refund, or of a held spend and a refund, and keeps the invariant for a credit and a refund" testConcurrentWrites
|
||||
#endif
|
||||
|
||||
-- fixtures
|
||||
|
||||
-- | Every name and commitment its own, so any number of live orders fit.
|
||||
fieldsN :: Text -> OrderFields
|
||||
fieldsN label =
|
||||
OrderFields
|
||||
{ ofLabelHash = labelHash label,
|
||||
ofLength = T.length label,
|
||||
ofDuration = 69292800,
|
||||
ofCommitment = C.sha256Hash $ encodeUtf8 label,
|
||||
ofSealed = "sealed-" <> label
|
||||
}
|
||||
|
||||
-- | A crypto invoice row, or a card one with its client secret in place of an address.
|
||||
invoiceRow :: DB.Connection -> Text -> Bool -> Int -> UTCTime -> IO ()
|
||||
invoiceRow db invId card cents expiresAt =
|
||||
DB.execute
|
||||
db
|
||||
"INSERT INTO sx_badge_service_invoices (invoice_id, provider, price, amount, currency, payment_url, payment_address, payment_crypto_currency, payment_crypto_amount, expires_at, status, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"
|
||||
((invId, provider, cents, cents, "usd" :: Text, url, address, currency, cryptoAmount, expiresAt) :. ("open" :: Text, t0, t0))
|
||||
where
|
||||
destination :: (Text, Maybe Text, Maybe Text, Maybe Text, Maybe Text)
|
||||
destination
|
||||
| card = ("stripe", Just "pi_secret", Nothing, Nothing, Nothing)
|
||||
| otherwise = ("crypto", Nothing, Just "bc1qexampleaddress", Just "btc", Just "0.003")
|
||||
(provider, url, address, currency, cryptoAmount) = destination
|
||||
|
||||
-- | A paid order, unpaid and live, whose invoice of the cents expires at the given time.
|
||||
placeOrderRow :: DBStore -> Text -> Bool -> Int -> UTCTime -> IO ()
|
||||
placeOrderRow st r card cents expiresAt = withTransaction st $ \db -> do
|
||||
invoiceRow db ("inv-" <> r) card cents expiresAt
|
||||
createPaidRegistration db (newReg r ownerA (fieldsN r)) (OTInvoice method cents) (paidOrder ("inv-" <> r)) {poMethod = method, poPrice = cents} t0 `shouldReturn` Right ()
|
||||
where
|
||||
method = if card then SPMCard CPStripe else btc
|
||||
|
||||
-- | A taken paid order with a balance of its price.
|
||||
source :: DBStore -> Text -> Int -> IO ()
|
||||
source st r cents = do
|
||||
placeOrderRow st r False cents (at 60)
|
||||
taken <- reg st r
|
||||
write st taken {nrPhase = PTaken} `shouldReturn` Written 2
|
||||
credit st r cents
|
||||
|
||||
credit :: DBStore -> Text -> Int -> IO ()
|
||||
credit st r cents = withTransaction st $ \db -> creditBalance db (RegistrationId r) cents t0
|
||||
|
||||
holdPrice :: Int
|
||||
holdPrice = 40000
|
||||
|
||||
holdTerms :: Text -> Int -> OrderTerms
|
||||
holdTerms src seen = OTBalance (RegistrationId src) holdPrice seen (Just btc)
|
||||
|
||||
-- | A difference order holding all of the source's balance seen, its invoice of the difference expiring at the given time.
|
||||
holder :: DBStore -> Text -> Text -> Int -> UTCTime -> IO (Either RegistrationRefused ())
|
||||
holder st r src seen expiresAt = withTransaction st $ \db -> do
|
||||
invoiceRow db ("inv-" <> r) False (holdPrice - seen) expiresAt
|
||||
createPaidRegistration db (newReg r ownerA (fieldsN r)) (holdTerms src seen) (paidOrder ("inv-" <> r)) {poPrice = holdPrice} t0
|
||||
|
||||
hold :: Text -> UTCTime -> Bool -> BalanceHold
|
||||
hold h bhUntil bhOverdue = BalanceHold {bhHolder = RegistrationId h, bhUntil, bhOverdue, bhFunded = False}
|
||||
|
||||
coveredSpend :: DBStore -> Text -> Text -> Int -> Int -> IO (Either RegistrationRefused ())
|
||||
coveredSpend st r src price seen = withTransaction st $ \db -> createBalanceRegistration db (newReg r ownerA (fieldsN r)) (RegistrationId src) price seen t0
|
||||
|
||||
-- | The holder queued and its hold spent in one transaction, as settlement does.
|
||||
settleHolder :: DB.Connection -> NameRegistration -> IO Bool
|
||||
settleHolder db r = do
|
||||
updateRegistration db r {nrPhase = PQueued} t0 `shouldReturn` Written (nrVersion r + 1)
|
||||
spendHeldBalance db (nrId r) (nrBalanceUsed r) t0
|
||||
|
||||
release :: DBStore -> Text -> IO Bool
|
||||
release st h = withTransaction st $ \db -> releaseHeldBalance db (RegistrationId h) t0
|
||||
|
||||
refund :: DBStore -> Text -> Int -> IO Bool
|
||||
refund st r cents = withTransaction st $ \db -> refundBalance db (RegistrationId r) cents (at 5)
|
||||
|
||||
-- | Amount, credited, refunded and the hold, as they read at the given time.
|
||||
figures :: DBStore -> Text -> UTCTime -> IO (Maybe (Int, Int, Int, Maybe BalanceHold))
|
||||
figures st r now = withTransaction st $ \db -> fmap (\Balance {blAmount, blCredited, blRefunded, blHold} -> (blAmount, blCredited, blRefunded, blHold)) <$> getBalance db (RegistrationId r) now
|
||||
|
||||
-- | amount = credited - spent - refunded, spent being the balance_used of the orders past unpaid it paid for.
|
||||
invariantHolds :: DBStore -> Text -> IO ()
|
||||
invariantHolds st r = do
|
||||
Just (amount, credited, refunded, _) <- figures st r t0
|
||||
used <- withTransaction st $ \db -> DB.query db "SELECT balance_used FROM sx_badge_service_name_registrations WHERE balance_source = ? AND phase <> ?" (r, PUnpaid)
|
||||
(r, amount) `shouldBe` (r, credited - sum (map fromOnly (used :: [Only Int])) - refunded)
|
||||
|
||||
absent :: DBStore -> Text -> IO ()
|
||||
absent st r = withTransaction st (\db -> getRegistration db (RegistrationId r)) `shouldReturn` Nothing
|
||||
|
||||
-- | A payment row with the figures the provider's reads left: cents received and confirmed, the crypto text, and units received and confirmed.
|
||||
data Paid = Paid
|
||||
{ pCents :: Int,
|
||||
pConfirmedCents :: Int,
|
||||
pCrypto :: Maybe Text,
|
||||
pUnits :: Maybe Int64,
|
||||
pConfirmedUnits :: Maybe Int64,
|
||||
pInFull :: Bool
|
||||
}
|
||||
|
||||
cryptoPaid :: Int64 -> Int64 -> Paid
|
||||
cryptoPaid units confirmed = Paid {pCents = 20000, pConfirmedCents = 0, pCrypto = Just "0.003", pUnits = Just units, pConfirmedUnits = Just confirmed, pInFull = False}
|
||||
|
||||
cardPaid :: Int -> Int -> Paid
|
||||
cardPaid cents confirmed = Paid {pCents = cents, pConfirmedCents = confirmed, pCrypto = Nothing, pUnits = Nothing, pConfirmedUnits = Nothing, pInFull = False}
|
||||
|
||||
payment :: DBStore -> Text -> Paid -> UTCTime -> IO ()
|
||||
payment st invId Paid {pCents, pConfirmedCents, pCrypto, pUnits, pConfirmedUnits, pInFull} createdAt =
|
||||
withTransaction st $ \db ->
|
||||
DB.execute
|
||||
db
|
||||
"INSERT INTO sx_badge_service_payments (payment_id, invoice_id, provider, amount, currency, crypto_paid, paid_in_full, status, confirmed_amount, received_units, confirmed_units, invoice_rate, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
|
||||
((invId, invId, "crypto" :: Text, pCents, "usd" :: Text, pCrypto, if pInFull then 1 else 0 :: Int, "pending" :: Text, pConfirmedCents, pUnits) :. (pConfirmedUnits, Just ("62500" :: Text), createdAt, createdAt))
|
||||
|
||||
-- | An order closed unpaid, by crypto unless card, with a late payment row created at the given time.
|
||||
closedWith :: DBStore -> Text -> Bool -> Paid -> UTCTime -> IO ()
|
||||
closedWith st r card paid createdAt = do
|
||||
placeOrderRow st r card 20000 (at 60)
|
||||
open <- reg st r
|
||||
write st open {nrLive = False} `shouldReturn` Written 2
|
||||
payment st ("inv-" <> r) paid createdAt
|
||||
|
||||
lateCredit :: Text -> Int -> Maybe Int64 -> Int -> LateCredit
|
||||
lateCredit r n units cents =
|
||||
LateCredit
|
||||
{ lcInvoice = InvoiceId ("inv-" <> r),
|
||||
lcCreditNo = n,
|
||||
lcRegistration = RegistrationId r,
|
||||
lcUnits = units,
|
||||
lcInvoiceRate = Just "62500",
|
||||
lcCurrentRate = Just "60000.5",
|
||||
lcRateUsed = Just "60000.5",
|
||||
lcCents = cents
|
||||
}
|
||||
|
||||
creditLate :: DBStore -> LateCredit -> IO Bool
|
||||
creditLate st c = withTransaction st $ \db -> creditLatePayment db c (at 3)
|
||||
|
||||
orderRequest :: Text -> OrderRequest
|
||||
orderRequest r = OrderRequest {orOwner = ownerA, orFields = fieldsN r, orTimestamp = 0, orSignature = signature}
|
||||
|
||||
spendInsert :: Text -> Text -> Int -> Int -> DB.Connection -> UTCTime -> IO (Either OrderRefusal ())
|
||||
spendInsert r src price seen db now = first (const $ ORBalanceChanged Nothing) <$> createBalanceRegistration db (newReg r ownerA (fieldsN r)) (RegistrationId src) price seen now
|
||||
|
||||
closedIds :: Either OrderRefusal [ClosedOrder] -> Either OrderRefusal [(RegistrationId, Int64)]
|
||||
closedIds = fmap $ map $ \ClosedOrder {coRegistration, coVersion} -> (nrId coRegistration, coVersion)
|
||||
|
||||
-- store
|
||||
|
||||
testCredit :: IO ()
|
||||
testCredit = withServiceStore $ \st -> do
|
||||
placeOrderRow st "s" False 20000 (at 60)
|
||||
figures st "s" t0 `shouldReturn` Nothing
|
||||
credit st "s" 20000
|
||||
credit st "s" 2500
|
||||
figures st "s" t0 `shouldReturn` Just (22500, 22500, 0, Nothing)
|
||||
|
||||
testSpendAtOnce :: IO ()
|
||||
testSpendAtOnce = withServiceStore $ \st -> do
|
||||
source st "s" 10000
|
||||
coveredSpend st "c1" "s" 6000 10000 `shouldReturn` Right ()
|
||||
c1 <- reg st "c1"
|
||||
(nrPhase c1, nrLive c1, nrPrice c1, nrPayment c1, nrBalanceSource c1, nrBalanceUsed c1) `shouldBe` (PQueued, True, 6000, RPBalance, Just (RegistrationId "s"), 6000)
|
||||
nrOrderHash c1 `shouldBe` orderHash ownerA (fieldsN "c1") (OTBalance (RegistrationId "s") 6000 10000 Nothing)
|
||||
figures st "s" t0 `shouldReturn` Just (4000, 10000, 0, Nothing)
|
||||
coveredSpend st "c2" "s" 3000 10000 `shouldReturn` Left RRBalanceChanged
|
||||
coveredSpend st "c3" "s" 5000 4000 `shouldReturn` Left RRBalanceChanged
|
||||
mapM_ (absent st) ["c2", "c3"]
|
||||
figures st "s" t0 `shouldReturn` Just (4000, 10000, 0, Nothing)
|
||||
holder st "h" "s" 4000 (at 60) `shouldReturn` Right ()
|
||||
coveredSpend st "c4" "s" 1000 4000 `shouldReturn` Left RRBalanceChanged
|
||||
absent st "c4"
|
||||
release st "h" `shouldReturn` True
|
||||
coveredSpend st "c5" "s" 4000 4000 `shouldReturn` Right ()
|
||||
figures st "s" t0 `shouldReturn` Just (0, 10000, 0, Nothing)
|
||||
|
||||
testTwoHolds :: IO ()
|
||||
testTwoHolds = withServiceStore $ \st -> do
|
||||
source st "s" 10000
|
||||
holder st "h1" "s" 10000 (at 60) `shouldReturn` Right ()
|
||||
holder st "h2" "s" 10000 (at 60) `shouldReturn` Left RRBalanceChanged
|
||||
absent st "h2"
|
||||
h1 <- reg st "h1"
|
||||
(nrPhase h1, nrPayment h1, nrPrice h1, nrBalanceSource h1, nrBalanceUsed h1) `shouldBe` (PUnpaid, RPInvoice btc (InvoiceId "inv-h1"), holdPrice, Just (RegistrationId "s"), 10000)
|
||||
figures st "s" t0 `shouldReturn` Just (10000, 10000, 0, Just $ hold "h1" (at 60) False)
|
||||
release st "h1" `shouldReturn` True
|
||||
holder st "h3" "s" 9000 (at 60) `shouldReturn` Left RRBalanceChanged
|
||||
absent st "h3"
|
||||
figures st "s" t0 `shouldReturn` Just (10000, 10000, 0, Nothing)
|
||||
|
||||
testSpendHeld :: IO ()
|
||||
testSpendHeld = withServiceStore $ \st -> do
|
||||
source st "s" 10000
|
||||
source st "other" 5000
|
||||
holder st "h" "s" 10000 (at 60) `shouldReturn` Right ()
|
||||
holder st "g" "other" 5000 (at 60) `shouldReturn` Right ()
|
||||
let spendBy :: Text -> Int -> IO Bool
|
||||
spendBy h used = withTransaction st $ \db -> spendHeldBalance db (RegistrationId h) used t0
|
||||
spendBy "nobody" 10000 `shouldReturn` False
|
||||
spendBy "h" 10001 `shouldReturn` False
|
||||
figures st "s" t0 `shouldReturn` Just (10000, 10000, 0, Just $ hold "h" (at 60) False)
|
||||
spendBy "g" 5000 `shouldReturn` True
|
||||
figures st "s" t0 `shouldReturn` Just (10000, 10000, 0, Just $ hold "h" (at 60) False)
|
||||
figures st "other" t0 `shouldReturn` Just (0, 5000, 0, Nothing)
|
||||
spendBy "h" 10000 `shouldReturn` True
|
||||
figures st "s" t0 `shouldReturn` Just (0, 10000, 0, Nothing)
|
||||
spendBy "h" 0 `shouldReturn` False
|
||||
|
||||
testRelease :: IO ()
|
||||
testRelease = withServiceStore $ \st -> do
|
||||
source st "s" 10000
|
||||
holder st "h" "s" 10000 (at 60) `shouldReturn` Right ()
|
||||
release st "g" `shouldReturn` False
|
||||
figures st "s" t0 `shouldReturn` Just (10000, 10000, 0, Just $ hold "h" (at 60) False)
|
||||
release st "h" `shouldReturn` True
|
||||
figures st "s" t0 `shouldReturn` Just (10000, 10000, 0, Nothing)
|
||||
release st "h" `shouldReturn` False
|
||||
|
||||
testNoNegativeCents :: IO ()
|
||||
testNoNegativeCents = withServiceStore $ \st -> do
|
||||
source st "s" 10000
|
||||
mapM (\(r, cents) -> coveredSpend st r "s" cents 10000) [("c0", 0), ("c1", -1)] `shouldReturn` replicate 2 (Left RRBalanceChanged)
|
||||
mapM_ (absent st) ["c0", "c1"]
|
||||
figures st "s" t0 `shouldReturn` Just (10000, 10000, 0, Nothing)
|
||||
holder st "h" "s" 10000 (at 60) `shouldReturn` Right ()
|
||||
mapM (\used -> withTransaction st $ \db -> spendHeldBalance db (RegistrationId "h") used t0) [0, -1] `shouldReturn` [False, False]
|
||||
figures st "s" t0 `shouldReturn` Just (10000, 10000, 0, Just $ hold "h" (at 60) False)
|
||||
source st "z" 0
|
||||
holder st "hz" "z" 0 (at 60) `shouldReturn` Left RRBalanceChanged
|
||||
figures st "z" t0 `shouldReturn` Just (0, 0, 0, Nothing)
|
||||
placeOrderRow st "x" False 20000 (at 60)
|
||||
credit st "x" 5000
|
||||
creditLate st (lateCredit "x" 1 Nothing (-1)) `shouldThrow` anyException
|
||||
figures st "x" t0 `shouldReturn` Just (5000, 5000, 0, Nothing)
|
||||
forM_ ["credited", "refunded"] $ \column ->
|
||||
withTransaction st (\db -> DB.execute_ db $ "UPDATE sx_badge_service_name_balances SET " <> column <> " = -1 WHERE registration_id = 's'") `shouldThrow` anyException
|
||||
figures st "s" t0 `shouldReturn` Just (10000, 10000, 0, Just $ hold "h" (at 60) False)
|
||||
|
||||
testRefund :: IO ()
|
||||
testRefund = withServiceStore $ \st -> do
|
||||
source st "s" 10000
|
||||
holder st "h" "s" 10000 (at 60) `shouldReturn` Right ()
|
||||
refund st "s" 10000 `shouldReturn` False
|
||||
figures st "s" t0 `shouldReturn` Just (10000, 10000, 0, Just $ hold "h" (at 60) False)
|
||||
release st "h" `shouldReturn` True
|
||||
mapM (refund st "s") [9999, 10001] `shouldReturn` [False, False]
|
||||
figures st "s" t0 `shouldReturn` Just (10000, 10000, 0, Nothing)
|
||||
refund st "s" 10000 `shouldReturn` True
|
||||
Just Balance {blAmount, blCredited, blRefunded, blRefundedAt} <- withTransaction st $ \db -> getBalance db (RegistrationId "s") t0
|
||||
(blAmount, blCredited, blRefunded, blRefundedAt) `shouldBe` (0, 10000, 10000, Just (at 5))
|
||||
mapM (refund st "s") [0, 10000] `shouldReturn` [False, False]
|
||||
|
||||
testInvariant :: IO ()
|
||||
testInvariant = withServiceStore $ \st -> do
|
||||
source st "s" 30000
|
||||
invariantHolds st "s"
|
||||
coveredSpend st "c1" "s" 5000 30000 `shouldReturn` Right ()
|
||||
invariantHolds st "s"
|
||||
holder st "h1" "s" 25000 (at 60) `shouldReturn` Right ()
|
||||
invariantHolds st "s"
|
||||
h1 <- reg st "h1"
|
||||
withTransaction st (`settleHolder` h1) `shouldReturn` True
|
||||
figures st "s" t0 `shouldReturn` Just (0, 30000, 0, Nothing)
|
||||
invariantHolds st "s"
|
||||
credit st "s" 8000
|
||||
holder st "h2" "s" 8000 (at 60) `shouldReturn` Right ()
|
||||
h2 <- reg st "h2"
|
||||
withTransaction st (\db -> closeOverdue db h2 (at 61)) `shouldReturn` Just (nrVersion h2 + 1)
|
||||
figures st "s" t0 `shouldReturn` Just (8000, 38000, 0, Nothing)
|
||||
invariantHolds st "s"
|
||||
refund st "s" 8000 `shouldReturn` True
|
||||
figures st "s" t0 `shouldReturn` Just (0, 38000, 8000, Nothing)
|
||||
invariantHolds st "s"
|
||||
|
||||
testCreditRefundTwice :: IO ()
|
||||
testCreditRefundTwice = withServiceStore $ \st -> do
|
||||
source st "s" 10000
|
||||
refund st "s" 10000 `shouldReturn` True
|
||||
credit st "s" 4000
|
||||
refund st "s" 4000 `shouldReturn` True
|
||||
figures st "s" t0 `shouldReturn` Just (0, 14000, 14000, Nothing)
|
||||
invariantHolds st "s"
|
||||
|
||||
testRestart :: IO ()
|
||||
testRestart = withServiceStores $ \open -> do
|
||||
st <- open
|
||||
source st "s" 10000
|
||||
source st "t" 8000
|
||||
holder st "h" "s" 10000 (at 60) `shouldReturn` Right ()
|
||||
coveredSpend st "c" "t" 3000 8000 `shouldReturn` Right ()
|
||||
let readBack :: DBStore -> IO (Maybe (Int, Int, Int, Maybe BalanceHold), Maybe (Int, Int, Int, Maybe BalanceHold), NameRegistration, NameRegistration)
|
||||
readBack store = (,,,) <$> figures store "s" t0 <*> figures store "t" t0 <*> reg store "h" <*> reg store "c"
|
||||
stored@(held, spent, _, c) <- readBack st
|
||||
(held, spent, nrBalanceUsed c) `shouldBe` (Just (10000, 10000, 0, Just $ hold "h" (at 60) False), Just (5000, 8000, 0, Nothing), 3000)
|
||||
restarted <- open
|
||||
readBack restarted `shouldReturn` stored
|
||||
|
||||
testByReference :: IO ()
|
||||
testByReference = withServiceStore $ \st -> do
|
||||
source st "s" 10000
|
||||
placeOrderRow st "plain" False 20000 (at 60)
|
||||
let byRef :: Text -> IO (Maybe (RegistrationId, Maybe Int))
|
||||
byRef ref = withTransaction st $ \db -> fmap (fmap (fmap blAmount)) <$> balanceByReference db ref t0
|
||||
mapM byRef ["s", "inv-s"] `shouldReturn` replicate 2 (Just (RegistrationId "s", Just 10000))
|
||||
mapM byRef ["plain", "inv-plain"] `shouldReturn` replicate 2 (Just (RegistrationId "plain", Nothing))
|
||||
byRef "nothing" `shouldReturn` Nothing
|
||||
|
||||
testChain :: IO ()
|
||||
testChain = withServiceStore $ \st -> do
|
||||
source st "a" 20000
|
||||
holder st "b" "a" 20000 (at 60) `shouldReturn` Right ()
|
||||
b <- reg st "b"
|
||||
withTransaction st (`settleHolder` b) `shouldReturn` True
|
||||
queued <- reg st "b"
|
||||
write st queued {nrPhase = PTaken} `shouldReturn` Written (nrVersion queued + 1)
|
||||
credit st "b" holdPrice
|
||||
coveredSpend st "c" "b" 10000 holdPrice `shouldReturn` Right ()
|
||||
withTransaction st (\db -> balanceChain db (RegistrationId "c"))
|
||||
`shouldReturn` [ BalanceLink {lkRegistration = RegistrationId "c", lkPayment = RPBalance, lkPaid = 0, lkFromBalance = 10000, lkLateCredits = []},
|
||||
BalanceLink {lkRegistration = RegistrationId "b", lkPayment = RPInvoice btc (InvoiceId "inv-b"), lkPaid = holdPrice - 20000, lkFromBalance = 20000, lkLateCredits = []},
|
||||
BalanceLink {lkRegistration = RegistrationId "a", lkPayment = RPInvoice btc (InvoiceId "inv-a"), lkPaid = 20000, lkFromBalance = 0, lkLateCredits = []}
|
||||
]
|
||||
|
||||
testChainOfClosed :: IO ()
|
||||
testChainOfClosed = withServiceStore $ \st -> do
|
||||
source st "s" 15000
|
||||
holder st "d" "s" 15000 (at 60) `shouldReturn` Right ()
|
||||
waiters <- newWaiters
|
||||
cancelOpenInvoice st waiters Nothing (InvoiceId "inv-d") (at 2) `shouldReturn` True
|
||||
figures st "s" t0 `shouldReturn` Just (15000, 15000, 0, Nothing)
|
||||
let late = lateCredit "d" 1 (Just 40000) 2400
|
||||
creditLate st late `shouldReturn` True
|
||||
withTransaction st (\db -> balanceChain db (RegistrationId "d"))
|
||||
`shouldReturn` [BalanceLink {lkRegistration = RegistrationId "d", lkPayment = RPInvoice btc (InvoiceId "inv-d"), lkPaid = 0, lkFromBalance = 0, lkLateCredits = [late]}]
|
||||
|
||||
testBalanceOrderHash :: IO ()
|
||||
testBalanceOrderHash = withServiceStore $ \st -> do
|
||||
let o = fieldsN "h"
|
||||
terms = holdTerms "s" 15000
|
||||
base = orderHash ownerA o terms
|
||||
src = RegistrationId "s"
|
||||
variants =
|
||||
[ ("labelHash" :: Text, orderHash ownerA o {ofLabelHash = labelHash "hh"} terms),
|
||||
("length", orderHash ownerA o {ofLength = 2} terms),
|
||||
("duration", orderHash ownerA o {ofDuration = 69292801} terms),
|
||||
("owner", orderHash ownerB o terms),
|
||||
("commitment", orderHash ownerA o {ofCommitment = C.sha256Hash "another"} terms),
|
||||
("sealed", orderHash ownerA o {ofSealed = ofSealed o <> "x"} terms),
|
||||
("paying order", orderHash ownerA o (OTBalance (RegistrationId "t") holdPrice 15000 (Just btc))),
|
||||
("price", orderHash ownerA o (OTBalance src (holdPrice + 1) 15000 (Just btc))),
|
||||
("balance", orderHash ownerA o (OTBalance src holdPrice 15001 (Just btc))),
|
||||
("method", orderHash ownerA o (OTBalance src holdPrice 15000 (Just $ SPMCard CPStripe))),
|
||||
("no method", orderHash ownerA o (OTBalance src holdPrice 15000 Nothing)),
|
||||
("an invoice order", orderHash ownerA o (OTInvoice btc holdPrice))
|
||||
]
|
||||
orderHash ownerA (fieldsN "h") (holdTerms "s" 15000) `shouldBe` base
|
||||
forM_ variants $ \(field, h) -> (field, h == base) `shouldBe` (field, False)
|
||||
source st "s" 15000
|
||||
holder st "h" "s" 15000 (at 60) `shouldReturn` Right ()
|
||||
fmap nrId <$> withTransaction st (`getRegistrationByOrderHash` base) `shouldReturn` Just (RegistrationId "h")
|
||||
|
||||
testFindBalances :: IO ()
|
||||
testFindBalances = withServiceStore $ \st -> do
|
||||
let rid :: Int -> Text
|
||||
rid i = "r" <> T.pack (show i)
|
||||
forM_ [1 .. 52 :: Int] $ \i -> withTransaction st $ \db -> do
|
||||
invoiceRow db ("inv-" <> rid i) False 20000 (at 60)
|
||||
createPaidRegistration db (newReg (rid i) ownerA (fieldsN $ rid i)) (OTInvoice btc 20000) (paidOrder ("inv-" <> rid i)) (at i) `shouldReturn` Right ()
|
||||
credit st "r1" 5000
|
||||
credit st "r2" 3000
|
||||
refund st "r2" 3000 `shouldReturn` True
|
||||
map (nrId . fst) <$> withTransaction st (\db -> findRegistrations db ownerA t0) `shouldReturn` map (RegistrationId . rid) ([52, 51 .. 3] <> [1])
|
||||
|
||||
-- closes
|
||||
|
||||
testClosesRelease :: IO ()
|
||||
testClosesRelease = withServiceStore $ \st -> do
|
||||
waiters <- newWaiters
|
||||
let closes = ["cancel", "sweep", "settled", "next"]
|
||||
forM_ closes $ \c -> do
|
||||
source st ("s-" <> c) 10000
|
||||
holder st ("h-" <> c) ("s-" <> c) 10000 (at 60) `shouldReturn` Right ()
|
||||
cancelOpenInvoice st waiters Nothing (InvoiceId "inv-h-cancel") (at 2) `shouldReturn` True
|
||||
expireOverdue st waiters Nothing (at 61) (at 61) [InvoiceId "inv-h-sweep"] `shouldReturn` [InvoiceId "inv-h-sweep"]
|
||||
settleOrder st waiters Nothing (InvoiceId "inv-h-settled") (SigClosed (rcv 0 Nothing) PaidInPart) (at 2) `shouldReturn` Right ISExpired
|
||||
next <- reg st "h-next"
|
||||
withTransaction st (\db -> closeOverdue db next (at 61)) `shouldReturn` Just (nrVersion next + 1)
|
||||
forM_ closes $ \c -> do
|
||||
(c,) <$> figures st ("s-" <> c) t0 `shouldReturn` (c, Just (10000, 10000, 0, Nothing))
|
||||
(c,) . nrLive <$> reg st ("h-" <> c) `shouldReturn` (c, False)
|
||||
(c,) <$> invoiceStatus st ("inv-h-" <> c) `shouldReturn` (c, "expired")
|
||||
|
||||
testOverdueHolderClosed :: IO ()
|
||||
testOverdueHolderClosed = withOrders $ \Ctx {cStore = st, cOrders} -> do
|
||||
now <- oeNow cOrders
|
||||
source st "s" 10000
|
||||
holder st "h" "s" 10000 (at 60) `shouldReturn` Right ()
|
||||
Just balance <- withTransaction st $ \db -> getBalance db (RegistrationId "s") now
|
||||
(blHold balance, heldBy balance) `shouldBe` (Just $ hold "h" (at 60) True, Nothing)
|
||||
Just h <- withTransaction st $ \db -> overdueHolder db (RegistrationId "s") now
|
||||
nrId h `shouldBe` RegistrationId "h"
|
||||
withTransaction st (\db -> overdueHolder db (RegistrationId "s") t0) `shouldReturn` Nothing
|
||||
closedIds <$> Orders.placeOrder cOrders (orderRequest "c") [h] (\_ _ -> pure $ Left ORBadRequest) `shouldReturn` Left ORBadRequest
|
||||
invoiceStatus st "inv-h" `shouldReturn` "open"
|
||||
nrLive <$> reg st "h" `shouldReturn` True
|
||||
figures st "s" now `shouldReturn` Just (10000, 10000, 0, Just $ hold "h" (at 60) True)
|
||||
closedIds <$> Orders.placeOrder cOrders (orderRequest "c") [h] (spendInsert "c" "s" 6000 10000) `shouldReturn` Right [(RegistrationId "h", nrVersion h + 1)]
|
||||
invoiceStatus st "inv-h" `shouldReturn` "expired"
|
||||
nrLive <$> reg st "h" `shouldReturn` False
|
||||
figures st "s" now `shouldReturn` Just (4000, 10000, 0, Nothing)
|
||||
nrPhase <$> reg st "c" `shouldReturn` PQueued
|
||||
|
||||
testNamedHolders :: IO ()
|
||||
testNamedHolders = withOrders $ \Ctx {cStore = st, cOrders, cWeb} -> do
|
||||
now <- oeNow cOrders
|
||||
source st "s1" 10000
|
||||
holder st "h1" "s1" 10000 (at 60) `shouldReturn` Right ()
|
||||
h1 <- reg st "h1"
|
||||
cancelOpenInvoice st (weWaiters cWeb) Nothing (InvoiceId "inv-h1") now `shouldReturn` True
|
||||
closedIds <$> Orders.placeOrder cOrders (orderRequest "c1") [h1] (spendInsert "c1" "s1" 6000 10000) `shouldReturn` Right []
|
||||
figures st "s1" now `shouldReturn` Just (4000, 10000, 0, Nothing)
|
||||
source st "s2" 10000
|
||||
holder st "h2" "s2" 10000 (at 60) `shouldReturn` Right ()
|
||||
h2 <- reg st "h2"
|
||||
payment st "inv-h2" (cardPaid 100 0) (at 61)
|
||||
Just funded <- withTransaction st $ \db -> getBalance db (RegistrationId "s2") now
|
||||
blHold funded `shouldBe` Just (hold "h2" (at 60) False) {bhFunded = True}
|
||||
closedIds <$> Orders.placeOrder cOrders (orderRequest "c2") [h2] (spendInsert "c2" "s2" 6000 10000) `shouldReturn` Left (ORBalanceChanged $ Just funded)
|
||||
absent st "c2"
|
||||
nrLive <$> reg st "h2" `shouldReturn` True
|
||||
invoiceStatus st "inv-h2" `shouldReturn` "open"
|
||||
|
||||
testNamedHolderNotDue :: IO ()
|
||||
testNamedHolderNotDue = withOrders $ \Ctx {cStore = st, cOrders} -> do
|
||||
now <- oeNow cOrders
|
||||
let expiry = addUTCTime 600 now
|
||||
source st "s" 10000
|
||||
holder st "h" "s" 10000 expiry `shouldReturn` Right ()
|
||||
h <- reg st "h"
|
||||
Just held <- withTransaction st $ \db -> getBalance db (RegistrationId "s") now
|
||||
blHold held `shouldBe` Just (hold "h" expiry False)
|
||||
closedIds <$> Orders.placeOrder cOrders (orderRequest "c") [h] (spendInsert "c" "s" 6000 10000) `shouldReturn` Left (ORBalanceChanged $ Just held)
|
||||
absent st "c"
|
||||
invoiceStatus st "inv-h" `shouldReturn` "open"
|
||||
nrLive <$> reg st "h" `shouldReturn` True
|
||||
figures st "s" now `shouldReturn` Just (10000, 10000, 0, Just $ hold "h" expiry False)
|
||||
|
||||
testCleanupKeepsHolder :: IO ()
|
||||
testCleanupKeepsHolder = withOrders $ \Ctx {cStore = st, cWeb} -> do
|
||||
source st "s" 10000
|
||||
holder st "h" "s" 10000 t0 `shouldReturn` Right ()
|
||||
let due = addUTCTime (unpaidRetention + 1) t0
|
||||
poller <- newPollerEnv st (weWaiters cWeb) Nothing (weHints cWeb) (weProviders cWeb) (poll $ weConfig cWeb)
|
||||
logs <- capturingStderr $ cleanupUnpaid poller due
|
||||
logs `shouldSatisfy` T.isInfixOf "unpaid registration h is kept because it still holds the balance of registration s"
|
||||
nrLive <$> reg st "h" `shouldReturn` True
|
||||
figures st "s" due `shouldReturn` Just (10000, 10000, 0, Just $ hold "h" t0 True)
|
||||
|
||||
-- refunds
|
||||
|
||||
testRecordRefund :: IO ()
|
||||
testRecordRefund = withServiceStore $ \st -> do
|
||||
turns <- newTurns
|
||||
waiters <- newWaiters
|
||||
source st "s" 10000
|
||||
placeOrderRow st "plain" False 20000 (at 60)
|
||||
holder st "h" "s" 10000 (at 60) `shouldReturn` Right ()
|
||||
let refundOf :: Text -> Int -> UTCTime -> IO (Either RefundRefusal RefundRecord)
|
||||
refundOf ref cents now = recordRefund turns st ref cents now
|
||||
refundOf "nothing" 10000 t0 `shouldReturn` Left RefundNoOrder
|
||||
refundOf "plain" 20000 t0 `shouldReturn` Left RefundNoBalance
|
||||
refundOf "s" 10000 t0 `shouldReturn` Left (RefundHeld $ hold "h" (at 60) False)
|
||||
refundOf "inv-s" 10000 (at 61) `shouldReturn` Left (RefundHeld $ hold "h" (at 60) True)
|
||||
figures st "s" t0 `shouldReturn` Just (10000, 10000, 0, Just $ hold "h" (at 60) False)
|
||||
cancelOpenInvoice st waiters Nothing (InvoiceId "inv-h") (at 2) `shouldReturn` True
|
||||
refundOf "s" 9000 t0 `shouldReturn` Left (RefundAmount 10000)
|
||||
chain <- withTransaction st $ \db -> balanceChain db (RegistrationId "s")
|
||||
chain `shouldBe` [BalanceLink {lkRegistration = RegistrationId "s", lkPayment = RPInvoice btc (InvoiceId "inv-s"), lkPaid = 10000, lkFromBalance = 0, lkLateCredits = []}]
|
||||
refundOf "inv-s" 10000 t0 `shouldReturn` Right RefundRecord {rdRegistration = RegistrationId "s", rdCents = 10000, rdChain = chain}
|
||||
figures st "s" t0 `shouldReturn` Just (0, 10000, 10000, Nothing)
|
||||
refundOf "s" 10000 t0 `shouldReturn` Left (RefundAmount 0)
|
||||
turnsCount turns `shouldReturn` 0
|
||||
|
||||
-- late credits
|
||||
|
||||
testCreditLatePayment :: IO ()
|
||||
testCreditLatePayment = withServiceStore $ \st -> do
|
||||
closedWith st "x" False (cryptoPaid 400000 400000) t0
|
||||
let state :: IO (Maybe (Int64, Int, Int))
|
||||
state = withTransaction st $ \db -> fmap (\LateCreditState {lsCreditedUnits, lsCreditedCents, lsCredits} -> (lsCreditedUnits, lsCreditedCents, lsCredits)) <$> lateCreditState db (InvoiceId "inv-x")
|
||||
creditLate st (lateCredit "x" 1 (Just 300000) 3000) `shouldReturn` True
|
||||
creditLate st (lateCredit "x" 1 (Just 100000) 1000) `shouldReturn` False
|
||||
figures st "x" t0 `shouldReturn` Just (3000, 3000, 0, Nothing)
|
||||
state `shouldReturn` Just (300000, 3000, 1)
|
||||
creditLate st (lateCredit "x" 2 (Just 100000) 1000) `shouldReturn` True
|
||||
figures st "x" t0 `shouldReturn` Just (4000, 4000, 0, Nothing)
|
||||
state `shouldReturn` Just (400000, 4000, 2)
|
||||
|
||||
testLateScans :: IO ()
|
||||
testLateScans = withServiceStore $ \st -> do
|
||||
let cases =
|
||||
[ ("uncredited", False, cryptoPaid 300000 300000, Just LPUncredited),
|
||||
("unconfirmed", False, cryptoPaid 300000 0, Just LPUnconfirmed),
|
||||
("monero", False, Paid {pCents = 0, pConfirmedCents = 0, pCrypto = Just "0", pUnits = Just 0, pConfirmedUnits = Just 0, pInFull = True}, Just LPConfirming),
|
||||
("part", False, cryptoPaid 300000 100000, Just LPUnconfirmed),
|
||||
("card", True, cardPaid 5000 5000, Just LPUncredited),
|
||||
("cardpending", True, cardPaid 5000 0, Just LPUnconfirmed),
|
||||
("settledlate", False, cryptoPaid 200000 200000, Just LPUncredited),
|
||||
("uncounted", False, (cryptoPaid 0 0) {pCents = 5000, pUnits = Nothing}, Just LPUncounted),
|
||||
("credited", True, cardPaid 5000 5000, Nothing)
|
||||
]
|
||||
forM_ (zip [1 ..] cases) $ \(i, (r, card, paid, _)) -> closedWith st r card paid (at i)
|
||||
creditLate st (lateCredit "part" 1 (Just 100000) 1500) `shouldReturn` True
|
||||
creditLate st (lateCredit "credited" 1 Nothing 5000) `shouldReturn` True
|
||||
withTransaction st $ \db -> DB.execute db "UPDATE sx_badge_service_invoices SET status = ? WHERE invoice_id = ?" ("paid" :: Text, "inv-settledlate" :: Text)
|
||||
placeOrderRow st "live" False 20000 (at 60)
|
||||
payment st "inv-live" (cryptoPaid 300000 300000) (at 20)
|
||||
let pendingOf :: Text -> IO (Text, Maybe LatePending)
|
||||
pendingOf r = withTransaction st $ \db -> (r,) <$> latePending db (InvoiceId $ "inv-" <> r)
|
||||
forM_ cases $ \(r, _, _, expected) -> pendingOf r `shouldReturn` (r, expected)
|
||||
pendingOf "live" `shouldReturn` ("live", Nothing)
|
||||
withTransaction st uncreditedLateInvoices `shouldReturn` map (InvoiceId . ("inv-" <>)) ["uncredited", "card", "settledlate"]
|
||||
withTransaction st (\db -> lateCreditState db (InvoiceId "inv-part"))
|
||||
`shouldReturn` Just
|
||||
LateCreditState
|
||||
{ lsInvoice = InvoiceId "inv-part",
|
||||
lsRegistration = RegistrationId "part",
|
||||
lsPhase = PUnpaid,
|
||||
lsLive = False,
|
||||
lsCoin = Just CCBtc,
|
||||
lsSupport = Nothing,
|
||||
lsReceivedCents = 20000,
|
||||
lsConfirmedCents = 0,
|
||||
lsReceivedUnits = Just 300000,
|
||||
lsConfirmedUnits = Just 100000,
|
||||
lsInvoiceRate = Just "62500",
|
||||
lsCreditedUnits = 100000,
|
||||
lsCreditedCents = 1500,
|
||||
lsCredits = 1,
|
||||
lsPaymentCreatedAt = at 4
|
||||
}
|
||||
withTransaction st (\db -> lateCreditState db (InvoiceId "inv-plain")) `shouldReturn` Nothing
|
||||
|
||||
testExactUnits :: IO ()
|
||||
testExactUnits = withServiceStore $ \st -> do
|
||||
closedWith st "x" False (cryptoPaid 30000000 30000000) t0
|
||||
creditLate st (lateCredit "x" 1 (Just 10000000) 6000) `shouldReturn` True
|
||||
creditLate st (lateCredit "x" 2 (Just 20000000) 12000) `shouldReturn` True
|
||||
withTransaction st (\db -> latePending db (InvoiceId "inv-x")) `shouldReturn` Nothing
|
||||
withTransaction st uncreditedLateInvoices `shouldReturn` []
|
||||
fmap lsCreditedUnits <$> withTransaction st (\db -> lateCreditState db (InvoiceId "inv-x")) `shouldReturn` Just 30000000
|
||||
|
||||
testConfirmedBeforeCents :: IO ()
|
||||
testConfirmedBeforeCents = withServiceStore $ \st -> do
|
||||
closedWith st "x" False Paid {pCents = 0, pConfirmedCents = 0, pCrypto = Just "0", pUnits = Just 1000000000000, pConfirmedUnits = Just 1000000000000, pInFull = True} t0
|
||||
withTransaction st (\db -> latePending db (InvoiceId "inv-x")) `shouldReturn` Just LPUncredited
|
||||
withTransaction st uncreditedLateInvoices `shouldReturn` [InvoiceId "inv-x"]
|
||||
|
||||
testNoConfirmedFigure :: IO ()
|
||||
testNoConfirmedFigure = withServiceStore $ \st -> do
|
||||
closedWith st "x" False (cryptoPaid 300000 0) {pConfirmedUnits = Nothing} t0
|
||||
withTransaction st (\db -> latePending db (InvoiceId "inv-x")) `shouldReturn` Just LPUnconfirmed
|
||||
|
||||
testLateAlerts :: IO ()
|
||||
testLateAlerts = withServiceStore $ \st -> do
|
||||
closedWith st "old" False (cryptoPaid 300000 0) t0
|
||||
closedWith st "card" True (cardPaid 5000 0) (at 1)
|
||||
closedWith st "done" True (cardPaid 5000 5000) (at 2)
|
||||
creditLate st (lateCredit "done" 1 Nothing 5000) `shouldReturn` True
|
||||
closedWith st "new" False (cryptoPaid 300000 0) (at 120)
|
||||
let due :: IO [LateAlert]
|
||||
due = withTransaction st $ \db -> lateAlertDue db (at 60)
|
||||
marks :: LateAlert -> (InvoiceId, LatePending, Maybe Int64, Maybe UTCTime, Maybe Int64)
|
||||
marks LateAlert {laState = LateCreditState {lsInvoice}, laPending, laReceived, laAlertedAt, laAlertedReceived} = (lsInvoice, laPending, laReceived, laAlertedAt, laAlertedReceived)
|
||||
claim :: LateAlert -> UTCTime -> IO Bool
|
||||
claim alert t = withTransaction st $ \db -> claimLateAlert db alert Nothing t
|
||||
[old, card] <- due
|
||||
map marks [old, card]
|
||||
`shouldBe` [(InvoiceId "inv-old", LPUnconfirmed, Just 300000, Nothing, Nothing), (InvoiceId "inv-card", LPUnconfirmed, Just 5000, Nothing, Nothing)]
|
||||
claim old (at 61) `shouldReturn` True
|
||||
claim old (at 61) `shouldReturn` False
|
||||
claim card (at 61) `shouldReturn` True
|
||||
due `shouldReturn` []
|
||||
withTransaction st $ \db -> DB.execute db "UPDATE sx_badge_service_payments SET received_units = ? WHERE invoice_id = ?" (400000 :: Int64, "inv-old" :: Text)
|
||||
[more] <- due
|
||||
marks more `shouldBe` (InvoiceId "inv-old", LPUnconfirmed, Just 400000, Just (at 61), Just 300000)
|
||||
claim more (at 62) `shouldReturn` True
|
||||
claim more (at 63) `shouldReturn` False
|
||||
due `shouldReturn` []
|
||||
map marks <$> withTransaction st (\db -> lateAlertDue db (at 180)) `shouldReturn` [(InvoiceId "inv-new", LPUnconfirmed, Just 300000, Nothing, Nothing)]
|
||||
|
||||
testUncountedAlertRepeats :: IO ()
|
||||
testUncountedAlertRepeats = withServiceStore $ \st -> do
|
||||
closedWith st "x" False (cryptoPaid 0 0) {pCents = 5000, pUnits = Nothing} t0
|
||||
let due :: IO [LateAlert]
|
||||
due = withTransaction st $ \db -> lateAlertDue db (at 60)
|
||||
[alert] <- due
|
||||
(laPending alert, laReceived alert) `shouldBe` (LPUncounted, Just 5000)
|
||||
withTransaction st (\db -> claimLateAlert db alert Nothing (at 61)) `shouldReturn` True
|
||||
due `shouldReturn` []
|
||||
withTransaction st $ \db -> DB.execute db "UPDATE sx_badge_service_payments SET amount = ? WHERE invoice_id = ?" (6000 :: Int, "inv-x" :: Text)
|
||||
map (\LateAlert {laPending, laReceived, laAlertedReceived} -> (laPending, laReceived, laAlertedReceived)) <$> due `shouldReturn` [(LPUncounted, Just 6000, Just 5000)]
|
||||
|
||||
-- turns
|
||||
|
||||
testBalanceTurn :: IO ()
|
||||
testBalanceTurn = withServiceStore $ \st -> do
|
||||
turns <- newTurns
|
||||
source st "s" 10000
|
||||
inside <- newEmptyMVar
|
||||
proceed <- newEmptyMVar
|
||||
let src = RegistrationId "s"
|
||||
firstHolder <- async $ withBalanceTurn turns src $ do
|
||||
putMVar inside ()
|
||||
takeMVar proceed
|
||||
holder st "h1" "s" 10000 (at 60)
|
||||
takeMVar inside
|
||||
secondHolder <- async $ withBalanceTurn turns src $ holder st "h2" "s" 10000 (at 60)
|
||||
timeout 5000000 (atomically $ balanceTurnCount turns src >>= check . (== 2)) `shouldReturn` Just ()
|
||||
putMVar proceed ()
|
||||
wait firstHolder `shouldReturn` Right ()
|
||||
wait secondHolder `shouldReturn` Left RRBalanceChanged
|
||||
timeout 5000000 (withLabelTurn turns (labelHash "alicebakery") $ withBalanceTurn turns src $ pure ()) `shouldReturn` Just ()
|
||||
turnsCount turns `shouldReturn` 0
|
||||
|
||||
#if defined(dbPostgres)
|
||||
-- | Both transactions begun before either writes, so the second writer waits for the first's row lock and re-reads its condition.
|
||||
together :: DBStore -> DBStore -> (DB.Connection -> IO a) -> (DB.Connection -> IO b) -> IO (a, b)
|
||||
together st1 st2 w1 w2 = do
|
||||
begun <- newTVarIO (0 :: Int)
|
||||
let run :: DBStore -> (DB.Connection -> IO c) -> IO c
|
||||
run st w = withTransaction st $ \db -> do
|
||||
atomically $ modifyTVar' begun (+ 1)
|
||||
atomically $ readTVar begun >>= check . (== 2)
|
||||
w db
|
||||
concurrently (run st1 w1) (run st2 w2)
|
||||
|
||||
testConcurrentWrites :: IO ()
|
||||
testConcurrentWrites = withServiceStores $ \open -> do
|
||||
st <- open
|
||||
other <- open
|
||||
forM_ [1 .. 25 :: Int] $ \n -> do
|
||||
let tag = T.pack (show n)
|
||||
spendSrc = "spend" <> tag
|
||||
heldSrc = "held" <> tag
|
||||
lateSrc = "late" <> tag
|
||||
source st spendSrc 10000
|
||||
(spent, refundedSpend) <-
|
||||
together st other (\db -> createBalanceRegistration db (newReg ("c" <> tag) ownerA (fieldsN $ "c" <> tag)) (RegistrationId spendSrc) 6000 10000 t0) (\db -> refundBalance db (RegistrationId spendSrc) 10000 t0)
|
||||
(n, isRight spent, refundedSpend) `shouldSatisfy` (\(_, a, b) -> a /= b)
|
||||
fmap (\(amount, _, _, _) -> amount) <$> figures st spendSrc t0 `shouldReturn` Just (if refundedSpend then 0 else 4000)
|
||||
invariantHolds st spendSrc
|
||||
source st heldSrc 10000
|
||||
holder st ("h" <> tag) heldSrc 10000 (at 60) `shouldReturn` Right ()
|
||||
h <- reg st ("h" <> tag)
|
||||
(n,) <$> together st other (`settleHolder` h) (\db -> refundBalance db (RegistrationId heldSrc) 10000 t0) `shouldReturn` (n, (True, False))
|
||||
figures st heldSrc t0 `shouldReturn` Just (0, 10000, 0, Nothing)
|
||||
invariantHolds st heldSrc
|
||||
source st lateSrc 10000
|
||||
(credited, refundedLate) <- together st other (\db -> creditLatePayment db (lateCredit lateSrc 1 (Just 50000) 3000) t0) (\db -> refundBalance db (RegistrationId lateSrc) 10000 t0)
|
||||
credited `shouldBe` True
|
||||
(n,) <$> figures st lateSrc t0 `shouldReturn` (n, Just $ if refundedLate then (3000, 13000, 10000, Nothing) else (13000, 13000, 0, Nothing))
|
||||
invariantHolds st lateSrc
|
||||
#endif
|
||||
@@ -0,0 +1,757 @@
|
||||
{-# LANGUAGE CPP #-}
|
||||
{-# LANGUAGE LambdaCase #-}
|
||||
{-# LANGUAGE NamedFieldPuns #-}
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
{-# LANGUAGE TupleSections #-}
|
||||
|
||||
module Bots.StoreService.NamesLateCreditTests (namesLateCreditTests) where
|
||||
|
||||
import Bots.StoreService.NamesBalancesTests (fieldsN, figures, holder, invariantHolds, placeOrderRow, source)
|
||||
import Bots.StoreService.NamesStoreTests (at, newReg, ownerA, reg, t0)
|
||||
import Bots.StoreService.WebTests (StubCall (..), StubState (..), capturingStderr, newStubState, sampleProviderInvoice, setSignals, stubCalls, stubProvider, withServiceStore)
|
||||
import Control.Monad (void)
|
||||
import qualified Data.Aeson as J
|
||||
import Data.Int (Int64)
|
||||
import Data.IORef (IORef, atomicModifyIORef', newIORef)
|
||||
import Data.Text (Text)
|
||||
import qualified Data.Text as T
|
||||
import Data.Time.Clock (UTCTime, addUTCTime, getCurrentTime)
|
||||
import Simplex.Chat.PaymentService.Types (CurrencyAmount (..), InvoiceId (..), InvoiceStatus (..), PaymentProvider (..))
|
||||
import Simplex.Messaging.Agent.Store.Common (DBStore, withTransaction)
|
||||
import qualified Simplex.Messaging.Agent.Store.DB as DB
|
||||
import StoreService.Config (PollConfig (..))
|
||||
import StoreService.Names.Balances (RefundRefusal (..), recordRefund)
|
||||
import StoreService.Names.LateCredits (CreditOutcome (..), creditLateInvoice)
|
||||
import StoreService.Names.Phases (RegistrationId (..))
|
||||
import StoreService.Names.Store
|
||||
import StoreService.Names.Turns (newTurns)
|
||||
import StoreService.Names.View (balanceJSON)
|
||||
import StoreService.Orders (cancelOpenInvoice, settleOrder)
|
||||
import StoreService.Poller (PollerEnv, ReadHints, cleanupUnpaid, creditPass, drainHints, forgetRates, newPollerEnv, newReadHints, queueReadHint)
|
||||
import StoreService.Providers (Confirmed (..), Funded (..), PaymentSignal (..), Provider (..), ProviderError (..), Rate (..), Received (..), Uncreditable (..), settleWindow)
|
||||
import StoreService.Store.Invoices (unpaidRefs)
|
||||
import StoreService.Waiters (Waiters, newWaiters)
|
||||
import Test.Hspec
|
||||
|
||||
#if defined(dbPostgres)
|
||||
import Bots.StoreService.WebTests (withServiceStores)
|
||||
import Control.Concurrent.Async (concurrently)
|
||||
import Control.Concurrent.STM (TVar, atomically, check, modifyTVar', newTVarIO, readTVar)
|
||||
import Control.Monad (forM, forM_)
|
||||
import Data.Maybe (fromJust, fromMaybe)
|
||||
import Simplex.Chat.PaymentService.Types (CryptoCurrency)
|
||||
import StoreService.Names.LateCredits (lateCreditOf)
|
||||
import StoreService.Store.Invoices (lockInvoice)
|
||||
import Database.PostgreSQL.Simple (Only (..))
|
||||
#else
|
||||
import Database.SQLite.Simple (Only (..))
|
||||
#endif
|
||||
|
||||
namesLateCreditTests :: Spec
|
||||
namesLateCreditTests = describe "StoreService names: balance life" $ do
|
||||
describe "settlement" $ do
|
||||
it "queues a held order and spends its hold, the source's amount down by fromBalance" testHeldSettled
|
||||
it "queues a difference order funded before its expiry and settled after it, still open in the database, spending its hold" testFundedThenSettledLate
|
||||
it "queues an order whose hold was removed by hand and alerts naming the order and the balance's order" testHoldNotSpent
|
||||
it "closes an order meeting another live order at settlement, alerts, and credits its payment after" testLiveOrderExists
|
||||
it "releases a difference order's hold in that settlement's transaction and credits its own balance after, by the credit step" testLiveOrderExistsHolder
|
||||
it "refuses a refund while the hold is open and spends the balance at settlement" testSettlementBeforeRefund
|
||||
describe "late credits" $ do
|
||||
it "credits a late payment to the closed order's balance at the lower rate, the released source's balance untouched, logged at info" testLateCredited
|
||||
it "credits at the invoice's rate when the price rose, storing both rates and the rate used" testRisingPrice
|
||||
it "credits a payment confirming over two reports by its increase, and a repeated report once" testGrowingReports
|
||||
it "credits a confirmed part payment the provider's close meets, and a cancel's at the pass, the cancel reading no rate" testCloseAndCancel
|
||||
it "credits nothing for unconfirmed money, logged as pending, then once when it reads Settled with the totals unchanged" testUnconfirmedThenSettled
|
||||
it "never credits a replaced or dropped payment, alerting it once past the window from its payment row, never again" testNeverConfirmed
|
||||
it "alerts a part credit with an unconfirmed rest once, naming its units" testPartCreditAlerted
|
||||
it "logs Monero's zero figure as pending and does not alert it within the window" testMoneroZero
|
||||
it "credits nothing while the rate read fails, warning once, then credits at the next pass" testRateFails
|
||||
it "credits nothing below the rate floor and never after, logging an error, and alerts support naming both rates" testRateFloor
|
||||
it "logs the rate floor of an invoice once while the price moves below it" testFloorLoggedOnce
|
||||
it "alerts confirmed money waiting on the rate read as such, whatever reason was stored before" testWaitingOutranksStoredReason
|
||||
it "warns once of an invoice no provider reads a rate for, and names an invoice with no recorded rate" testRateProblemsNamed
|
||||
it "reads one rate per coin per pass for several invoices, and none when nothing is due" testOneRateReadPerPass
|
||||
it "never credits a late Settled payment on an invoice made under HighSpeed, alerting it past the window" testHighSpeed
|
||||
it "credits at the next pass a late Settled invoice and a settlement whose credit step did not run" testCreditedByPass
|
||||
it "refuses to credit an order that is live again by the time it takes the invoice's lock" testLiveAgain
|
||||
it "alerts once of two instances, and again when more money arrives" testTwoInstancesAlert
|
||||
it "keeps the confirmed figure and the credit when the settled sum falls, crediting nothing on the same sum again" testFallingSum
|
||||
it "credits an invoice past the read window after a hinted read" testHintPastWindow
|
||||
it "credits Stripe's succeeded amount without reading a rate" testStripeCredited
|
||||
it "credits late XMR in piconero when the plugin shows a confirmation, and alerts it to support when it shows none" testXmrLate
|
||||
describe "balances with late credits" $ do
|
||||
it "keeps a credit made while the balance is held, the held spend settling" testCreditWhileHeld
|
||||
it "refuses a covered spend that read the amount before a credit" testSpendBeforeCredit
|
||||
it "sums the refunds over credit, refund, late credit, refund" testCreditRefundTwice
|
||||
it "spends a late credit with a covered spend and refunds the rest" testSpendAndRefundLate
|
||||
describe "the view" $ do
|
||||
it "shows a funded holder past its expiry held with no end time, and an unfunded one before it with its expiry" testHeldUntil
|
||||
it "shows a balance spent to 0 and a refunded one as objects with amount 0" testZeroBalances
|
||||
it "waits confirming, crediting, or support for each reason, on nothing once all is credited, and on support for good below the rate floor" testLateWaits
|
||||
it "finds the order a balance paid and the order holding a balance, none for an overdue unfunded holder" testFindLinks
|
||||
#if defined(dbPostgres)
|
||||
describe "two connections" $ do
|
||||
it "credits once of two credit steps on one invoice, cleanly, where a step reading before the lock is refused" testConcurrentCredits
|
||||
it "credits the confirmed units once against a settlement raising them" testCreditAgainstSettlement
|
||||
#endif
|
||||
|
||||
-- fixtures
|
||||
|
||||
data Late = Late
|
||||
{ lStore :: DBStore,
|
||||
lStub :: IORef StubState,
|
||||
lPoller :: PollerEnv,
|
||||
lHints :: ReadHints,
|
||||
lWaiters :: Waiters
|
||||
}
|
||||
|
||||
withLate :: (Late -> IO a) -> IO a
|
||||
withLate action = withServiceStore (`withLateOn` action)
|
||||
|
||||
-- | Another poller over the store, as another instance or a restarted service runs.
|
||||
withLateOn :: DBStore -> (Late -> IO a) -> IO a
|
||||
withLateOn lStore action = do
|
||||
lStub <- newIORef (newStubState (Right sampleProviderInvoice))
|
||||
lWaiters <- newWaiters
|
||||
lHints <- newReadHints
|
||||
let crypto = stubProvider lStub
|
||||
card = crypto {pProvider = PPStripe, pCurrentRate = Nothing}
|
||||
lPoller <- newPollerEnv lStore lWaiters Nothing lHints [crypto, card] PollConfig {pWaitingSeconds = 1, pIdleSeconds = 1}
|
||||
action Late {lStore, lStub, lPoller, lHints, lWaiters}
|
||||
|
||||
-- | The invoices' rate, 62500 dollars a bitcoin, is 0.0625 cents a satoshi.
|
||||
satCents :: Int64 -> Int
|
||||
satCents units = fromIntegral (units * 625 `div` 10000)
|
||||
|
||||
-- | Bitcoin received and confirmed, in satoshi, at the invoices' rate.
|
||||
btcPaid :: Int64 -> Int64 -> Received
|
||||
btcPaid units confirmed =
|
||||
Received
|
||||
{ rcvAmount = CurrencyAmount (fromIntegral $ satCents units),
|
||||
rcvCrypto = Just (T.pack $ show units),
|
||||
rcvDue = Nothing,
|
||||
rcvUnits = Just units,
|
||||
rcvRate = Just "62500",
|
||||
rcvConfirmed = Confirmed {cfCents = CurrencyAmount (fromIntegral $ satCents confirmed), cfUnits = Just confirmed},
|
||||
rcvUncreditable = Nothing
|
||||
}
|
||||
|
||||
cardPaid :: Int -> Int -> Received
|
||||
cardPaid cents confirmed =
|
||||
Received
|
||||
{ rcvAmount = CurrencyAmount (fromIntegral cents),
|
||||
rcvCrypto = Nothing,
|
||||
rcvDue = Nothing,
|
||||
rcvUnits = Nothing,
|
||||
rcvRate = Nothing,
|
||||
rcvConfirmed = Confirmed {cfCents = CurrencyAmount (fromIntegral confirmed), cfUnits = Nothing},
|
||||
rcvUncreditable = Nothing
|
||||
}
|
||||
|
||||
nothingPaid :: Received
|
||||
nothingPaid = cardPaid 0 0
|
||||
|
||||
-- | 320000 satoshi: 20000 cents at the invoice's rate, 19200 at the stub's current rate of 60000.5.
|
||||
lateUnits :: Int64
|
||||
lateUnits = 320000
|
||||
|
||||
invOf :: Text -> InvoiceId
|
||||
invOf r = InvoiceId ("inv-" <> r)
|
||||
|
||||
refOf :: Text -> Text
|
||||
refOf r = "ref-inv-" <> r
|
||||
|
||||
setRate :: Late -> Either ProviderError Rate -> IO ()
|
||||
setRate Late {lStub} r = atomicModifyIORef' lStub $ \s -> (s {ssRate = r}, ())
|
||||
|
||||
rateOf :: Text -> Rational -> Rate
|
||||
rateOf t v = Rate {rateText = t, rateValue = fromRational v}
|
||||
|
||||
stubRate :: Rate
|
||||
stubRate = rateOf "60000.5" 60000.5
|
||||
|
||||
-- | An unpaid order of 20000 cents, crypto unless card, whose invoice the provider closed with nothing received.
|
||||
closedOrder :: Late -> Text -> Bool -> IO ()
|
||||
closedOrder l@Late {lStore} r card = do
|
||||
placeOrderRow lStore r card 20000 (at 60)
|
||||
settleAt l r (SigClosed nothingPaid PaidInPart) (at 61) `shouldReturn` Right ISExpired
|
||||
NameRegistration {nrPhase, nrLive} <- reg lStore r
|
||||
(nrPhase, nrLive) `shouldBe` (PUnpaid, False)
|
||||
|
||||
-- | The provider reports the signal for the order's invoice, and the poller reads it on a hint, as a webhook asks; the logs.
|
||||
readSignal :: Late -> Text -> PaymentSignal -> IO Text
|
||||
readSignal Late {lStub, lHints, lPoller} r signal = do
|
||||
setSignals lStub [(refOf r, signal)]
|
||||
capturingStderr $ void (queueReadHint lHints (refOf r)) >> drainHints lPoller
|
||||
|
||||
-- | Settled straight in the store at the given time, with no credit step after it.
|
||||
settleAt :: Late -> Text -> PaymentSignal -> UTCTime -> IO (Either Text InvoiceStatus)
|
||||
settleAt Late {lStore, lWaiters} r = settleOrder lStore lWaiters Nothing (invOf r)
|
||||
|
||||
-- | A new pass's credits; the logs.
|
||||
passAt :: Late -> UTCTime -> IO Text
|
||||
passAt Late {lPoller} now = capturingStderr $ forgetRates lPoller >> creditPass lPoller now
|
||||
|
||||
-- | The daily alerts of a newly started instance at the given time, with its rates; the logs.
|
||||
alertsAt :: Late -> Either ProviderError Rate -> UTCTime -> IO Text
|
||||
alertsAt Late {lStore} r now = withLateOn lStore $ \l@Late {lPoller} -> setRate l r >> capturingStderr (cleanupUnpaid lPoller now)
|
||||
|
||||
-- | Amount, credited and refunded of the order's balance.
|
||||
balanceOf :: DBStore -> Text -> IO (Maybe (Int, Int, Int))
|
||||
balanceOf st r = fmap (\(amount, credited, refunded, _) -> (amount, credited, refunded)) <$> figures st r t0
|
||||
|
||||
-- | Units, the invoice's, current and used rates, and cents of each credit of the order's invoice.
|
||||
creditsOf :: DBStore -> Text -> IO [(Maybe Int64, Maybe Text, Maybe Text, Maybe Text, Int)]
|
||||
creditsOf st r =
|
||||
withTransaction st $ \db ->
|
||||
DB.query db "SELECT units, invoice_rate, current_rate, rate_used, cents FROM sx_badge_service_name_late_credits WHERE invoice_id = ? ORDER BY credit_no" (Only $ "inv-" <> r)
|
||||
|
||||
rateCalls :: Late -> IO Int
|
||||
rateCalls Late {lStub} = length . filter isRate <$> stubCalls lStub
|
||||
where
|
||||
isRate = \case
|
||||
StubRate _ -> True
|
||||
_ -> False
|
||||
|
||||
lateWaitOf :: DBStore -> Text -> IO (Maybe LateWait)
|
||||
lateWaitOf st r = withTransaction st $ \db -> lateWait db (invOf r)
|
||||
|
||||
-- | A log line of the level holding the text.
|
||||
logged :: Text -> Text -> Text -> Bool
|
||||
logged level needle = any (\ln -> ("[" <> level <> " ") `T.isPrefixOf` ln && needle `T.isInfixOf` ln) . T.lines
|
||||
|
||||
count :: Text -> Text -> Int
|
||||
count needle = length . T.breakOnAll needle
|
||||
|
||||
-- | The payment rows' created_at, past the read window by the seconds given.
|
||||
pastWindow :: UTCTime -> Integer -> UTCTime
|
||||
pastWindow createdAt by = addUTCTime (settleWindow + fromInteger by) createdAt
|
||||
|
||||
-- settlement
|
||||
|
||||
testHeldSettled :: IO ()
|
||||
testHeldSettled = withLate $ \l@Late {lStore = st} -> do
|
||||
source st "s" 10000
|
||||
holder st "h" "s" 10000 (at 60) `shouldReturn` Right ()
|
||||
settleAt l "h" (SigSettled (btcPaid 480000 480000) (at 10)) (at 10) `shouldReturn` Right ISPaid
|
||||
NameRegistration {nrPhase, nrLive, nrBalanceUsed} <- reg st "h"
|
||||
(nrPhase, nrLive, nrBalanceUsed) `shouldBe` (PQueued, True, 10000)
|
||||
figures st "s" (at 10) `shouldReturn` Just (0, 10000, 0, Nothing)
|
||||
invariantHolds st "s"
|
||||
|
||||
testFundedThenSettledLate :: IO ()
|
||||
testFundedThenSettledLate = withLate $ \l@Late {lStore = st} -> do
|
||||
source st "s" 10000
|
||||
holder st "h" "s" 10000 (at 60) `shouldReturn` Right ()
|
||||
settleAt l "h" (SigFunded (btcPaid 480000 0) PaidInFull) (at 50) `shouldReturn` Right ISOpen
|
||||
settleAt l "h" (SigSettled (btcPaid 480000 480000) (at 120)) (at 120) `shouldReturn` Right ISPaid
|
||||
nrPhase <$> reg st "h" `shouldReturn` PQueued
|
||||
figures st "s" (at 120) `shouldReturn` Just (0, 10000, 0, Nothing)
|
||||
|
||||
testHoldNotSpent :: IO ()
|
||||
testHoldNotSpent = withLate $ \l@Late {lStore = st} -> do
|
||||
source st "unspentsrc" 10000
|
||||
holder st "unspent" "unspentsrc" 10000 (at 60) `shouldReturn` Right ()
|
||||
withTransaction st $ \db -> DB.execute db "UPDATE sx_badge_service_name_balances SET reserved_by = NULL WHERE registration_id = ?" (Only ("unspentsrc" :: Text))
|
||||
logs <- capturingStderr $ settleAt l "unspent" (SigSettled (btcPaid 480000 480000) (at 10)) (at 10) `shouldReturn` Right ISPaid
|
||||
logs `shouldSatisfy` logged "ERROR" "queued registration unspent as paid, but the balance of registration unspentsrc it held could not be spent"
|
||||
nrPhase <$> reg st "unspent" `shouldReturn` PQueued
|
||||
balanceOf st "unspentsrc" `shouldReturn` Just (10000, 10000, 0)
|
||||
|
||||
-- | The unique index keeping one live order per commitment is dropped, so a second live order can meet the first at settlement.
|
||||
meetsLiveOrder :: DBStore -> Text -> IO ()
|
||||
meetsLiveOrder st r = do
|
||||
withTransaction st $ \db -> DB.execute_ db "DROP INDEX sx_badge_service_idx_name_registrations_live_commitment"
|
||||
NameRegistration {nrCommitment} <- reg st r
|
||||
placeOrderRow st "twin" False 20000 (at 60)
|
||||
withTransaction st $ \db -> DB.execute db "UPDATE sx_badge_service_name_registrations SET commitment = ? WHERE registration_id = 'twin'" (Only $ DB.Binary nrCommitment)
|
||||
|
||||
testLiveOrderExists :: IO ()
|
||||
testLiveOrderExists = withLate $ \l@Late {lStore = st} -> do
|
||||
placeOrderRow st "a" False 20000 (at 60)
|
||||
meetsLiveOrder st "a"
|
||||
logs <- readSignal l "a" (SigSettled (btcPaid lateUnits lateUnits) (at 10))
|
||||
logs `shouldSatisfy` logged "ERROR" "was paid while another live order held the commitment, or the owner and name, of registration a"
|
||||
NameRegistration {nrPhase, nrLive} <- reg st "a"
|
||||
(nrPhase, nrLive) `shouldBe` (PUnpaid, False)
|
||||
balanceOf st "a" `shouldReturn` Just (19200, 19200, 0)
|
||||
|
||||
testLiveOrderExistsHolder :: IO ()
|
||||
testLiveOrderExistsHolder = withLate $ \l@Late {lStore = st} -> do
|
||||
source st "s" 10000
|
||||
holder st "a" "s" 10000 (at 60) `shouldReturn` Right ()
|
||||
meetsLiveOrder st "a"
|
||||
setRate l (Left $ ProviderError "rates down")
|
||||
void $ readSignal l "a" (SigSettled (btcPaid lateUnits lateUnits) (at 10))
|
||||
figures st "s" t0 `shouldReturn` Just (10000, 10000, 0, Nothing)
|
||||
balanceOf st "a" `shouldReturn` Nothing
|
||||
setRate l (Right stubRate)
|
||||
void $ passAt l (at 20)
|
||||
balanceOf st "a" `shouldReturn` Just (19200, 19200, 0)
|
||||
invariantHolds st "s"
|
||||
|
||||
testSettlementBeforeRefund :: IO ()
|
||||
testSettlementBeforeRefund = withLate $ \l@Late {lStore = st} -> do
|
||||
turns <- newTurns
|
||||
source st "s" 10000
|
||||
holder st "h" "s" 10000 (at 60) `shouldReturn` Right ()
|
||||
recordRefund turns st "s" 10000 (at 5) >>= (`shouldSatisfy` \case Left (RefundHeld _) -> True; _ -> False)
|
||||
settleAt l "h" (SigSettled (btcPaid 480000 480000) (at 10)) (at 10) `shouldReturn` Right ISPaid
|
||||
recordRefund turns st "s" 10000 (at 11) >>= (`shouldSatisfy` \case Left _ -> True; Right _ -> False)
|
||||
balanceOf st "s" `shouldReturn` Just (0, 10000, 0)
|
||||
|
||||
-- late credits
|
||||
|
||||
testLateCredited :: IO ()
|
||||
testLateCredited = withLate $ \l@Late {lStore = st} -> do
|
||||
source st "paid" 10000
|
||||
holder st "credited" "paid" 10000 (at 60) `shouldReturn` Right ()
|
||||
settleAt l "credited" (SigClosed nothingPaid PaidInPart) (at 61) `shouldReturn` Right ISExpired
|
||||
figures st "paid" t0 `shouldReturn` Just (10000, 10000, 0, Nothing)
|
||||
logs <- readSignal l "credited" (SigClosed (btcPaid lateUnits lateUnits) PaidInPart)
|
||||
logs `shouldSatisfy` logged "INFO" "invoice inv-credited credited 19200 cents to the balance of registration credited for 320000 units at 60000.5 (invoice 62500, current 60000.5)"
|
||||
logs `shouldNotSatisfy` logged "ERROR" "inv-credited"
|
||||
balanceOf st "credited" `shouldReturn` Just (19200, 19200, 0)
|
||||
creditsOf st "credited" `shouldReturn` [(Just lateUnits, Just "62500", Just "60000.5", Just "60000.5", 19200)]
|
||||
figures st "paid" t0 `shouldReturn` Just (10000, 10000, 0, Nothing)
|
||||
|
||||
testRisingPrice :: IO ()
|
||||
testRisingPrice = withLate $ \l@Late {lStore = st} -> do
|
||||
closedOrder l "x" False
|
||||
setRate l (Right $ rateOf "70000" 70000)
|
||||
void $ readSignal l "x" (SigClosed (btcPaid lateUnits lateUnits) PaidInPart)
|
||||
creditsOf st "x" `shouldReturn` [(Just lateUnits, Just "62500", Just "70000", Just "62500", 20000)]
|
||||
balanceOf st "x" `shouldReturn` Just (20000, 20000, 0)
|
||||
|
||||
testGrowingReports :: IO ()
|
||||
testGrowingReports = withLate $ \l@Late {lStore = st} -> do
|
||||
closedOrder l "x" False
|
||||
void $ readSignal l "x" (SigClosed (btcPaid lateUnits 160000) PaidInPart)
|
||||
balanceOf st "x" `shouldReturn` Just (9600, 9600, 0)
|
||||
void $ readSignal l "x" (SigClosed (btcPaid lateUnits 160000) PaidInPart)
|
||||
void $ readSignal l "x" (SigClosed (btcPaid lateUnits lateUnits) PaidInPart)
|
||||
void $ readSignal l "x" (SigClosed (btcPaid lateUnits lateUnits) PaidInPart)
|
||||
map (\(units, _, _, _, cents) -> (units, cents)) <$> creditsOf st "x" `shouldReturn` [(Just 160000, 9600), (Just 160000, 9600)]
|
||||
balanceOf st "x" `shouldReturn` Just (19200, 19200, 0)
|
||||
|
||||
testCloseAndCancel :: IO ()
|
||||
testCloseAndCancel = withLate $ \l@Late {lStore = st, lWaiters} -> do
|
||||
placeOrderRow st "p" False 20000 (at 60)
|
||||
settleAt l "p" (SigFunded (btcPaid lateUnits 160000) PaidInPart) (at 10) `shouldReturn` Right ISOpen
|
||||
void $ readSignal l "p" (SigClosed (btcPaid lateUnits 160000) PaidInPart)
|
||||
nrLive <$> reg st "p" `shouldReturn` False
|
||||
balanceOf st "p" `shouldReturn` Just (9600, 9600, 0)
|
||||
placeOrderRow st "c" False 20000 (at 60)
|
||||
settleAt l "c" (SigFunded (btcPaid lateUnits lateUnits) PaidInFull) (at 10) `shouldReturn` Right ISOpen
|
||||
calls <- rateCalls l
|
||||
cancelOpenInvoice st lWaiters Nothing (invOf "c") (at 20) `shouldReturn` True
|
||||
rateCalls l `shouldReturn` calls
|
||||
balanceOf st "c" `shouldReturn` Nothing
|
||||
void $ passAt l (at 21)
|
||||
balanceOf st "c" `shouldReturn` Just (19200, 19200, 0)
|
||||
|
||||
testUnconfirmedThenSettled :: IO ()
|
||||
testUnconfirmedThenSettled = withLate $ \l@Late {lStore = st} -> do
|
||||
closedOrder l "x" False
|
||||
logs <- readSignal l "x" (SigClosed (btcPaid lateUnits 0) PaidInPart)
|
||||
logs `shouldSatisfy` logged "INFO" "invoice inv-x holds money of its closed order not yet confirmed"
|
||||
balanceOf st "x" `shouldReturn` Nothing
|
||||
void $ readSignal l "x" (SigClosed (btcPaid lateUnits lateUnits) PaidInPart)
|
||||
void $ readSignal l "x" (SigClosed (btcPaid lateUnits lateUnits) PaidInPart)
|
||||
length <$> creditsOf st "x" `shouldReturn` 1
|
||||
balanceOf st "x" `shouldReturn` Just (19200, 19200, 0)
|
||||
|
||||
-- | The order was placed long before the payment, whose own row the window counts from.
|
||||
testNeverConfirmed :: IO ()
|
||||
testNeverConfirmed = withLate $ \l@Late {lStore = st} -> do
|
||||
closedOrder l "never" False
|
||||
let seenAt = at (60 * 24 * 5)
|
||||
alert = "invoice inv-never of order never: 320000 satoshi received, 0 satoshi confirmed, 0 satoshi credited; refund by hand only a transaction confirmed on chain that BTCPay no longer monitors; one still Processing there waits"
|
||||
settleAt l "never" (SigClosed (btcPaid lateUnits 0) PaidInPart) seenAt `shouldReturn` Right ISExpired
|
||||
alertsAt l (Right stubRate) (pastWindow seenAt (-60)) >>= (`shouldNotSatisfy` T.isInfixOf "invoice inv-never of order never")
|
||||
lateWaitOf st "never" `shouldReturn` Just LWConfirming
|
||||
logs <- alertsAt l (Right stubRate) (pastWindow seenAt 60)
|
||||
(count alert logs, logged "ERROR" alert logs) `shouldBe` (1, True)
|
||||
lateWaitOf st "never" `shouldReturn` Just LWSupport
|
||||
alertsAt l (Right stubRate) (pastWindow seenAt (24 * 3600 + 60)) >>= (`shouldNotSatisfy` T.isInfixOf "invoice inv-never of order never")
|
||||
balanceOf st "never" `shouldReturn` Nothing
|
||||
|
||||
testPartCreditAlerted :: IO ()
|
||||
testPartCreditAlerted = withLate $ \l@Late {lStore = st} -> do
|
||||
closedOrder l "part" False
|
||||
settleAt l "part" (SigClosed (btcPaid lateUnits 160000) PaidInPart) (at 100) `shouldReturn` Right ISExpired
|
||||
void $ passAt l (at 101)
|
||||
balanceOf st "part" `shouldReturn` Just (9600, 9600, 0)
|
||||
logs <- alertsAt l (Right stubRate) (pastWindow (at 100) 60)
|
||||
count "invoice inv-part of order part: 320000 satoshi received, 160000 satoshi confirmed, 160000 satoshi credited; refund by hand only" logs `shouldBe` 1
|
||||
alertsAt l (Right stubRate) (pastWindow (at 100) (24 * 3600 + 60)) >>= (`shouldNotSatisfy` T.isInfixOf "invoice inv-part of order part")
|
||||
|
||||
testMoneroZero :: IO ()
|
||||
testMoneroZero = withLate $ \l@Late {lStore = st} -> do
|
||||
closedOrder l "monero" False
|
||||
logs <- readSignal l "monero" (SigFunded (btcPaid 0 0) {rcvCrypto = Nothing} PaidInFull)
|
||||
logs `shouldSatisfy` logged "INFO" "invoice inv-monero holds money of its closed order not yet confirmed"
|
||||
withTransaction st (\db -> latePending db (invOf "monero")) `shouldReturn` Just LPConfirming
|
||||
now <- getCurrentTime
|
||||
alertsAt l (Right stubRate) (addUTCTime 3600 now) >>= (`shouldNotSatisfy` T.isInfixOf "invoice inv-monero of order monero")
|
||||
balanceOf st "monero" `shouldReturn` Nothing
|
||||
|
||||
testRateFails :: IO ()
|
||||
testRateFails = withLate $ \l@Late {lStore = st} -> do
|
||||
closedOrder l "fail1" False
|
||||
closedOrder l "fail2" False
|
||||
setRate l (Left $ ProviderError "rates down for fail1")
|
||||
logs <- readSignal l "fail1" (SigClosed (btcPaid lateUnits lateUnits) PaidInPart)
|
||||
settleAt l "fail2" (SigClosed (btcPaid lateUnits lateUnits) PaidInPart) (at 70) `shouldReturn` Right ISExpired
|
||||
more <- passAt l (at 71)
|
||||
count "late credits wait, as the current rate cannot be read; each pass tries again: rates down for fail1" (logs <> more) `shouldBe` 1
|
||||
lateWaitOf st "fail1" `shouldReturn` Just LWCrediting
|
||||
mapM (balanceOf st) ["fail1", "fail2"] `shouldReturn` [Nothing, Nothing]
|
||||
setRate l (Right stubRate)
|
||||
void $ passAt l (at 72)
|
||||
mapM (balanceOf st) ["fail1", "fail2"] `shouldReturn` replicate 2 (Just (19200, 19200, 0))
|
||||
lateWaitOf st "fail1" `shouldReturn` Nothing
|
||||
|
||||
testRateFloor :: IO ()
|
||||
testRateFloor = withLate $ \l@Late {lStore = st} -> do
|
||||
closedOrder l "floored" False
|
||||
let floored = rateOf "31000" 31000
|
||||
setRate l (Right floored)
|
||||
settleAt l "floored" (SigClosed (btcPaid lateUnits lateUnits) PaidInPart) (at 70) `shouldReturn` Right ISExpired
|
||||
logs <- passAt l (at 71)
|
||||
logs `shouldSatisfy` logged "ERROR" "invoice inv-floored is not credited: the current rate 31000 is below half its rate 62500"
|
||||
balanceOf st "floored" `shouldReturn` Nothing
|
||||
lateWaitOf st "floored" `shouldReturn` Just LWSupport
|
||||
alertsAt l (Right floored) (pastWindow (at 70) 60)
|
||||
>>= (`shouldSatisfy` logged "ERROR" "invoice inv-floored of order floored: 320000 satoshi received, 320000 satoshi confirmed, 0 satoshi credited; confirmed; the coin's price fell by more than half since the invoice (62500, 31000); it is never credited by itself; refund by hand only a transaction confirmed on chain")
|
||||
setRate l (Right stubRate)
|
||||
void $ passAt l (at 72)
|
||||
creditsOf st "floored" `shouldReturn` []
|
||||
withTransaction st uncreditedLateInvoices >>= (`shouldNotSatisfy` elem (invOf "floored"))
|
||||
lateWaitOf st "floored" `shouldReturn` Just LWSupport
|
||||
|
||||
testFloorLoggedOnce :: IO ()
|
||||
testFloorLoggedOnce = withLate $ \l -> do
|
||||
closedOrder l "floorlog" False
|
||||
settleAt l "floorlog" (SigClosed (btcPaid lateUnits lateUnits) PaidInPart) (at 70) `shouldReturn` Right ISExpired
|
||||
setRate l (Right $ rateOf "31000" 31000)
|
||||
first <- passAt l (at 71)
|
||||
setRate l (Right $ rateOf "30000" 30000)
|
||||
second <- passAt l (at 72)
|
||||
count "invoice inv-floorlog is not credited" (first <> second) `shouldBe` 1
|
||||
|
||||
-- | A reason stored by an earlier read, as one without the invoice's policy would store HighSpeed.
|
||||
testWaitingOutranksStoredReason :: IO ()
|
||||
testWaitingOutranksStoredReason = withLate $ \l@Late {lStore = st} -> do
|
||||
closedOrder l "outranked" False
|
||||
withTransaction st $ \db -> setLateSupport db (invOf "outranked") LSHighSpeed
|
||||
settleAt l "outranked" (SigClosed (btcPaid lateUnits lateUnits) PaidInPart) (at 70) `shouldReturn` Right ISExpired
|
||||
alertsAt l (Left $ ProviderError "rates down for outranked") (pastWindow (at 70) 60)
|
||||
>>= (`shouldSatisfy` logged "ERROR" "invoice inv-outranked of order outranked: 320000 satoshi received, 320000 satoshi confirmed, 0 satoshi credited; confirmed, the credit waits on the rate read; do not refund; fix the rate read")
|
||||
|
||||
testRateProblemsNamed :: IO ()
|
||||
testRateProblemsNamed = withLate $ \l@Late {lStore = st} -> do
|
||||
closedOrder l "noprovider" False
|
||||
settleAt l "noprovider" (SigClosed (btcPaid lateUnits lateUnits) PaidInPart) (at 70) `shouldReturn` Right ISExpired
|
||||
withTransaction st $ \db -> DB.execute_ db "UPDATE sx_badge_service_invoices SET provider = 'apple' WHERE invoice_id = 'inv-noprovider'"
|
||||
closedOrder l "norate" False
|
||||
settleAt l "norate" (SigClosed (btcPaid lateUnits lateUnits) {rcvRate = Nothing} PaidInPart) (at 70) `shouldReturn` Right ISExpired
|
||||
logs <- (<>) <$> passAt l (at 71) <*> passAt l (at 72)
|
||||
count "invoice inv-noprovider has late money to credit, but no provider" logs `shouldBe` 1
|
||||
logs `shouldSatisfy` logged "ERROR" "invoice inv-norate has confirmed late money, but no invoice rate was recorded to credit it at"
|
||||
|
||||
testOneRateReadPerPass :: IO ()
|
||||
testOneRateReadPerPass = withLate $ \l@Late {lStore = st} -> do
|
||||
mapM_ (\r -> closedOrder l r False >> settleAt l r (SigClosed (btcPaid lateUnits lateUnits) PaidInPart) (at 70)) ["x", "y", "z"]
|
||||
closedOrder l "card" True
|
||||
settleAt l "card" (SigSettled (cardPaid 20000 20000) (at 70)) (at 70) `shouldReturn` Right ISPaid
|
||||
void $ passAt l (at 71)
|
||||
rateCalls l `shouldReturn` 1
|
||||
mapM (balanceOf st) ["x", "y", "z", "card"] `shouldReturn` replicate 3 (Just (19200, 19200, 0)) <> [Just (20000, 20000, 0)]
|
||||
void $ passAt l (at 72)
|
||||
rateCalls l `shouldReturn` 1
|
||||
|
||||
testHighSpeed :: IO ()
|
||||
testHighSpeed = withLate $ \l@Late {lStore = st} -> do
|
||||
closedOrder l "hs" False
|
||||
let highSpeed = (btcPaid lateUnits 0) {rcvUncreditable = Just UCHighSpeed}
|
||||
settleAt l "hs" (SigSettled highSpeed (at 70)) (at 70) `shouldReturn` Right ISPaid
|
||||
void $ passAt l (at 71)
|
||||
balanceOf st "hs" `shouldReturn` Nothing
|
||||
lateWaitOf st "hs" `shouldReturn` Just LWSupport
|
||||
alertsAt l (Right stubRate) (pastWindow (at 70) 60)
|
||||
>>= (`shouldSatisfy` logged "ERROR" "invoice inv-hs of order hs: 320000 satoshi received, 0 satoshi confirmed, 0 satoshi credited; the invoice was made under HighSpeed")
|
||||
|
||||
testCreditedByPass :: IO ()
|
||||
testCreditedByPass = withLate $ \l@Late {lStore = st} -> do
|
||||
closedOrder l "settled" False
|
||||
settleAt l "settled" (SigSettled (btcPaid lateUnits lateUnits) (at 70)) (at 70) `shouldReturn` Right ISPaid
|
||||
closedOrder l "crashed" False
|
||||
settleAt l "crashed" (SigClosed (btcPaid lateUnits lateUnits) PaidInPart) (at 70) `shouldReturn` Right ISExpired
|
||||
mapM (balanceOf st) ["settled", "crashed"] `shouldReturn` [Nothing, Nothing]
|
||||
void $ passAt l (at 71)
|
||||
mapM (balanceOf st) ["settled", "crashed"] `shouldReturn` replicate 2 (Just (19200, 19200, 0))
|
||||
|
||||
testLiveAgain :: IO ()
|
||||
testLiveAgain = withLate $ \l@Late {lStore = st} -> do
|
||||
closedOrder l "x" False
|
||||
settleAt l "x" (SigClosed (btcPaid lateUnits lateUnits) PaidInPart) (at 70) `shouldReturn` Right ISExpired
|
||||
let liveAgain _ = do
|
||||
withTransaction st $ \db -> DB.execute_ db "UPDATE sx_badge_service_name_registrations SET live = 1 WHERE registration_id = 'x'"
|
||||
pure (Right stubRate)
|
||||
creditLateInvoice st liveAgain (invOf "x") (at 71) `shouldReturn` CONothingDue
|
||||
balanceOf st "x" `shouldReturn` Nothing
|
||||
creditsOf st "x" `shouldReturn` []
|
||||
|
||||
testTwoInstancesAlert :: IO ()
|
||||
testTwoInstancesAlert = withLate $ \l -> do
|
||||
closedOrder l "twice" False
|
||||
settleAt l "twice" (SigClosed (btcPaid lateUnits 0) PaidInPart) (at 70) `shouldReturn` Right ISExpired
|
||||
let first = "invoice inv-twice of order twice: 320000 satoshi received"
|
||||
logs <- (<>) <$> alertsAt l (Right stubRate) (pastWindow (at 70) 60) <*> alertsAt l (Right stubRate) (pastWindow (at 70) 60)
|
||||
count first logs `shouldBe` 1
|
||||
settleAt l "twice" (SigClosed (btcPaid 400000 0) PaidInPart) (at 80) `shouldReturn` Right ISExpired
|
||||
alertsAt l (Right stubRate) (pastWindow (at 70) 120) >>= (`shouldSatisfy` logged "ERROR" "invoice inv-twice of order twice: 400000 satoshi received, 0 satoshi confirmed")
|
||||
|
||||
testFallingSum :: IO ()
|
||||
testFallingSum = withLate $ \l@Late {lStore = st} -> do
|
||||
closedOrder l "x" False
|
||||
void $ readSignal l "x" (SigClosed (btcPaid lateUnits lateUnits) PaidInPart)
|
||||
void $ readSignal l "x" (SigClosed (btcPaid lateUnits 160000) PaidInPart)
|
||||
confirmed <- withTransaction st $ \db -> DB.query db "SELECT confirmed_units FROM sx_badge_service_payments WHERE invoice_id = 'inv-x'" ()
|
||||
confirmed `shouldBe` [Only (Just lateUnits)]
|
||||
void $ readSignal l "x" (SigClosed (btcPaid lateUnits lateUnits) PaidInPart)
|
||||
length <$> creditsOf st "x" `shouldReturn` 1
|
||||
balanceOf st "x" `shouldReturn` Just (19200, 19200, 0)
|
||||
|
||||
testHintPastWindow :: IO ()
|
||||
testHintPastWindow = withLate $ \l@Late {lStore = st} -> do
|
||||
closedOrder l "x" False
|
||||
now <- getCurrentTime
|
||||
let longAgo = addUTCTime (negate $ settleWindow + 3600) now
|
||||
withTransaction st $ \db -> DB.execute db "UPDATE sx_badge_service_invoices SET created_at = ? WHERE invoice_id = 'inv-x'" (Only longAgo)
|
||||
unpaidRefs st (addUTCTime (negate settleWindow) now) >>= (`shouldNotSatisfy` elem ("crypto", refOf "x"))
|
||||
void $ readSignal l "x" (SigClosed (btcPaid lateUnits lateUnits) PaidInPart)
|
||||
balanceOf st "x" `shouldReturn` Just (19200, 19200, 0)
|
||||
|
||||
testStripeCredited :: IO ()
|
||||
testStripeCredited = withLate $ \l@Late {lStore = st} -> do
|
||||
closedOrder l "c" True
|
||||
void $ readSignal l "c" (SigSettled (cardPaid 20000 20000) (at 70))
|
||||
creditsOf st "c" `shouldReturn` [(Nothing, Nothing, Nothing, Nothing, 20000)]
|
||||
balanceOf st "c" `shouldReturn` Just (20000, 20000, 0)
|
||||
rateCalls l `shouldReturn` 0
|
||||
|
||||
-- | 0.32095 XMR at the invoice's rate of 168.25, all of it Settled; uncreditable unless the plugin shows a confirmation.
|
||||
xmrPaid :: Maybe Uncreditable -> Received
|
||||
xmrPaid uncreditable =
|
||||
Received
|
||||
{ rcvAmount = CurrencyAmount 5400,
|
||||
rcvCrypto = Just "0.32095000",
|
||||
rcvDue = Nothing,
|
||||
rcvUnits = Just xmrUnits,
|
||||
rcvRate = Just "168.25",
|
||||
rcvConfirmed = maybe (Confirmed {cfCents = CurrencyAmount 5400, cfUnits = Just xmrUnits}) (const Confirmed {cfCents = CurrencyAmount 0, cfUnits = Just 0}) uncreditable,
|
||||
rcvUncreditable = uncreditable
|
||||
}
|
||||
where
|
||||
xmrUnits = 320950000000
|
||||
|
||||
testXmrLate :: IO ()
|
||||
testXmrLate = withLate $ \l@Late {lStore = st} -> do
|
||||
mapM_ (\r -> closedOrder l r False) ["xmrshown", "xmrnone"]
|
||||
withTransaction st $ \db -> DB.execute_ db "UPDATE sx_badge_service_invoices SET payment_crypto_currency = 'xmr' WHERE invoice_id IN ('inv-xmrshown', 'inv-xmrnone')"
|
||||
setRate l (Right $ rateOf "150" 150)
|
||||
void $ readSignal l "xmrshown" (SigSettled (xmrPaid Nothing) (at 70))
|
||||
creditsOf st "xmrshown" `shouldReturn` [(Just 320950000000, Just "168.25", Just "150", Just "150", 4814)]
|
||||
void $ readSignal l "xmrnone" (SigSettled (xmrPaid $ Just UCNoConfirmationShown) (at 70))
|
||||
balanceOf st "xmrnone" `shouldReturn` Nothing
|
||||
lateWaitOf st "xmrnone" `shouldReturn` Just LWSupport
|
||||
now <- getCurrentTime
|
||||
alertsAt l (Right stubRate) (pastWindow now 60)
|
||||
>>= (`shouldSatisfy` logged "ERROR" "invoice inv-xmrnone of order xmrnone: 320950000000 piconero received, 0 piconero confirmed, 0 piconero credited; the Monero plugin shows no confirmation of this money, so it is never credited by itself; refund by hand only a transaction confirmed on chain")
|
||||
|
||||
-- balances with late credits
|
||||
|
||||
testCreditWhileHeld :: IO ()
|
||||
testCreditWhileHeld = withLate $ \l@Late {lStore = st} -> do
|
||||
closedOrder l "x" False
|
||||
void $ readSignal l "x" (SigClosed (btcPaid lateUnits lateUnits) PaidInPart)
|
||||
holder st "h" "x" 19200 (at 60) `shouldReturn` Right ()
|
||||
void $ readSignal l "x" (SigClosed (btcPaid 400000 400000) PaidInPart)
|
||||
figures st "x" (at 10) `shouldReturn` Just (24000, 24000, 0, Just BalanceHold {bhHolder = RegistrationId "h", bhUntil = at 60, bhOverdue = False, bhFunded = False})
|
||||
settleAt l "h" (SigSettled (btcPaid 330000 330000) (at 10)) (at 10) `shouldReturn` Right ISPaid
|
||||
figures st "x" (at 10) `shouldReturn` Just (4800, 24000, 0, Nothing)
|
||||
invariantHolds st "x"
|
||||
|
||||
coveredSpend :: DBStore -> Text -> Text -> Int -> Int -> IO (Either RegistrationRefused ())
|
||||
coveredSpend st r src price seen = withTransaction st $ \db -> createBalanceRegistration db (newReg r ownerA (fieldsN r)) (RegistrationId src) price seen t0
|
||||
|
||||
testSpendBeforeCredit :: IO ()
|
||||
testSpendBeforeCredit = withLate $ \l@Late {lStore = st} -> do
|
||||
closedOrder l "x" False
|
||||
void $ readSignal l "x" (SigClosed (btcPaid lateUnits lateUnits) PaidInPart)
|
||||
void $ readSignal l "x" (SigClosed (btcPaid 400000 400000) PaidInPart)
|
||||
coveredSpend st "c" "x" 10000 19200 `shouldReturn` Left RRBalanceChanged
|
||||
coveredSpend st "c" "x" 10000 24000 `shouldReturn` Right ()
|
||||
balanceOf st "x" `shouldReturn` Just (14000, 24000, 0)
|
||||
|
||||
testCreditRefundTwice :: IO ()
|
||||
testCreditRefundTwice = withLate $ \l@Late {lStore = st} -> do
|
||||
turns <- newTurns
|
||||
closedOrder l "x" False
|
||||
void $ readSignal l "x" (SigClosed (btcPaid lateUnits 160000) PaidInPart)
|
||||
void (recordRefund turns st "x" 9600 (at 80) >>= either (fail . show) pure)
|
||||
void $ readSignal l "x" (SigClosed (btcPaid lateUnits lateUnits) PaidInPart)
|
||||
void (recordRefund turns st "inv-x" 9600 (at 81) >>= either (fail . show) pure)
|
||||
balanceOf st "x" `shouldReturn` Just (0, 19200, 19200)
|
||||
invariantHolds st "x"
|
||||
|
||||
testSpendAndRefundLate :: IO ()
|
||||
testSpendAndRefundLate = withLate $ \l@Late {lStore = st} -> do
|
||||
turns <- newTurns
|
||||
closedOrder l "x" False
|
||||
void $ readSignal l "x" (SigClosed (btcPaid lateUnits lateUnits) PaidInPart)
|
||||
coveredSpend st "c" "x" 10000 19200 `shouldReturn` Right ()
|
||||
nrBalanceSource <$> reg st "c" `shouldReturn` Just (RegistrationId "x")
|
||||
recordRefund turns st "x" 10000 (at 80) >>= (`shouldSatisfy` \case Left (RefundAmount 9200) -> True; _ -> False)
|
||||
void (recordRefund turns st "x" 9200 (at 80) >>= either (fail . show) pure)
|
||||
balanceOf st "x" `shouldReturn` Just (0, 19200, 9200)
|
||||
|
||||
-- the view
|
||||
|
||||
balanceAt :: DBStore -> Text -> UTCTime -> IO (Maybe J.Value)
|
||||
balanceAt st r now = fmap balanceJSON <$> withTransaction st (\db -> getBalance db (RegistrationId r) now)
|
||||
|
||||
balanceObject :: Int -> Bool -> Maybe UTCTime -> Int -> J.Value
|
||||
balanceObject amount held heldUntil refunded = J.object ["amount" J..= amount, "held" J..= held, "heldUntil" J..= heldUntil, "refunded" J..= refunded]
|
||||
|
||||
testHeldUntil :: IO ()
|
||||
testHeldUntil = withLate $ \l@Late {lStore = st} -> do
|
||||
source st "funded" 10000
|
||||
holder st "fh" "funded" 10000 (at 60) `shouldReturn` Right ()
|
||||
source st "unfunded" 10000
|
||||
holder st "uh" "unfunded" 10000 (at 60) `shouldReturn` Right ()
|
||||
balanceAt st "funded" (at 30) `shouldReturn` Just (balanceObject 10000 True (Just $ at 60) 0)
|
||||
settleAt l "fh" (SigFunded (btcPaid 100 0) PaidInPart) (at 30) `shouldReturn` Right ISOpen
|
||||
balanceAt st "funded" (at 30) `shouldReturn` Just (balanceObject 10000 True Nothing 0)
|
||||
balanceAt st "funded" (at 120) `shouldReturn` Just (balanceObject 10000 True Nothing 0)
|
||||
balanceAt st "unfunded" (at 30) `shouldReturn` Just (balanceObject 10000 True (Just $ at 60) 0)
|
||||
balanceAt st "unfunded" (at 120) `shouldReturn` Just (balanceObject 10000 False Nothing 0)
|
||||
|
||||
testZeroBalances :: IO ()
|
||||
testZeroBalances = withLate $ \Late {lStore = st} -> do
|
||||
turns <- newTurns
|
||||
source st "spent" 10000
|
||||
coveredSpend st "c" "spent" 10000 10000 `shouldReturn` Right ()
|
||||
balanceAt st "spent" t0 `shouldReturn` Just (balanceObject 0 False Nothing 0)
|
||||
source st "refunded" 10000
|
||||
void (recordRefund turns st "refunded" 10000 (at 5) >>= either (fail . show) pure)
|
||||
balanceAt st "refunded" t0 `shouldReturn` Just (balanceObject 0 False Nothing 10000)
|
||||
placeOrderRow st "none" False 20000 (at 60)
|
||||
balanceAt st "none" t0 `shouldReturn` Nothing
|
||||
|
||||
testLateWaits :: IO ()
|
||||
testLateWaits = withLate $ \l@Late {lStore = st} -> do
|
||||
mapM_ (\r -> closedOrder l r False) ["confirming", "crediting", "highspeed", "units", "floor", "alerted"]
|
||||
settleAt l "crediting" (SigClosed (btcPaid lateUnits lateUnits) PaidInPart) (at 70) `shouldReturn` Right ISExpired
|
||||
settleAt l "highspeed" (SigClosed (btcPaid lateUnits 0) {rcvUncreditable = Just UCHighSpeed} PaidInPart) (at 70) `shouldReturn` Right ISExpired
|
||||
settleAt l "units" (SigClosed (btcPaid 0 0) {rcvAmount = CurrencyAmount 20000, rcvCrypto = Just "0.003200001", rcvUnits = Nothing, rcvUncreditable = Just UCUncounted} PaidInPart) (at 70) `shouldReturn` Right ISExpired
|
||||
settleAt l "alerted" (SigClosed (btcPaid lateUnits 0) PaidInPart) (at 70) `shouldReturn` Right ISExpired
|
||||
void $ alertsAt l (Right stubRate) (pastWindow (at 70) 60)
|
||||
settleAt l "confirming" (SigClosed (btcPaid lateUnits 0) PaidInPart) (pastWindow (at 70) 60) `shouldReturn` Right ISExpired
|
||||
setRate l (Right $ rateOf "31000" 31000)
|
||||
void $ readSignal l "floor" (SigClosed (btcPaid lateUnits lateUnits) PaidInPart)
|
||||
placeOrderRow st "open" False 20000 (at 60)
|
||||
settleAt l "open" (SigFunded (btcPaid lateUnits 0) PaidInFull) (at 70) `shouldReturn` Right ISOpen
|
||||
let waits = mapM (\r -> (r,) <$> lateWaitOf st r)
|
||||
waits ["confirming", "crediting", "highspeed", "units", "floor", "alerted", "open"]
|
||||
`shouldReturn` [ ("confirming", Just LWConfirming),
|
||||
("crediting", Just LWCrediting),
|
||||
("highspeed", Just LWSupport),
|
||||
("units", Just LWSupport),
|
||||
("floor", Just LWSupport),
|
||||
("alerted", Just LWSupport),
|
||||
("open", Nothing)
|
||||
]
|
||||
setRate l (Right stubRate)
|
||||
void $ readSignal l "alerted" (SigClosed (btcPaid lateUnits lateUnits) PaidInPart)
|
||||
void $ passAt l (at 71)
|
||||
waits ["crediting", "floor", "alerted"] `shouldReturn` [("crediting", Nothing), ("floor", Just LWSupport), ("alerted", Nothing)]
|
||||
|
||||
testFindLinks :: IO ()
|
||||
testFindLinks = withLate $ \Late {lStore = st} -> do
|
||||
source st "paying" 10000
|
||||
coveredSpend st "spend" "paying" 10000 10000 `shouldReturn` Right ()
|
||||
source st "held" 10000
|
||||
holder st "holder" "held" 10000 (at 60) `shouldReturn` Right ()
|
||||
let links now = map (\(NameRegistration {nrId = RegistrationId r, nrBalanceSource}, heldBy') -> (r, nrBalanceSource, heldBy')) <$> withTransaction st (\db -> findRegistrations db ownerA now)
|
||||
linked rows = filter (\(_, src, h) -> src /= Nothing || h /= Nothing) rows
|
||||
linked <$> links (at 30) `shouldReturn` [("spend", Just (RegistrationId "paying"), Nothing), ("holder", Just (RegistrationId "held"), Nothing), ("held", Nothing, Just (RegistrationId "holder"))]
|
||||
linked <$> links (at 120) `shouldReturn` [("spend", Just (RegistrationId "paying"), Nothing), ("holder", Just (RegistrationId "held"), Nothing)]
|
||||
|
||||
#if defined(dbPostgres)
|
||||
-- | Each thread waits here until both arrive, after its unlocked read and before its locked transaction.
|
||||
meet :: TVar Int -> IO ()
|
||||
meet arrived = atomically (modifyTVar' arrived (+ 1)) >> atomically (readTVar arrived >>= check . (== 2))
|
||||
|
||||
rounds :: Int
|
||||
rounds = 20
|
||||
|
||||
testConcurrentCredits :: IO ()
|
||||
testConcurrentCredits = withServiceStores $ \open -> do
|
||||
st <- open
|
||||
other <- open
|
||||
withLateOn st $ \l -> do
|
||||
let due :: Text -> IO ()
|
||||
due r = do
|
||||
closedOrder l r False
|
||||
settleAt l r (SigClosed (btcPaid lateUnits lateUnits) PaidInPart) (at 70) `shouldReturn` Right ISExpired
|
||||
forM_ [1 .. rounds] $ \n -> do
|
||||
let r = "x" <> T.pack (show n)
|
||||
due r
|
||||
arrived <- newTVarIO 0
|
||||
let readRate :: CryptoCurrency -> IO (Either ProviderError Rate)
|
||||
readRate _ = Right stubRate <$ meet arrived
|
||||
(a, b) <- concurrently (creditLateInvoice st readRate (invOf r) (at 80)) (creditLateInvoice other readRate (invOf r) (at 80))
|
||||
(n, length [() | COCredited _ <- [a, b]], length [() | CONothingDue <- [a, b]]) `shouldBe` (n, 1, 1)
|
||||
length <$> creditsOf st r `shouldReturn` 1
|
||||
balanceOf st r `shouldReturn` Just (19200, 19200, 0)
|
||||
refused <- forM [1 .. rounds] $ \n -> do
|
||||
let r = "stale" <> T.pack (show n)
|
||||
due r
|
||||
arrived <- newTVarIO 0
|
||||
let staleStep :: DBStore -> IO Bool
|
||||
staleStep store = do
|
||||
Just s <- withTransaction store (`lateCreditState` invOf r)
|
||||
meet arrived
|
||||
withTransaction store $ \db -> do
|
||||
lockInvoice db (invOf r) (at 80)
|
||||
creditLatePayment db (fromJust $ lateCreditOf s (Just stubRate)) (at 80)
|
||||
(a, b) <- concurrently (staleStep st) (staleStep other)
|
||||
balanceOf st r `shouldReturn` Just (19200, 19200, 0)
|
||||
pure $ length (filter not [a, b])
|
||||
sum refused `shouldSatisfy` (> 0)
|
||||
|
||||
testCreditAgainstSettlement :: IO ()
|
||||
testCreditAgainstSettlement = withServiceStores $ \open -> do
|
||||
st <- open
|
||||
other <- open
|
||||
otherWaiters <- newWaiters
|
||||
withLateOn st $ \l -> forM_ [1 .. rounds] $ \n -> do
|
||||
let r = "x" <> T.pack (show n)
|
||||
closedOrder l r False
|
||||
settleAt l r (SigClosed (btcPaid lateUnits 160000) PaidInPart) (at 70) `shouldReturn` Right ISExpired
|
||||
arrived <- newTVarIO 0
|
||||
let readRate :: CryptoCurrency -> IO (Either ProviderError Rate)
|
||||
readRate _ = Right stubRate <$ meet arrived
|
||||
raise :: IO (Either Text InvoiceStatus)
|
||||
raise = meet arrived >> settleOrder other otherWaiters Nothing (invOf r) (SigClosed (btcPaid lateUnits lateUnits) PaidInPart) (at 80)
|
||||
(credited, raised) <- concurrently (creditLateInvoice st readRate (invOf r) (at 80)) raise
|
||||
(n, raised) `shouldBe` (n, Right ISExpired)
|
||||
credited `shouldSatisfy` \case COCredited _ -> True; _ -> False
|
||||
creditLateInvoice st (const $ pure $ Right stubRate) (invOf r) (at 81) >>= (`shouldSatisfy` (/= CORefused))
|
||||
units <- map (\(u, _, _, _, _) -> u) <$> creditsOf st r
|
||||
(n, sum (map (fromMaybe 0) units)) `shouldBe` (n, lateUnits)
|
||||
balanceOf st r `shouldReturn` Just (19200, 19200, 0)
|
||||
#endif
|
||||
@@ -7,12 +7,15 @@ module Bots.StoreService.NamesOrdersTests
|
||||
Ctx (..),
|
||||
Order (..),
|
||||
withOrders,
|
||||
withOrdersVia,
|
||||
withOrdersOn,
|
||||
withOrdersCancelling,
|
||||
withSettings,
|
||||
configured,
|
||||
codesOnly,
|
||||
aliceOrder,
|
||||
commitmentOf,
|
||||
fieldsOf,
|
||||
orderTime,
|
||||
placeOrder,
|
||||
placed,
|
||||
@@ -30,6 +33,7 @@ module Bots.StoreService.NamesOrdersTests
|
||||
issueCode,
|
||||
registered,
|
||||
registrationById,
|
||||
registrationsOf,
|
||||
field,
|
||||
advance,
|
||||
refusedWith,
|
||||
@@ -39,7 +43,7 @@ where
|
||||
import Bots.StoreService.FakeBTCPay (FakeBTCPay (..), setInvoiceState, withFakeBTCPay)
|
||||
import Bots.StoreService.FakeEthNode
|
||||
import Bots.StoreService.NamesContractsTests (alice, answerRegistered, answerRegistrar, nameExpiresCall, noncesCall, registrarOf, rentPriceAnswer, rentPriceCall, reservedNamesCall, unhex)
|
||||
import Bots.StoreService.NamesStoreTests (btc, order, ownerA, ownerB, placeCode, placePaid, t0)
|
||||
import Bots.StoreService.NamesStoreTests (btc, insertInvoiceRow, newReg, order, ownerA, ownerB, paidOrder, placeCode, placePaid, t0)
|
||||
import Bots.StoreService.WebTests
|
||||
import Control.Concurrent (threadDelay)
|
||||
import Control.Concurrent.Async (async, concurrently, wait)
|
||||
@@ -92,7 +96,7 @@ import StoreService.Names.Phases (RegistrationId (..), awaitChange, newPhases)
|
||||
import StoreService.Names.Signatures (OrderFields (..), orderMessage, personalDigest)
|
||||
import StoreService.Names.Store
|
||||
import StoreService.Names.Turns (newTurns, withCodeTurn)
|
||||
import StoreService.Names.View (ViewReads (..), readViewChain, viewJSON)
|
||||
import StoreService.Names.View (ViewReads (..), readViewChain, registrationView, viewJSON)
|
||||
import StoreService.Orders (cancelOpenInvoice, expireOverdue, settleOrder)
|
||||
import StoreService.Poller (cleanupInterval, cleanupReadsPerPass, cleanupUnpaid, drainHints, newPollerEnv, newReadHints, queueReadHint, runOnePass, unpaidRetention)
|
||||
import StoreService.Providers.BTCPay (btcpayProvider)
|
||||
@@ -177,6 +181,7 @@ namesOrdersTests = describe "StoreService names: orders" $ do
|
||||
it "has the contract's fields" testViewFields
|
||||
it "reads the intent nonce in committed and nothing in taken" testViewReads
|
||||
it "leaves a failed intentNonce read null and named in unread, reading nothing in taken" testViewUnread
|
||||
it "reads the order's balance, held until its holder's invoice expires and free past it, and the cents its order took from another's" testViewBalance
|
||||
|
||||
-- fixtures
|
||||
|
||||
@@ -279,6 +284,8 @@ withSignature sig = KM.insert "signature" (J.String sig)
|
||||
|
||||
data Ctx = Ctx
|
||||
{ cStore :: DBStore,
|
||||
-- | Another store over the same database, as a second process opens one.
|
||||
cOpenStore :: IO DBStore,
|
||||
cNode :: FakeEthNode,
|
||||
cOrders :: OrdersEnv,
|
||||
cWeb :: WebEnv,
|
||||
@@ -317,7 +324,11 @@ withOrders = withOrdersVia id
|
||||
|
||||
-- | With the providers changed as a test needs them.
|
||||
withOrdersVia :: (Provider -> Provider) -> (Ctx -> IO a) -> IO a
|
||||
withOrdersVia via action = withServiceStore $ \cStore -> withFakeEthNode $ \cNode -> do
|
||||
withOrdersVia via action = withServiceStores $ \open -> withOrdersOn open via action
|
||||
|
||||
-- | Over the stores the action opens.
|
||||
withOrdersOn :: IO DBStore -> (Provider -> Provider) -> (Ctx -> IO a) -> IO a
|
||||
withOrdersOn cOpenStore via action = cOpenStore >>= \cStore -> withFakeEthNode $ \cNode -> do
|
||||
cRandom <- C.newRandom
|
||||
ct <- newContracts TLDSimplex =<< newChainClient cRandom (fakeChainConfig cNode)
|
||||
turns <- newTurns
|
||||
@@ -340,7 +351,7 @@ withOrdersVia via action = withServiceStore $ \cStore -> withFakeEthNode $ \cNod
|
||||
let cWeb = built {weOrders = Just cOrders}
|
||||
mgr <- newManager defaultManagerSettings
|
||||
Warp.testWithApplicationSettings (webSettings (listener cfg)) (pure $ ordersApp cWeb cOrders) $ \port ->
|
||||
action Ctx {cStore, cNode, cOrders, cWeb, cClient = (mgr, "http://127.0.0.1:" <> show port), cStub, cClock, cRandom, cIps}
|
||||
action Ctx {cStore, cOpenStore, cNode, cOrders, cWeb, cClient = (mgr, "http://127.0.0.1:" <> show port), cStub, cClock, cRandom, cIps}
|
||||
|
||||
-- | The context's store, chain, providers and clock with its names settings changed, as after a restart.
|
||||
configured :: (NamesConfig -> NamesConfig) -> Ctx -> Ctx
|
||||
@@ -424,7 +435,7 @@ advance :: Ctx -> NominalDiffTime -> IO ()
|
||||
advance Ctx {cClock} by = modifyIORef' cClock (addUTCTime by)
|
||||
|
||||
registrationsOf :: Ctx -> Address -> IO [NameRegistration]
|
||||
registrationsOf Ctx {cStore} owner = withTransaction cStore (`findRegistrations` owner)
|
||||
registrationsOf Ctx {cStore, cClock} owner = readIORef cClock >>= \now -> map fst <$> withTransaction cStore (\db -> findRegistrations db owner now)
|
||||
|
||||
invoiceRegistration :: Ctx -> InvoiceId -> IO NameRegistration
|
||||
invoiceRegistration Ctx {cStore} invId =
|
||||
@@ -971,7 +982,7 @@ testCodeNotReservable = withOrders $ \ctx@Ctx {cStore} -> do
|
||||
req <- fromJust . Orders.parseOrderRequest <$> signedBody (cRandom ctx) aliceOrder
|
||||
let new = NewRegistration {nrgId = RegistrationId "late", nrgOwner = ownerA, nrgOrder = fieldsOf aliceOrder, nrgYears = 2}
|
||||
forM_ [(reservedLate, CRReserved), (revokedLate, CRInvalid)] $ \(stale, refusal) -> do
|
||||
placedOrder <- Orders.placeOrder (cOrders ctx) req (Orders.codeOrderInsert new stale)
|
||||
placedOrder <- Orders.placeOrder (cOrders ctx) req [] (Orders.codeOrderInsert new stale)
|
||||
either Just (const Nothing) placedOrder `shouldBe` Just (Orders.ORCode refusal)
|
||||
length <$> registrationsOf ctx ownerA `shouldReturn` 0
|
||||
|
||||
@@ -1054,7 +1065,7 @@ testLatePaymentAfterNewOrder = withOrders $ \ctx -> do
|
||||
now <- readIORef (cClock ctx)
|
||||
(newInv, _) <- placed ctx aliceOrder {oCommitment = commitmentOf 2, oTimestamp = seconds now, oDuration = durationAt now}
|
||||
logs <- capturingStderr $ settleNow ctx oldInv settled `shouldReturn` Right ISPaid
|
||||
logs `shouldSatisfy` T.isInfixOf "refund"
|
||||
logs `shouldSatisfy` T.isInfixOf "credited to its balance"
|
||||
old <- invoiceRegistration ctx oldInv
|
||||
(nrPhase old, nrLive old) `shouldBe` (PUnpaid, False)
|
||||
new <- invoiceRegistration ctx newInv
|
||||
@@ -1088,28 +1099,28 @@ testLateBTCPayPayments = withFakeBTCPay $ \fake -> do
|
||||
let refOf inv = maybe (error "no invoice") irProviderRef <$> getInvoice st inv
|
||||
readAt ref = queueReadHint (weHints cWeb) ref >> drainHints poller
|
||||
paidLate ref fields = capturingStderr $ setInvoiceState fake ref fields >> readAt ref
|
||||
alerted logs = T.isInfixOf "stays unpaid; refund the payment" logs
|
||||
alerted (InvoiceId t) logs = T.isInfixOf ("invoice " <> t <> " received money after registration") logs
|
||||
later = addUTCTime 3600 orderTime
|
||||
(expired, _) <- placed ctx aliceOrder
|
||||
expiredRef <- refOf expired
|
||||
setInvoiceState fake expiredRef ["status" .= ("Expired" :: Text)]
|
||||
readAt expiredRef
|
||||
(irStatus <$>) <$> getInvoice st expired `shouldReturn` Just ISExpired
|
||||
paidLate expiredRef ["additionalStatus" .= ("PaidLate" :: Text), "paymentMethodPaid" .= ("0.00050000" :: Text)] >>= (`shouldSatisfy` alerted)
|
||||
capturingStderr (readAt expiredRef) >>= (`shouldNotSatisfy` alerted)
|
||||
paidLate expiredRef ["additionalStatus" .= ("PaidLate" :: Text), "paymentMethodPaid" .= ("0.00050000" :: Text)] >>= (`shouldSatisfy` alerted expired)
|
||||
capturingStderr (readAt expiredRef) >>= (`shouldNotSatisfy` alerted expired)
|
||||
(cancelled, _) <- placed ctx aliceOrder {oLabel = "dynamis", oPrice = 20000, oCommitment = commitmentOf 2}
|
||||
cancelledRef <- refOf cancelled
|
||||
cancelOpenInvoice st (weWaiters cWeb) (Just $ oePhases $ cOrders ctx) cancelled later `shouldReturn` True
|
||||
paidLate cancelledRef ["status" .= ("Invalid" :: Text), "paymentMethodPaid" .= ("0.00078000" :: Text)] >>= (`shouldSatisfy` alerted)
|
||||
paidLate cancelledRef ["status" .= ("Invalid" :: Text), "paymentMethodPaid" .= ("0.00078000" :: Text)] >>= (`shouldSatisfy` alerted cancelled)
|
||||
(swept, _) <- placed ctx aliceOrder {oOwner = ownerBText, oKey = keyB, oCommitment = commitmentOf 3}
|
||||
sweptRef <- refOf swept
|
||||
expireOverdue st (weWaiters cWeb) (Just $ oePhases $ cOrders ctx) later later [swept] `shouldReturn` [swept]
|
||||
paidLate sweptRef ["paymentMethodPaid" .= ("0.00025000" :: Text)] >>= (`shouldSatisfy` alerted)
|
||||
paidLate sweptRef ["paymentMethodPaid" .= ("0.00025000" :: Text)] >>= (`shouldSatisfy` alerted swept)
|
||||
forM_ [expired, cancelled, swept] $ \inv -> do
|
||||
r <- invoiceRegistration ctx inv
|
||||
(nrPhase r, nrLive r) `shouldBe` (PUnpaid, False)
|
||||
|
||||
-- | Paid in part while open, then expired by BTCPay with the same figures: one refund line, none from a restarted poller.
|
||||
-- | Paid in part while open, then expired by BTCPay with the same figures: one late payment line, none from a restarted poller.
|
||||
testOneLateAlert :: IO ()
|
||||
testOneLateAlert = withOrders $ \ctx@Ctx {cStore = st, cWeb} -> do
|
||||
(inv, _) <- placed ctx aliceOrder
|
||||
@@ -1117,14 +1128,15 @@ testOneLateAlert = withOrders $ \ctx@Ctx {cStore = st, cWeb} -> do
|
||||
let paid = rcv 5000 (Just "0.00078")
|
||||
newPoller = newPollerEnv st (weWaiters cWeb) (Just $ oePhases $ cOrders ctx) (weHints cWeb) (weProviders cWeb) (poll $ weConfig cWeb)
|
||||
readWith poller = capturingStderr $ queueReadHint (weHints cWeb) ref >> drainHints poller
|
||||
refunds = length . T.breakOnAll "refund"
|
||||
InvoiceId invText = inv
|
||||
refunds = length . T.breakOnAll ("invoice " <> invText <> " received money after")
|
||||
poller <- newPoller
|
||||
setSignals (cStub ctx) [(ref, SigFunded paid PaidInPart)]
|
||||
refunds <$> readWith poller `shouldReturn` 0
|
||||
setSignals (cStub ctx) [(ref, SigClosed paid PaidInPart)]
|
||||
logs <- readWith poller
|
||||
refunds logs `shouldBe` 1
|
||||
logs `shouldSatisfy` T.isInfixOf "stays unpaid; refund the payment"
|
||||
logs `shouldSatisfy` T.isInfixOf "it stays unpaid, and its money is credited to its balance once confirmed, else alerted"
|
||||
restarted <- newPoller
|
||||
refunds <$> readWith restarted `shouldReturn` 0
|
||||
(nrPhase &&& nrLive) <$> invoiceRegistration ctx inv `shouldReturn` (PUnpaid, False)
|
||||
@@ -1166,7 +1178,7 @@ testCancelAlertsFunded = withOrdersCancelling (SigFunded paid PaidInPart) $ \ctx
|
||||
where
|
||||
paid = rcv 5000 (Just "0.00078")
|
||||
invoiceText (InvoiceId t) = t
|
||||
alertOf invId = "invoice " <> invoiceText invId <> " was paid after its order closed"
|
||||
alertOf invId = "invoice " <> invoiceText invId <> " received money after"
|
||||
|
||||
testNamesOff :: IO ()
|
||||
testNamesOff = withOrders $ \ctx -> do
|
||||
@@ -1219,7 +1231,7 @@ testLatePayment = withOrders $ \ctx -> do
|
||||
fst <$> post ctx ("/api/invoice/" <> T.unpack t <> "/cancel") "" `shouldReturn` 200
|
||||
closed <- invoiceRegistration ctx invId
|
||||
logs <- capturingStderr $ settleNow ctx invId settled `shouldReturn` Right ISPaid
|
||||
logs `shouldSatisfy` T.isInfixOf ("registration " <> (\(RegistrationId r) -> r) (nrId closed) <> " stays unpaid")
|
||||
logs `shouldSatisfy` T.isInfixOf ("registration " <> (\(RegistrationId r) -> r) (nrId closed) <> " closed; it stays unpaid")
|
||||
invoiceRegistration ctx invId `shouldReturn` closed
|
||||
r <- webGet (cClient ctx) ("/api/invoice/" <> T.unpack t)
|
||||
v <- jsonObject r
|
||||
@@ -1320,7 +1332,7 @@ testCleanupIn ctx@Ctx {cStore = st} = do
|
||||
isNothing <$> getInvoice st (InvoiceId "inv-gone") `shouldReturn` True
|
||||
Just InvoiceRow {irPayment = latePayment} <- getInvoice st (InvoiceId "inv-late")
|
||||
(ipCryptoPaid <$> latePayment) `shouldBe` Just (Just "0.00078")
|
||||
logs `shouldSatisfy` T.isInfixOf "registration late is kept because invoice inv-late received a payment"
|
||||
logs `shouldSatisfy` T.isInfixOf "registration late is kept with its balance, because invoice inv-late received a payment"
|
||||
logs `shouldSatisfy` T.isInfixOf "registration unread is kept until the next run"
|
||||
reads' <- stubReads
|
||||
sort reads' `shouldBe` [ref "gone", ref "late"]
|
||||
@@ -1396,13 +1408,16 @@ testViewFields :: IO ()
|
||||
testViewFields = withServiceStore $ \st -> withFakeEthNode $ \node -> do
|
||||
Right () <- placePaid st "r1" ownerA (order "alicebakery" 1) (addUTCTime 3600 t0)
|
||||
r <- withTransaction st $ \db -> fromJust <$> getRegistration db (RegistrationId "r1")
|
||||
let v = objectOf $ viewJSON (testNamesConfig node) r ViewReads {vrIntentNonce = Nothing, vrUnread = []}
|
||||
let v = objectOf $ viewJSON (testNamesConfig node) r Nothing Nothing ViewReads {vrIntentNonce = Nothing, vrUnread = []}
|
||||
sort (KM.keys v)
|
||||
`shouldBe` sort
|
||||
[ "id", "version", "moves", "linksRefused", "phase", "labelHash", "label", "owner", "commitment", "sealed", "resolver", "sponsor", "chainId", "tld",
|
||||
"years", "duration", "price", "commitTx", "registerTx", "revealAfter", "revealBefore", "intentNonce", "unread", "expiresAt", "error"
|
||||
"years", "duration", "price", "fromBalance", "balance", "latePayment", "commitTx", "registerTx", "revealAfter", "revealBefore", "intentNonce", "unread", "expiresAt", "error"
|
||||
]
|
||||
map (`field` v) ["id", "phase", "owner", "tld", "chainId", "linksRefused", "label", "unread", "sponsor"]
|
||||
field "latePayment" v `shouldBe` Just J.Null
|
||||
let waiting w = field "latePayment" $ objectOf $ viewJSON (testNamesConfig node) r Nothing (Just w) ViewReads {vrIntentNonce = Nothing, vrUnread = []}
|
||||
map waiting [LWConfirming, LWCrediting, LWSupport] `shouldBe` map (\t -> Just $ J.object ["waiting" .= (t :: Text)]) ["confirming", "crediting", "support"]
|
||||
map (`field` v) ["id", "phase", "owner", "tld", "chainId", "linksRefused", "label", "unread", "sponsor", "fromBalance", "balance"]
|
||||
`shouldBe` map
|
||||
Just
|
||||
[ "r1",
|
||||
@@ -1413,7 +1428,9 @@ testViewFields = withServiceStore $ \st -> withFakeEthNode $ \node -> do
|
||||
J.Bool False,
|
||||
J.Null,
|
||||
J.Array mempty,
|
||||
J.String $ safeDecodeUtf8 $ strEncode fakeSponsor
|
||||
J.String $ safeDecodeUtf8 $ strEncode fakeSponsor,
|
||||
J.Number 0,
|
||||
J.Null
|
||||
]
|
||||
|
||||
testViewReads :: IO ()
|
||||
@@ -1440,5 +1457,35 @@ testViewUnread = withServiceStore $ \st -> withFakeEthNode $ \node -> do
|
||||
r <- withTransaction st $ \db -> fromJust <$> getRegistration db (RegistrationId "paid")
|
||||
readViewChain ct r {nrPhase = PCommitted} `shouldReturn` ViewReads Nothing ["intentNonce"]
|
||||
readViewChain ct r {nrPhase = PTaken} `shouldReturn` ViewReads Nothing []
|
||||
let v = objectOf $ viewJSON (testNamesConfig node) r {nrPhase = PCommitted} (ViewReads Nothing ["intentNonce"])
|
||||
let v = objectOf $ viewJSON (testNamesConfig node) r {nrPhase = PCommitted} Nothing Nothing (ViewReads Nothing ["intentNonce"])
|
||||
(field "intentNonce" v, field "unread" v) `shouldBe` (Just J.Null, Just (J.toJSON ["intentNonce" :: Text]))
|
||||
|
||||
testViewBalance :: IO ()
|
||||
testViewBalance = withServiceStore $ \st -> withFakeEthNode $ \node -> do
|
||||
g <- C.newRandom
|
||||
ct <- newContracts TLDSimplex =<< newChainClient g (fakeChainConfig node)
|
||||
let holderExpiry = addUTCTime 3600 t0
|
||||
viewOf :: Text -> UTCTime -> IO J.Object
|
||||
viewOf rid now = do
|
||||
r <- withTransaction st $ \db -> fromJust <$> getRegistration db (RegistrationId rid)
|
||||
objectOf <$> registrationView st (testNamesConfig node) ct now r
|
||||
balanceOf :: J.Object -> (Maybe J.Value, Maybe J.Value)
|
||||
balanceOf v = (field "balance" v, field "fromBalance" v)
|
||||
balance :: Int -> Bool -> Maybe UTCTime -> Int -> J.Value
|
||||
balance amount held heldUntil refunded = J.object ["amount" .= amount, "held" .= held, "heldUntil" .= heldUntil, "refunded" .= refunded]
|
||||
Right () <- placePaid st "source" ownerA (order "alicebakery" 1) holderExpiry
|
||||
withTransaction st $ \db -> creditBalance db (RegistrationId "source") 15000 t0
|
||||
balanceOf <$> viewOf "source" t0 `shouldReturn` (Just $ balance 15000 False Nothing 0, Just $ J.Number 0)
|
||||
Right () <- withTransaction st $ \db -> do
|
||||
insertInvoiceRow db "inv-holder" holderExpiry "open"
|
||||
let terms = OTBalance (RegistrationId "source") 20000 15000 (Just btc)
|
||||
createPaidRegistration db (newReg "holder" ownerA (order "bobsbakery" 2)) terms (paidOrder "inv-holder") t0
|
||||
balanceOf <$> viewOf "source" t0 `shouldReturn` (Just $ balance 15000 True (Just holderExpiry) 0, Just $ J.Number 0)
|
||||
balanceOf <$> viewOf "source" (addUTCTime 1 holderExpiry) `shouldReturn` (Just $ balance 15000 False Nothing 0, Just $ J.Number 0)
|
||||
balanceOf <$> viewOf "holder" t0 `shouldReturn` (Just J.Null, Just $ J.Number 15000)
|
||||
version <- nrVersion <$> withTransaction st (\db -> fromJust <$> getRegistration db (RegistrationId "source"))
|
||||
withTransaction st (\db -> releaseHeldBalance db (RegistrationId "holder") t0) `shouldReturn` True
|
||||
withTransaction st (\db -> refundBalance db (RegistrationId "source") 15000 t0) `shouldReturn` True
|
||||
v <- viewOf "source" t0
|
||||
balanceOf v `shouldBe` (Just $ balance 0 False Nothing 15000, Just $ J.Number 0)
|
||||
field "version" v `shouldBe` Just (J.toJSON version)
|
||||
@@ -17,6 +17,7 @@ import Simplex.Messaging.Encoding.String (strDecode)
|
||||
import Simplex.Messaging.Eth.Address (Address, recoverAddress)
|
||||
import Simplex.Messaging.SimplexName (SimplexTLD (..), labelHash)
|
||||
import StoreService.Names.Abi
|
||||
import StoreService.Names.Phases (RegistrationId (..))
|
||||
import StoreService.Names.Registration
|
||||
import StoreService.Names.Signatures
|
||||
import Test.Hspec
|
||||
@@ -37,6 +38,12 @@ namesSignatureTests = describe "StoreService names: signatures" $ do
|
||||
"simplex.domains order 0x78b602f03f164366531da963764c1f2fdfd588d0487daf2aa261ca799e5ffe33 7 69259500 0x9cf04ddef2eedfb02e6e7ba58f879c0636c584b6acc67ffe9f97a06bfb016ac1 0xb1971beb567c8dc1b2f01f0d823754c6168d8d6830db2221702a7678e1804674 1792574100"
|
||||
"0x5deee1b3589df9e53665e34aa65a491a4eabfd76a39207b0e9303457f7c44b7a"
|
||||
"0x73e32be461e99e64b093a4ad09b04b4d810e5623a1b0e9c9fdb4701ec2a6a2a84df9ffdccc39c5cb827cde4d846c7662f591665f1b868ab1c15778646d3f414e1b"
|
||||
it "signs a spend from an order's balance, as the webapp signs it" $
|
||||
testMessage
|
||||
(spendMessage registrationId spendOrder timestamp)
|
||||
"simplex.domains spend t2Jk8RmQ4vXw9NcP3yLb6g 0x5bfbbf75311ec002834031d73fa30bfe8bdf675f4a3df72443841490c4b49d02 7 69259500 0xbb87d2d7aa14251a04cdd68b5d878d0b4c44c6c76486d90a534dab9525105e33 0x51431a705eb4903084cc8dbf3c1b966c9372914511c4623c889d49fdb8047da4 1792574100"
|
||||
"0x72c2f4b7d84839fb97eb78668355a02fc0b18e211f264fca97d19a8f36decde3"
|
||||
"0x8668cb4b72295479b4f9bcc2fd07fabfec2b4b8ae9230f2553536acb93c3e0cf6b2dad928a9a11b003c43ab43edeec117ce01c9214b8e99fe75fd547425e74481b"
|
||||
describe "signature format" $ do
|
||||
it "refuses a high s, though recovery accepts it" testHighS
|
||||
it "refuses v other than 27 or 28" $
|
||||
@@ -119,6 +126,17 @@ dynamisOrder =
|
||||
ofSealed = "q3Zk0Yx7c2VhbGVkLW9yZGVyLWZpeHR1cmU"
|
||||
}
|
||||
|
||||
-- the webapp's spend vector (test/flow.test.ts, SPEND): "another" with no links, sealed under a zero IV
|
||||
spendOrder :: OrderFields
|
||||
spendOrder =
|
||||
OrderFields
|
||||
{ ofLabelHash = labelHash "another",
|
||||
ofLength = 7,
|
||||
ofDuration = duration,
|
||||
ofCommitment = hx "0xbb87d2d7aa14251a04cdd68b5d878d0b4c44c6c76486d90a534dab9525105e33",
|
||||
ofSealed = "AAAAAAAAAAAAAAAACWgxqMk-UKfpra_bgbzR57AIDvSNmCR_G7IYbN7DX70sL2FVRHB1VfC0wdF-tc3ajHM3o8koM159Ja8hyg"
|
||||
}
|
||||
|
||||
commitment :: ByteString
|
||||
commitment = hx "0x9cf04ddef2eedfb02e6e7ba58f879c0636c584b6acc67ffe9f97a06bfb016ac1"
|
||||
|
||||
@@ -133,6 +151,9 @@ timestamp = 1792574100
|
||||
duration :: Word64
|
||||
duration = 69259500
|
||||
|
||||
registrationId :: RegistrationId
|
||||
registrationId = RegistrationId "t2Jk8RmQ4vXw9NcP3yLb6g"
|
||||
|
||||
orderSignature :: Text
|
||||
orderSignature = "0x73e32be461e99e64b093a4ad09b04b4d810e5623a1b0e9c9fdb4701ec2a6a2a84df9ffdccc39c5cb827cde4d846c7662f591665f1b868ab1c15778646d3f414e1b"
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ module Bots.StoreService.NamesStoreTests (namesStoreTests, at, btc, insertInvoic
|
||||
import Bots.StoreService.WebTests (columnsOf, digestFixture, runMigrations, withServiceStore)
|
||||
import Control.Arrow ((&&&))
|
||||
import Control.Monad (forM_, void)
|
||||
import Data.Int (Int64)
|
||||
import Data.List (sort)
|
||||
import Data.Maybe (fromJust, mapMaybe)
|
||||
import Data.Text (Text)
|
||||
@@ -21,8 +22,8 @@ import Simplex.Messaging.Agent.Store.Common (DBStore, withTransaction)
|
||||
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)
|
||||
import Simplex.Messaging.SimplexName (labelHash)
|
||||
import Simplex.Messaging.Eth.Address (Address, unAddress)
|
||||
import Simplex.Messaging.SimplexName (LabelHash (..), labelHash)
|
||||
import StoreService.Names.Chain (TxHash (..))
|
||||
import StoreService.Names.Phases (RegistrationId (..))
|
||||
import StoreService.Names.Signatures (OrderFields (..), parseAnyCaseAddress, parseSignature)
|
||||
@@ -45,6 +46,7 @@ namesStoreTests = describe "StoreService names: store" $ do
|
||||
it "creates the names tables with the planned columns" testNamesColumns
|
||||
it "rolls back and re-applies only the names migrations, with rows in them, leaving the badge tables and paid invoices as they were" testNamesDownUp
|
||||
it "turns a code_issued order taken at price 0 and not live at its next version, dropping issued_code_id with its index and foreign key, which the down migration restores" testDropTakenCodes
|
||||
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
|
||||
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
|
||||
@@ -134,7 +136,7 @@ insertInvoiceRow db invId expiresAt status =
|
||||
placePaid :: DBStore -> Text -> Address -> OrderFields -> UTCTime -> IO (Either RegistrationRefused ())
|
||||
placePaid st rid owner o expiresAt = withTransaction st $ \db -> do
|
||||
insertInvoiceRow db ("inv-" <> rid) expiresAt "open"
|
||||
createPaidRegistration db (newReg rid owner o) (paidOrder $ "inv-" <> rid) t0
|
||||
createPaidRegistration db (newReg rid owner o) (OTInvoice btc price) (paidOrder $ "inv-" <> rid) t0
|
||||
|
||||
issue :: DBStore -> Word8 -> NewPrepaidCode -> IO PrepaidCode
|
||||
issue st n c = withTransaction st $ \db -> do
|
||||
@@ -154,7 +156,11 @@ 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"]
|
||||
namesTables = map ("sx_badge_service_name_" <>) ["prepaid_codes", "registrations", "invoices", "record_edits", "transactions", "balances", "late_credits"]
|
||||
|
||||
-- | Added to the badge tables' payments by the names migrations.
|
||||
balancePaymentColumns :: [Text]
|
||||
balancePaymentColumns = ["confirmed_amount", "received_units", "confirmed_units", "invoice_rate"]
|
||||
|
||||
badgeTables :: [Text]
|
||||
badgeTables = map ("sx_badge_service_" <>) ["invoices", "payments", "badge_prices", "badge_offers", "badge_purchases", "badge_ledger", "badge_issuances", "badge_codes", "badge_code_invoices", "group"]
|
||||
@@ -168,9 +174,12 @@ testNamesColumns = withServiceStore $ \st -> do
|
||||
[ "registration_id", "label_hash", "length", "label", "secret", "contact_link", "channel_link", "intent_nonce", "intent_deadline", "intent_signature",
|
||||
"sealed", "owner", "commitment", "phase", "commit_tx", "commit_block", "register_tx", "register_block", "reveal_after", "reveal_before",
|
||||
"years", "duration", "expires_at", "price", "name_prepaid_code_id", "registered_at", "failed_at", "error", "created_at",
|
||||
"updated_at", "version", "live", "order_hash", "method", "moves", "links_refused_at"
|
||||
"updated_at", "version", "live", "order_hash", "method", "moves", "links_refused_at", "balance_source", "balance_used"
|
||||
]
|
||||
has "sx_badge_service_name_invoices" ["invoice_id", "registration_id", "provider_ref"]
|
||||
has "sx_badge_service_name_invoices" ["invoice_id", "registration_id", "provider_ref", "late_alerted_at", "late_alerted_units", "late_support"]
|
||||
has "sx_badge_service_name_balances" ["registration_id", "amount", "credited", "refunded", "reserved_by", "refunded_at", "created_at", "updated_at"]
|
||||
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_transactions" ["registration_id", "name_record_edit_id", "kind", "raw", "tx_hash", "registrar_nonce", "sent_at", "mined_block", "status"]
|
||||
|
||||
@@ -178,7 +187,7 @@ 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"]
|
||||
map name names `shouldBe` ["20261013_names", "20261022_drop_taken_codes", "20261022_name_balances", "20261022_name_late_wait"]
|
||||
badgeBefore <- badgeColumns
|
||||
code <- issue st 1 usable
|
||||
placeCode st "r1" ownerA (order "alicebakery" 1) code `shouldReturn` Right ()
|
||||
@@ -188,7 +197,7 @@ testNamesDownUp = withServiceStore $ \st -> do
|
||||
runMigrations st $ MTRDown (mapMaybe toDownMigration names)
|
||||
mapM (columnsOf st) namesTables `shouldReturn` map (const []) namesTables
|
||||
mapM (invoiceCount st) ["inv-r2", "inv-r3"] `shouldReturn` [0, 1]
|
||||
badgeColumns `shouldReturn` badgeBefore
|
||||
badgeColumns `shouldReturn` map (filter (`notElem` balancePaymentColumns)) badgeBefore
|
||||
runMigrations st $ MTRUp names
|
||||
mapM (fmap null . columnsOf st) namesTables `shouldReturn` map (const False) namesTables
|
||||
badgeColumns `shouldReturn` badgeBefore
|
||||
@@ -218,6 +227,53 @@ testDropTakenCodes = withServiceStore $ \st -> do
|
||||
worth <$> reg st "r1" `shouldReturn` (PTaken, 0, False, 2)
|
||||
withTransaction st (\db -> DB.execute db "UPDATE sx_badge_service_name_registrations SET issued_code_id = ? WHERE registration_id = 'r1'" (Only $ pcId code + 1)) `shouldThrow` foreignKeyViolation
|
||||
|
||||
testNameBalancesMigration :: IO ()
|
||||
testNameBalancesMigration = withServiceStore $ \st -> do
|
||||
let balances = [m | m@Migration {name = "20261022_name_balances"} <- storeServiceSchemaMigrations]
|
||||
applied :: IO (Bool, Bool, Bool)
|
||||
applied = (,,) <$> (not . null <$> columnsOf st "sx_badge_service_name_balances") <*> (elem "balance_source" <$> columnsOf st "sx_badge_service_name_registrations") <*> (elem "confirmed_units" <$> columnsOf st "sx_badge_service_payments")
|
||||
live :: Text -> IO Bool
|
||||
live rid = withTransaction st $ \db -> DB.query db "SELECT live FROM sx_badge_service_name_registrations WHERE registration_id = ?" (Only rid) >>= \case
|
||||
[Only (DB.BI l)] -> pure l
|
||||
rows -> fail $ "registration " <> show rid <> ": " <> show (length rows) <> " rows"
|
||||
balanceOf :: Text -> IO (Maybe (Int, Int, Int, Maybe BalanceHold))
|
||||
balanceOf rid = withTransaction st $ \db -> fmap (\Balance {blAmount, blCredited, blRefunded, blHold} -> (blAmount, blCredited, blRefunded, blHold)) <$> getBalance db (RegistrationId rid) t0
|
||||
length balances `shouldBe` 1
|
||||
runMigrations st $ MTRDown (mapMaybe toDownMigration balances)
|
||||
applied `shouldReturn` (False, False, False)
|
||||
code <- issue st 1 usable
|
||||
withTransaction st $ \db -> do
|
||||
insertInvoiceRow db "inv-paid" (at 60) "paid"
|
||||
insertOldRegistration db "paid" 1 "taken" price Nothing (Just "inv-paid")
|
||||
insertOldRegistration db "code" 2 "taken" 0 (Just $ pcId code) Nothing
|
||||
insertInvoiceRow db "inv-converted" (at 60) "paid"
|
||||
insertOldRegistration db "converted" 3 "taken" 0 Nothing (Just "inv-converted")
|
||||
insertInvoiceRow db "inv-queued" (at 60) "paid"
|
||||
insertOldRegistration db "queued" 4 "queued" price Nothing (Just "inv-queued")
|
||||
runMigrations st $ MTRUp balances
|
||||
applied `shouldReturn` (True, True, True)
|
||||
mapM live ["paid", "code", "converted", "queued"] `shouldReturn` [False, False, False, True]
|
||||
mapM balanceOf ["paid", "code", "converted", "queued"] `shouldReturn` [Just (price, price, 0, Nothing), Nothing, Nothing, Nothing]
|
||||
runMigrations st $ MTRDown (mapMaybe toDownMigration balances)
|
||||
applied `shouldReturn` (False, False, False)
|
||||
mapM live ["paid", "queued"] `shouldReturn` [False, True]
|
||||
runMigrations st $ MTRUp balances
|
||||
balanceOf "paid" `shouldReturn` Just (price, price, 0, Nothing)
|
||||
|
||||
-- | 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
|
||||
let OrderFields {ofLabelHash = LabelHash lh, ofLength, ofDuration, ofCommitment, ofSealed} = order ("alicebakery" <> rid) n
|
||||
DB.execute
|
||||
db
|
||||
( "INSERT INTO sx_badge_service_name_registrations (registration_id, version, label_hash, length, duration, owner, commitment, sealed, phase, years,"
|
||||
<> " price, method, name_prepaid_code_id, live, order_hash, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?,?,?, ?,?,?,?,?,?,?)"
|
||||
)
|
||||
( (rid, 1 :: Int, DB.Binary lh, ofLength, fromIntegral ofDuration :: Int64, DB.Binary $ unAddress ownerA, DB.Binary ofCommitment, ofSealed, phase, twoYears)
|
||||
:. (cents, ("btc" :: Text) <$ invId, codeId, DB.BI True, DB.Binary $ digestFixture n, t0, t0)
|
||||
)
|
||||
mapM_ (\i -> DB.execute db "INSERT INTO sx_badge_service_name_invoices (invoice_id, registration_id, provider_ref, created_at) VALUES (?,?,?,?)" (i, rid, "ref-" <> i, t0)) invId
|
||||
|
||||
testOrderHashFields :: IO ()
|
||||
testOrderHashFields = do
|
||||
let o = order "alicebakery" 1
|
||||
@@ -263,6 +319,8 @@ testCreatePaid = withServiceStore $ \st -> do
|
||||
nrYears = twoYears,
|
||||
nrPrice = price,
|
||||
nrPayment = RPInvoice btc (InvoiceId "inv-r1"),
|
||||
nrBalanceSource = Nothing,
|
||||
nrBalanceUsed = 0,
|
||||
nrReveal = Nothing,
|
||||
nrCommitTx = Nothing,
|
||||
nrCommitBlock = Nothing,
|
||||
@@ -352,7 +410,7 @@ testCloseOverdue = withServiceStore $ \st -> do
|
||||
[LiveOrder {loRegistration, loOverdue = True}] <- getLiveOrders db (ofCommitment o') ownerA (ofLabelHash o') (at 61)
|
||||
void $ closeOverdue db loRegistration (at 61)
|
||||
insertInvoiceRow db "inv-r2" (at 120) "open"
|
||||
createPaidRegistration db (newReg "r2" ownerA o') (paidOrder "inv-r2") (at 61)
|
||||
createPaidRegistration db (newReg "r2" ownerA o') (OTInvoice btc price) (paidOrder "inv-r2") (at 61)
|
||||
placed `shouldBe` Right ()
|
||||
old <- reg st "r1"
|
||||
(nrLive old, nrPhase old, nrVersion old) `shouldBe` (False, PUnpaid, 2)
|
||||
@@ -494,11 +552,11 @@ testFind = withServiceStore $ \st -> do
|
||||
let rid = "r" <> T.pack (show i)
|
||||
o = order ("alicebakery" <> T.pack (show i)) (fromIntegral i)
|
||||
insertInvoiceRow db ("inv-" <> rid) (at 60) "open"
|
||||
createPaidRegistration db (newReg rid ownerA o) (paidOrder $ "inv-" <> rid) (at i) `shouldReturn` Right ()
|
||||
createPaidRegistration db (newReg rid ownerA o) (OTInvoice btc price) (paidOrder $ "inv-" <> rid) (at i) `shouldReturn` Right ()
|
||||
placePaid st "other" ownerB (order "bobsbakery" 99) (at 60) `shouldReturn` Right ()
|
||||
found <- withTransaction st $ \db -> findRegistrations db ownerA
|
||||
map nrId found `shouldBe` [RegistrationId $ "r" <> T.pack (show i) | i <- [52, 51 .. 3 :: Int]]
|
||||
withTransaction st (\db -> findRegistrations db (address "0x0000000000000000000000000000000000000001")) `shouldReturn` []
|
||||
found <- withTransaction st $ \db -> findRegistrations db ownerA t0
|
||||
map (nrId . fst) found `shouldBe` [RegistrationId $ "r" <> T.pack (show i) | i <- [52, 51 .. 3 :: Int]]
|
||||
withTransaction st (\db -> findRegistrations db (address "0x0000000000000000000000000000000000000001") t0) `shouldReturn` []
|
||||
|
||||
testSameSecondOrder :: IO ()
|
||||
testSameSecondOrder = withServiceStore $ \st -> do
|
||||
@@ -508,7 +566,7 @@ testSameSecondOrder = withServiceStore $ \st -> do
|
||||
placePaid st rid ownerA (order ("alicebakery" <> rid) n) (at 60) `shouldReturn` Right ()
|
||||
r <- reg st rid
|
||||
write st r {nrPhase = PQueued} `shouldReturn` Written 2
|
||||
map nrId <$> withTransaction st (`findRegistrations` ownerA) `shouldReturn` map RegistrationId ["r3", "r2", "r1"]
|
||||
map (nrId . fst) <$> withTransaction st (\db -> findRegistrations db ownerA t0) `shouldReturn` map RegistrationId ["r3", "r2", "r1"]
|
||||
map nrId <$> withTransaction st activeRegistrations `shouldReturn` map RegistrationId ["r1", "r2", "r3"]
|
||||
forM_ ["r5", "r4"] $ \rid -> do
|
||||
placePaid st rid ownerB o (at 60) `shouldReturn` Right ()
|
||||
@@ -553,7 +611,7 @@ testUnpaidCleanup = withServiceStore $ \st -> do
|
||||
void $ write st r {nrPhase = PQueued}
|
||||
candidates <- withTransaction st $ \db -> unpaidCleanupCandidates db (at 61)
|
||||
map (\(RegistrationId rid, InvoiceId invId) -> (rid, invId)) candidates `shouldBe` [("old", "inv-old")]
|
||||
withTransaction st (\db -> mapM (deleteUnpaidRegistration db . RegistrationId) ["old", "funded", "queued"]) `shouldReturn` [True, False, False]
|
||||
withTransaction st (\db -> mapM (deleteUnpaidRegistration db . RegistrationId) ["old", "funded", "queued"]) `shouldReturn` [Right (), Left CKPaid, Left CKPaid]
|
||||
withTransaction st (\db -> getRegistration db (RegistrationId "old")) `shouldReturn` Nothing
|
||||
invoiceCount st "inv-old" `shouldReturn` 0
|
||||
invoiceCount st "inv-funded" `shouldReturn` 1
|
||||
|
||||
@@ -10,11 +10,14 @@ import Bots.StoreService.NamesContractsTests (availableCall, maxCommitmentAgeCal
|
||||
import Bots.StoreService.NamesOrdersTests
|
||||
import Bots.StoreService.NamesOwnerTests (answerExpiry, answerFree, answerOwner, answerUnowned, byB, codeIn, committedPhase, dynamisOrder, failedPhase, labelBytes, ownerOfSelector, paidIn, rewrite, sentRegister, stored)
|
||||
import Bots.StoreService.NamesPhasesTests (held, prompt, registrationPath, woken)
|
||||
import Bots.StoreService.NamesStoreTests (reveal)
|
||||
import Bots.StoreService.NamesStoreTests (btc, insertInvoiceRow, ownerA, paidOrder, reveal)
|
||||
import Bots.StoreService.WebTests (capturingStderr, jsonObject, statusOf, stubCalls, webGet, webRequestBody)
|
||||
import Control.Applicative ((<|>))
|
||||
import Control.Arrow ((&&&))
|
||||
import Control.Concurrent (threadDelay)
|
||||
import qualified Control.Concurrent.Async as Async
|
||||
import Control.Concurrent.Async (wait, withAsync)
|
||||
import qualified Control.Exception as E
|
||||
import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar)
|
||||
import Control.Concurrent.STM (atomically, check)
|
||||
import Control.Monad (forM_, replicateM, replicateM_, void)
|
||||
@@ -30,6 +33,7 @@ import Data.Time.Clock.POSIX (posixSecondsToUTCTime, utcTimeToPOSIXSeconds)
|
||||
import Data.Word (Word64)
|
||||
import Network.HTTP.Client (defaultManagerSettings, newManager, responseBody)
|
||||
import qualified Network.Wai.Handler.Warp as Warp
|
||||
import Simplex.Chat.PaymentService.Types (InvoiceId (..), InvoiceStatus (..))
|
||||
import Simplex.Messaging.Agent.Store.Common (withTransaction)
|
||||
import qualified Simplex.Messaging.Agent.Store.DB as DB
|
||||
import Simplex.Messaging.Crypto (keccak256)
|
||||
@@ -44,6 +48,7 @@ import StoreService.Names.Phases (RegistrationId (..), awaitChange)
|
||||
import StoreService.Names.Registration (RegisterIntent (..), commitCalldata, registerIntentDigest, registerWithCreditCalldata, sponsorDomain)
|
||||
import StoreService.Names.Reveal (intentOf)
|
||||
import StoreService.Names.Sender
|
||||
import StoreService.Names.Signatures (OrderFields (..))
|
||||
import StoreService.Names.Store
|
||||
import StoreService.Names.Turns (labelTurnCount, withLabelTurn)
|
||||
import StoreService.Names.Worker
|
||||
@@ -55,7 +60,16 @@ import System.Timeout (timeout)
|
||||
import Test.Hspec
|
||||
|
||||
namesWorkerTests :: Spec
|
||||
namesWorkerTests = describe "StoreService names: worker" $ do
|
||||
namesWorkerTests = workerTests >> takenBalanceTests
|
||||
|
||||
takenBalanceTests :: Spec
|
||||
takenBalanceTests = describe "StoreService names: balance life" $ describe "taken" $ do
|
||||
it "credits a taken order paid wholly from a balance, and one paid partly, its whole price as a balance of its own, the source's left as it was" testTakenFromBalance
|
||||
it "leaves the order as it was when the taken write's credit is refused, in one transaction" testTakenCreditRefused
|
||||
it "wakes a held poll with the taken write, and not with a change of the order's balance" testTakenWakesPoll
|
||||
|
||||
workerTests :: Spec
|
||||
workerTests = describe "StoreService names: worker" $ do
|
||||
describe "commit" $ do
|
||||
it "commits, waits for the reveal and revealAfter, and registers a code order, spending its code and publishing each change" testCommitWaitRegister
|
||||
it "registers a code order with codes_only on, from the code check to the registered view, refusing a paid order" testCodesOnlyRegister
|
||||
@@ -70,8 +84,8 @@ namesWorkerTests = describe "StoreService names: worker" $ do
|
||||
it "writes nothing when the registration changed since it was read" testLostRace
|
||||
it "writes in the name's turn" testInNameTurn
|
||||
describe "register" $ do
|
||||
it "ends the later of two wallets' paid orders for one name taken, not live, with its value kept" testTwoWallets
|
||||
it "ends taken on any revert while the name is not available, releasing a code" testRevertTaken
|
||||
it "ends the later of two wallets' paid orders for one name taken, not live, with a balance of its price" testTwoWallets
|
||||
it "ends taken on any revert while the name is not available, releasing a code and keeping no balance" testRevertTaken
|
||||
it "keeps the phase on NameNotAvailable while the name still reads available, as for a pending competitor" testPendingCompetitor
|
||||
it "ends failed on a revert while the name is available, alerting on InsufficientAllowance and keeping a code" testRevertFailed
|
||||
it "clears the reveal on InvalidNonce, staying committed" testInvalidNonce
|
||||
@@ -507,8 +521,77 @@ testTwoWallets = withWorker $ \w@W {wCtx = ctx} -> do
|
||||
published w b (steps w b) >>= done
|
||||
x <- stored ctx b
|
||||
(nrPhase x, nrLive x, nrPrice x, nrPayment x, nrError x) `shouldBe` (PTaken, False, nrPrice b, nrPayment b, Nothing)
|
||||
fmap (\Balance {blAmount, blCredited, blHold} -> (blAmount, blCredited, blHold)) <$> withTransaction (cStore ctx) (\db -> getBalance db (nrId b) orderTime)
|
||||
`shouldReturn` Just (nrPrice b, nrPrice b, Nothing)
|
||||
length <$> sent w `shouldReturn` 1
|
||||
|
||||
-- | The order of alicebakery, by owner A, with this commitment.
|
||||
aliceFields :: Int -> OrderFields
|
||||
aliceFields n = OrderFields {ofLabelHash = labelHash "alicebakery", ofLength = 11, ofDuration = yearsDuration 2 orderTime, ofCommitment = commitmentOf n, ofSealed = "sealed-alicebakery-" <> tshow n}
|
||||
|
||||
aliceRegistration :: Text -> Int -> NewRegistration
|
||||
aliceRegistration rid n = NewRegistration {nrgId = RegistrationId rid, nrgOwner = ownerA, nrgOrder = aliceFields n, nrgYears = 2}
|
||||
|
||||
-- | The amount and credited of the order's balance.
|
||||
balanceFigures :: Ctx -> RegistrationId -> IO (Maybe (Int, Int))
|
||||
balanceFigures Ctx {cStore} rid = fmap (\Balance {blAmount, blCredited} -> (blAmount, blCredited)) <$> withTransaction cStore (\db -> getBalance db rid orderTime)
|
||||
|
||||
-- | The register's dry run reverts on a name someone else holds, so the registration ends taken.
|
||||
endsTaken :: W -> NameRegistration -> IO ()
|
||||
endsTaken w@W {wCtx = Ctx {cNode}} r = do
|
||||
answerAvailable w False
|
||||
setFault cNode "eth_estimateGas" $ RpcError 3 "execution reverted: ERC721: invalid token ID" Nothing
|
||||
published w r (steps w r) >>= done
|
||||
|
||||
testTakenFromBalance :: IO ()
|
||||
testTakenFromBalance = withWorker $ \w@W {wCtx = ctx@Ctx {cStore}} -> do
|
||||
let price = oPrice aliceOrder
|
||||
wholly <- paidIn ctx (byB dynamisOrder) failedPhase
|
||||
partly <- paidIn ctx (byB aliceOrder) {oCommitment = commitmentOf 5} failedPhase
|
||||
withTransaction cStore $ \db -> creditBalance db (nrId wholly) 30000 orderTime >> creditBalance db (nrId partly) 4000 orderTime
|
||||
withTransaction cStore (\db -> createBalanceRegistration db (aliceRegistration "covered" 1) (nrId wholly) price 30000 orderTime) `shouldReturn` Right ()
|
||||
covered <- registrationById ctx (RegistrationId "covered") >>= \r -> rewrite ctx r openPhase >>= revealed ctx keyA "alicebakery"
|
||||
endsTaken w covered
|
||||
(\x -> (nrPhase x, nrLive x, nrPayment x)) <$> stored ctx covered `shouldReturn` (PTaken, False, RPBalance)
|
||||
balanceFigures ctx (nrId covered) `shouldReturn` Just (price, price)
|
||||
balanceFigures ctx (nrId wholly) `shouldReturn` Just (30000 - price, 30000)
|
||||
withTransaction cStore $ \db -> do
|
||||
insertInvoiceRow db "inv-diff" (addUTCTime 3600 orderTime) "open"
|
||||
createPaidRegistration db (aliceRegistration "diff" 2) (OTBalance (nrId partly) price 4000 (Just btc)) (paidOrder "inv-diff") {poPrice = price} orderTime `shouldReturn` Right ()
|
||||
settleNow ctx (InvoiceId "inv-diff") settled `shouldReturn` Right ISPaid
|
||||
balanceFigures ctx (nrId partly) `shouldReturn` Just (0, 4000)
|
||||
diff <- registrationById ctx (RegistrationId "diff") >>= \r -> rewrite ctx r openPhase >>= revealed ctx keyA "alicebakery"
|
||||
endsTaken w diff
|
||||
nrPhase <$> stored ctx diff `shouldReturn` PTaken
|
||||
balanceFigures ctx (nrId diff) `shouldReturn` Just (price, price)
|
||||
balanceFigures ctx (nrId partly) `shouldReturn` Just (0, 4000)
|
||||
|
||||
-- | A price the balance's CHECK refuses makes the credit fail inside the taken write's transaction.
|
||||
testTakenCreditRefused :: IO ()
|
||||
testTakenCreditRefused = withWorker $ \w@W {wCtx = ctx@Ctx {cStore, cNode}} -> do
|
||||
r <- paidIn ctx aliceOrder openPhase >>= revealed ctx keyA "alicebakery"
|
||||
withTransaction cStore $ \db -> DB.execute db "UPDATE sx_badge_service_name_registrations SET price = -1 WHERE registration_id = ?" [(\(RegistrationId t) -> t) $ nrId r]
|
||||
unchanged <- stored ctx r
|
||||
answerAvailable w False
|
||||
setFault cNode "eth_estimateGas" $ RpcError 3 "execution reverted: ERC721: invalid token ID" Nothing
|
||||
void (E.try (steps w r) :: IO (Either E.SomeException Next))
|
||||
stored ctx r `shouldReturn` unchanged
|
||||
balanceFigures ctx (nrId r) `shouldReturn` Nothing
|
||||
|
||||
testTakenWakesPoll :: IO ()
|
||||
testTakenWakesPoll = withWorker $ \w@W {wCtx = ctx@Ctx {cStore}} -> do
|
||||
r <- paidIn ctx aliceOrder openPhase >>= revealed ctx keyA "alicebakery"
|
||||
waiting <- held ctx (0, 1) $ registrationPath (nrId r) <> "?seenVersion=" <> show (nrVersion r)
|
||||
withTransaction cStore $ \db -> creditBalance db (nrId r) 500 orderTime
|
||||
threadDelay shortWait
|
||||
isJust <$> Async.poll waiting `shouldReturn` False
|
||||
endsTaken w r
|
||||
(status, view) <- woken "the registration poll" waiting
|
||||
(status, field "phase" view) `shouldBe` (200, Just "taken")
|
||||
balanceFigures ctx (nrId r) `shouldReturn` Just (500 + oPrice aliceOrder, 500 + oPrice aliceOrder)
|
||||
where
|
||||
shortWait = 500000
|
||||
|
||||
testPendingCompetitor :: IO ()
|
||||
testPendingCompetitor = withWorker $ \w@W {wCtx = ctx} -> do
|
||||
(r, code) <- codeIn ctx 8 aliceOrder openPhase >>= traverseFst (revealed ctx keyA "alicebakery")
|
||||
@@ -534,6 +617,7 @@ testRevertTaken = withWorker $ \w@W {wCtx = ctx@Ctx {cNode}} -> do
|
||||
(nrPhase x, nrLive x) `shouldBe` (PTaken, False)
|
||||
PrepaidCode {pcReservedBy, pcSpentAt} <- codeOf ctx code
|
||||
(pcReservedBy, pcSpentAt) `shouldBe` (Nothing, Nothing)
|
||||
balanceFigures ctx (nrId r) `shouldReturn` Nothing
|
||||
sent w `shouldReturn` []
|
||||
|
||||
testRevertFailed :: IO ()
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
module Bots.StoreService.WebTests
|
||||
( badgeWebTests,
|
||||
withServiceStore,
|
||||
withServiceStores,
|
||||
columnsOf,
|
||||
runMigrations,
|
||||
digestFixture,
|
||||
@@ -77,7 +78,7 @@ import qualified Data.ByteString.Lazy.Char8 as LB
|
||||
import Data.Char (toLower)
|
||||
import Data.Either (isLeft)
|
||||
import Data.Functor ((<&>))
|
||||
import Data.IORef (IORef, atomicModifyIORef', newIORef, readIORef)
|
||||
import Data.IORef (IORef, atomicModifyIORef', modifyIORef', newIORef, readIORef)
|
||||
import Data.Int (Int64)
|
||||
import Data.List (isInfixOf, sort, sortOn)
|
||||
import qualified Data.Map.Strict as Map
|
||||
@@ -134,32 +135,37 @@ import Simplex.Messaging.Agent.Store.DB (TrackQueries (..))
|
||||
import qualified Simplex.Messaging.Agent.Store.SQLite.Migrations as Migrations
|
||||
#endif
|
||||
|
||||
#if defined(dbPostgres)
|
||||
withServiceStore :: (DBStore -> IO a) -> IO a
|
||||
withServiceStore action = do
|
||||
withServiceStore action = withServiceStores (>>= action)
|
||||
|
||||
-- | Each store the action opens is a new one over the same test database, as a restarted service opens; all are closed at the end.
|
||||
withServiceStores :: (IO DBStore -> IO a) -> IO a
|
||||
withServiceStores action = withServiceDBOpts $ \opts -> do
|
||||
opened <- newIORef []
|
||||
let open = do
|
||||
Right st <- createDBStore opts storeServiceSchemaMigrations (MigrationConfig MCError Nothing)
|
||||
st <$ modifyIORef' opened (st :)
|
||||
action open `E.finally` (readIORef opened >>= mapM_ closeDBStore)
|
||||
|
||||
withServiceDBOpts :: (DBOpts -> IO a) -> IO a
|
||||
#if defined(dbPostgres)
|
||||
withServiceDBOpts action = do
|
||||
n <- atomicModifyIORef' serviceSchemaCounter (\i -> (i + 1, i))
|
||||
Right st <- createDBStore (serviceDBOpts n) storeServiceSchemaMigrations (MigrationConfig MCError Nothing)
|
||||
action st `E.finally` closeDBStore st
|
||||
where
|
||||
serviceDBOpts :: Int -> DBOpts
|
||||
serviceDBOpts n =
|
||||
DBOpts
|
||||
{ connstr = BC.pack testDBConnstr,
|
||||
schema = "sx_badge_service_web_test_" <> BC.pack (show n),
|
||||
poolSize = 4,
|
||||
createSchema = True
|
||||
}
|
||||
action
|
||||
DBOpts
|
||||
{ connstr = BC.pack testDBConnstr,
|
||||
schema = "sx_badge_service_web_test_" <> BC.pack (show n),
|
||||
poolSize = 4,
|
||||
createSchema = True
|
||||
}
|
||||
|
||||
serviceSchemaCounter :: IORef Int
|
||||
serviceSchemaCounter = unsafePerformIO $ newIORef 0
|
||||
{-# NOINLINE serviceSchemaCounter #-}
|
||||
#else
|
||||
withServiceStore :: (DBStore -> IO a) -> IO a
|
||||
withServiceStore action = do
|
||||
withServiceDBOpts action = do
|
||||
createDirectoryIfMissing True "tests/tmp"
|
||||
withTempDirectory "tests/tmp" "badge-web" $ \dir -> do
|
||||
Right st <- createDBStore (DBOpts (dir </> "badge_service_test.db") [] "" False True TQOff) storeServiceSchemaMigrations (MigrationConfig MCError Nothing)
|
||||
action st `E.finally` closeDBStore st
|
||||
withTempDirectory "tests/tmp" "badge-web" $ \dir -> action (DBOpts (dir </> "badge_service_test.db") [] "" False True TQOff)
|
||||
#endif
|
||||
|
||||
columnsOf :: DBStore -> Text -> IO [Text]
|
||||
@@ -417,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"]
|
||||
ours `shouldBe` ["20261013_names", "20261022_drop_taken_codes", "20261022_name_balances", "20261022_name_late_wait"]
|
||||
where
|
||||
badgeMigrations = ["20260915_badge_service_schema", "20260918_badge_group_ops", "20260925_badge_store_receipts", "20261012_badge_subscriptions"]
|
||||
|
||||
@@ -1039,6 +1045,7 @@ data StubCall
|
||||
| StubRead Text
|
||||
| StubCancel Text
|
||||
| StubListOpen
|
||||
| StubRate CryptoCurrency
|
||||
deriving (Eq, Show)
|
||||
|
||||
data StubState = StubState
|
||||
@@ -1054,7 +1061,8 @@ data StubState = StubState
|
||||
ssVerifyResult :: Either WebhookError (Maybe Text),
|
||||
ssVerifyThrows :: Bool,
|
||||
ssWebhooks :: [([Header], ByteString)],
|
||||
ssReadDelay :: Int
|
||||
ssReadDelay :: Int,
|
||||
ssRate :: Either ProviderError Rate
|
||||
}
|
||||
|
||||
newStubState :: Either ProviderError ProviderInvoice -> StubState
|
||||
@@ -1071,9 +1079,14 @@ newStubState ssCreateResult =
|
||||
ssVerifyResult = Right Nothing,
|
||||
ssVerifyThrows = False,
|
||||
ssWebhooks = [],
|
||||
ssReadDelay = 0
|
||||
ssReadDelay = 0,
|
||||
ssRate = Right stubRate
|
||||
}
|
||||
|
||||
-- | Below the stored invoices' rate of 62500.
|
||||
stubRate :: Rate
|
||||
stubRate = Rate {rateText = "60000.5", rateValue = 60000.5}
|
||||
|
||||
record :: IORef StubState -> StubCall -> IO ()
|
||||
record ref call = atomicModifyIORef' ref $ \s -> (s {ssCalls = ssCalls s ++ [call]}, ())
|
||||
|
||||
@@ -1103,6 +1116,9 @@ stubProvider ref =
|
||||
pure $ case ssListError stub of
|
||||
Just e -> Left e
|
||||
Nothing -> Right ListPass {lpMoved = Map.toList (ssInvoices stub), lpSkipped = ssSkipped stub},
|
||||
pCurrentRate = Just $ \cc -> do
|
||||
record ref (StubRate cc)
|
||||
ssRate <$> readIORef ref,
|
||||
pVerifyWebhook = const (verifyRecording ref)
|
||||
}
|
||||
|
||||
@@ -2416,8 +2432,18 @@ replayAt = addUTCTime 3600 settleAt
|
||||
detectedAt :: UTCTime
|
||||
detectedAt = addUTCTime 300 settleAt
|
||||
|
||||
-- | Nothing confirmed and no units, as the badge paths read it.
|
||||
rcv :: Word32 -> Maybe Text -> Received
|
||||
rcv amount crypto = Received {rcvAmount = CurrencyAmount amount, rcvCrypto = crypto, rcvDue = Nothing}
|
||||
rcv amount crypto =
|
||||
Received
|
||||
{ rcvAmount = CurrencyAmount amount,
|
||||
rcvCrypto = crypto,
|
||||
rcvDue = Nothing,
|
||||
rcvUnits = Nothing,
|
||||
rcvRate = Nothing,
|
||||
rcvConfirmed = Confirmed {cfCents = CurrencyAmount 0, cfUnits = Nothing},
|
||||
rcvUncreditable = Nothing
|
||||
}
|
||||
|
||||
settle :: DBStore -> InvoiceId -> PaymentSignal -> UTCTime -> IO (Either Text InvoiceStatus)
|
||||
settle st iid signal at = newWaiters >>= \waiters -> settleOrder st waiters Nothing iid signal at
|
||||
@@ -2727,8 +2753,8 @@ testSettledPaymentIsNotDowngraded :: IO ()
|
||||
testSettledPaymentIsNotDowngraded = bounded "settled is not downgraded" $ withServiceStore $ \st -> do
|
||||
iid <- seedOpen st
|
||||
row <- getInvoice st iid >>= maybe (failWith "no invoice row") pure
|
||||
withTransaction st $ \db -> upsertPayment db row PSSettled (CurrencyAmount 500) (Just "0.00050000") Nothing False settleAt
|
||||
withTransaction st $ \db -> upsertPayment db row PSPending (CurrencyAmount 200) (Just "0.00020000") Nothing False replayAt
|
||||
withTransaction st $ \db -> upsertPayment db row PSSettled (rcv 500 (Just "0.00050000")) False settleAt
|
||||
withTransaction st $ \db -> upsertPayment db row PSPending (rcv 200 (Just "0.00020000")) False replayAt
|
||||
p <- paymentRow st iid
|
||||
ipStatus p `shouldBe` "settled"
|
||||
ipUpdatedAt p `shouldBe` settleAt
|
||||
@@ -2737,8 +2763,8 @@ testSettledPaymentIsNotDowngraded = bounded "settled is not downgraded" $ withSe
|
||||
let second' = sampleInvoice {niInvoiceId = InvoiceId "inv-pending", niProviderRef = "p-pending", niCodeHash = digestFixture 16}
|
||||
createInvoiceRows st second' `shouldReturn` Right ()
|
||||
row' <- getInvoice st (niInvoiceId second') >>= maybe (failWith "no invoice row") pure
|
||||
withTransaction st $ \db -> upsertPayment db row' PSPending (CurrencyAmount 100) Nothing Nothing False settleAt
|
||||
withTransaction st $ \db -> upsertPayment db row' PSSettled (CurrencyAmount 500) (Just "0.00050000") Nothing False replayAt
|
||||
withTransaction st $ \db -> upsertPayment db row' PSPending (rcv 100 Nothing) False settleAt
|
||||
withTransaction st $ \db -> upsertPayment db row' PSSettled (rcv 500 (Just "0.00050000")) False replayAt
|
||||
p' <- paymentRow st (niInvoiceId second')
|
||||
ipStatus p' `shouldBe` "settled"
|
||||
ipUpdatedAt p' `shouldBe` replayAt
|
||||
|
||||
Reference in new issue
Block a user