store: add the names chain client and reads

This commit is contained in:
sh-agents committed 2026-11-01 15:27:03 +00:00
1 parent c31f1862e1
commit 9dcb6978fd
11 files changed
+1634 -146

No files matched your search

@@ -3,50 +3,127 @@
module StoreService.Names.Abi
( AbiValue (..),
AbiError (..),
abiTuple,
abiBytes,
abiArray,
uint256,
addressWord,
addressFromBytes,
selector,
hex,
decodeUint256,
decodeWord64,
decodeAddress,
decodeBool,
decodeString,
)
where
import Crypto.Number.Serialize (i2ospOf_)
import Control.Monad (unless)
import Crypto.Number.Serialize (i2ospOf_, os2ip)
import Data.Bifunctor (first)
import Data.ByteArray.Encoding (Base (Base16), convertToBase)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.List (mapAccumL)
import Data.Text (Text)
import Data.Text.Encoding (decodeLatin1)
import Data.Text.Encoding (decodeLatin1, decodeUtf8')
import Data.Word (Word64)
import Simplex.Messaging.Crypto (keccak256)
import Simplex.Messaging.Encoding.String (strDecode)
import Simplex.Messaging.Eth.Address (Address, unAddress)
data AbiValue = Static ByteString | Dynamic ByteString
data AbiError
= AEShort
| AEOffset
| AENotAddress
| AENotBool
| AENotUtf8
| AERange
deriving (Eq, Show)
abiWordSize :: Int
abiWordSize = 32
addressPadding :: Int
addressPadding = 12
abiTuple :: [AbiValue] -> ByteString
abiTuple values = B.concat heads <> B.concat [tl | Dynamic tl <- values]
where
heads = snd $ mapAccumL encodeHead (32 * length values) values
heads = snd $ mapAccumL encodeHead (abiWordSize * length values) values
encodeHead offset = \case
Static w -> (offset, w)
Dynamic tl -> (offset + B.length tl, uint256 offset)
abiBytes :: ByteString -> ByteString
abiBytes bs = uint256 (B.length bs) <> bs <> B.replicate (negate (B.length bs) `mod` 32) 0
abiBytes bs = uint256 (B.length bs) <> bs <> B.replicate (negate (B.length bs) `mod` abiWordSize) 0
abiArray :: [ByteString] -> ByteString
abiArray items = uint256 (length items) <> abiTuple (map Dynamic items)
uint256 :: Integral a => a -> ByteString
uint256 = i2ospOf_ 32 . toInteger
uint256 = i2ospOf_ abiWordSize . toInteger
addressWord :: Address -> ByteString
addressWord a = B.replicate 12 0 <> unAddress a
addressWord a = B.replicate addressPadding 0 <> unAddress a
selector :: ByteString -> ByteString
selector = B.take 4 . keccak256
hex :: ByteString -> Text
hex bs = "0x" <> decodeLatin1 (convertToBase Base16 bs)
decodeUint256 :: ByteString -> Either AbiError Integer
decodeUint256 = uintAt 0
decodeWord64 :: ByteString -> Either AbiError Word64
decodeWord64 ret = do
n <- decodeUint256 ret
if n <= toInteger (maxBound :: Word64) then Right (fromInteger n) else Left AERange
decodeAddress :: ByteString -> Either AbiError Address
decodeAddress ret = do
(padding, a) <- B.splitAt addressPadding <$> wordAt 0 ret
unless (B.all (== 0) padding) $ Left AENotAddress
maybe (Left AENotAddress) Right $ addressFromBytes a
-- | Address has no exported constructor; its parser takes lowercase hex without the EIP-55 check.
addressFromBytes :: ByteString -> Maybe Address
addressFromBytes = either (const Nothing) Just . strDecode . convertToBase Base16
decodeBool :: ByteString -> Either AbiError Bool
decodeBool ret =
uintAt 0 ret >>= \case
0 -> Right False
1 -> Right True
_ -> Left AENotBool
decodeBytes :: ByteString -> Either AbiError ByteString
decodeBytes ret = offsetAt 0 ret >>= bytesAt ret
decodeString :: ByteString -> Either AbiError Text
decodeString ret = decodeBytes ret >>= first (const AENotUtf8) . decodeUtf8'
wordAt :: Int -> ByteString -> Either AbiError ByteString
wordAt o ret
| o + abiWordSize <= B.length ret = Right $ B.take abiWordSize $ B.drop o ret
| otherwise = Left AEShort
uintAt :: Int -> ByteString -> Either AbiError Integer
uintAt o ret = os2ip <$> wordAt o ret
-- an offset or a length, never more than the data's size, so it fits an Int
offsetAt :: Int -> ByteString -> Either AbiError Int
offsetAt o ret = do
n <- uintAt o ret
if n <= toInteger (B.length ret) then Right (fromInteger n) else Left AEOffset
bytesAt :: ByteString -> Int -> Either AbiError ByteString
bytesAt ret o = do
n <- offsetAt o ret
let start = o + abiWordSize
if start + n <= B.length ret then Right $ B.take n $ B.drop start ret else Left AEShort
@@ -1,109 +1,329 @@
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
module StoreService.Names.Chain
( ChainClient (..),
ChainError (..),
TxHash (..),
sendCommit,
sendRegister,
SignedTx (..),
TxRequest (..),
Block (..),
Receipt (..),
TxState (..),
BlockTag (..),
newChainClient,
ethCall,
ethCallAt,
latestBlock,
transactionReceipt,
transactionByHash,
transactionCount,
estimateGas,
maxPriorityFee,
signTransaction,
decodeSignedTx,
sendRawTransaction,
httpFailureDetail,
)
where
import StoreService.Names.Registration (RegisterIntent, commitCalldata, registerWithCreditCalldata)
import Control.Concurrent.STM (TVar)
import Control.Exception (try)
import Control.Monad.Except (ExceptT, liftEither, runExceptT, throwError)
import Control.Monad.IO.Class (liftIO)
import Control.Exception (evaluate, try)
import Control.Monad ((<=<), (>=>))
import Crypto.Number.Serialize (os2ip)
import Crypto.Random (ChaChaDRG)
import Data.Aeson ((.:), (.:?), (.=))
import qualified Data.Aeson as J
import qualified Data.Aeson.Types as JT
import Data.ByteArray.Encoding (Base (Base16), convertFromBase, convertToBase)
import Data.ByteArray.Encoding (Base (Base16), convertFromBase)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as LB
import Data.List (foldl')
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Encoding (decodeLatin1, encodeUtf8)
import Data.Word (Word64)
import Data.Word (Word64, Word8)
import Network.HTTP.Client (Manager)
import qualified Network.HTTP.Client as HTTP
import Network.HTTP.Types (hContentType, methodPost)
import Numeric (readHex)
import Simplex.Messaging.Crypto.Secp256k1 (Secp256k1PrivateKey)
import Network.HTTP.Client.TLS (newTlsManager)
import Network.HTTP.Types (hContentType, methodPost, statusCode, statusIsSuccessful)
import Numeric (readHex, showHex)
import Simplex.Messaging.Crypto (keccak256)
import Simplex.Messaging.Eth.Address (Address, addressFromPrivateKey)
import Simplex.Messaging.Eth.RLP (RLPItem (..))
import Simplex.Messaging.Eth.Transaction (Eip1559Tx (..), signEip1559Tx)
import Simplex.Messaging.Util (liftError', tshow)
import Simplex.Messaging.Util (tshow)
import StoreService.Config (ChainConfig (..))
import StoreService.Log (logWarn)
import StoreService.Names.Abi (addressFromBytes, hex)
import StoreService.Names.Revert (RevertName (..), decodeRevert)
import System.Timeout (timeout)
data ChainClient = ChainClient
{ ccManager :: Manager,
ccRpcUrl :: String,
ccChainId :: Word64,
ccController :: Address,
ccSponsor :: Address,
ccRegistrarKey :: Secp256k1PrivateKey
ccConfig :: ChainConfig,
ccRegistrar :: Address,
-- | microseconds for a whole call, from the request to the end of its body
ccTimeout :: Int
}
newtype ChainError = ChainError Text
-- | 'ChainUnavailable' never holds the RPC URL, which can carry a provider's key.
data ChainError
= ChainReverted (Maybe RevertName)
| ChainUnavailable Text
| ChainGasAboveCap Word64
deriving (Eq, Show)
newtype TxHash = TxHash ByteString
deriving (Eq, Show)
sendCommit :: TVar ChaChaDRG -> ChainClient -> ByteString -> IO (Either ChainError TxHash)
sendCommit g c@ChainClient {ccController} = sendTransaction g c ccController . commitCalldata
data SignedTx = SignedTx {stRaw :: ByteString, stHash :: TxHash}
deriving (Eq, Show)
sendRegister :: TVar ChaChaDRG -> ChainClient -> RegisterIntent -> IO (Either ChainError TxHash)
sendRegister g c@ChainClient {ccSponsor} = sendTransaction g c ccSponsor . registerWithCreditCalldata
data TxRequest = TxRequest
{ trTo :: Address,
trData :: ByteString,
trNonce :: Word64,
trGasLimit :: Word64,
trMaxFeePerGas :: Word64,
trMaxPriorityFeePerGas :: Word64
}
deriving (Eq, Show)
sendTransaction :: TVar ChaChaDRG -> ChainClient -> Address -> ByteString -> IO (Either ChainError TxHash)
sendTransaction g c@ChainClient {ccChainId, ccRegistrarKey} to calldata = runExceptT $ do
from <- liftIO $ addressFromPrivateKey g ccRegistrarKey
gas <- rpc c "eth_estimateGas" [J.object ["from" .= from, "to" .= to, "data" .= hex calldata], "pending"] quantity
nonce <- rpc c "eth_getTransactionCount" [J.toJSON from, "pending"] quantity
tip <- rpc c "eth_maxPriorityFeePerGas" [] quantity
baseFee <- rpc c "eth_getBlockByNumber" ["latest", J.Bool False] $ J.withObject "block" $ \b -> quantity =<< b .: "baseFeePerGas"
let tx =
Eip1559Tx
{ txChainId = ccChainId,
txNonce = nonce,
txMaxPriorityFeePerGas = tip,
txMaxFeePerGas = 2 * baseFee + tip,
txGasLimit = gas,
txTo = to,
txValue = 0,
txData = calldata
}
raw <- liftError' (ChainError . T.pack) $ signEip1559Tx g ccRegistrarKey tx
TxHash <$> rpc c "eth_sendRawTransaction" [J.String $ hex raw] bytes
data Block = Block {blockNumber :: Word64, blockTimestamp :: Word64, blockBaseFee :: Word64}
deriving (Eq, Show)
rpc :: ChainClient -> Text -> [J.Value] -> (J.Value -> JT.Parser a) -> ExceptT ChainError IO a
rpc ChainClient {ccManager, ccRpcUrl} method params parseResult = do
resp <- liftError' (\(e :: HTTP.HttpException) -> ChainError $ tshow e) $ try $ do
req <- HTTP.parseRequest ccRpcUrl
HTTP.httpLbs
req
{ HTTP.method = methodPost,
HTTP.redirectCount = 0,
HTTP.requestHeaders = (hContentType, "application/json") : HTTP.requestHeaders req,
HTTP.requestBody = HTTP.RequestBodyLBS body
}
ccManager
either (throwError . ChainError . T.pack) liftEither $ JT.parseEither response =<< J.eitherDecode (HTTP.responseBody resp)
data Receipt = Receipt {receiptSuccess :: Bool, receiptBlock :: Word64}
deriving (Eq, Show)
data TxState = TxPending | TxMined Word64
deriving (Eq, Show)
data BlockTag = Latest | Pending | AtBlock Word64
rpcTimeout :: Int
rpcTimeout = 10000000
-- | Far above the largest answer the service reads: a block with its transaction hashes, or two records at the link bound.
maxRpcResponseBytes :: Int
maxRpcResponseBytes = 1024 * 1024
revertCode :: Int
revertCode = 3
revertMessage :: Text
revertMessage = "execution reverted"
-- | A node's error message is cut to this many characters.
maxNodeMessageLength :: Int
maxNodeMessageLength = 200
-- | The hex digits of a 256-bit quantity.
maxQuantityDigits :: Int
maxQuantityDigits = 64
newChainClient :: TVar ChaChaDRG -> ChainConfig -> IO ChainClient
newChainClient g ccConfig@ChainConfig {cServiceKey} = do
ccManager <- newTlsManager
ccRegistrar <- addressFromPrivateKey g cServiceKey
pure ChainClient {ccManager, ccConfig, ccRegistrar, ccTimeout = rpcTimeout}
ethCall :: ChainClient -> Address -> ByteString -> IO (Either ChainError ByteString)
ethCall c = ethCallAt c Latest
ethCallAt :: ChainClient -> BlockTag -> Address -> ByteString -> IO (Either ChainError ByteString)
ethCallAt c tag to calldata = rpc c "eth_call" [J.object ["to" .= to, "data" .= hex calldata], blockTagParam tag] bytes
latestBlock :: ChainClient -> IO (Either ChainError Block)
latestBlock c = blockByNumber c "latest"
blockByNumber :: ChainClient -> J.Value -> IO (Either ChainError Block)
blockByNumber c tag =
rpc c "eth_getBlockByNumber" [tag, J.Bool False] $ J.withObject "block" $ \b ->
Block <$> (quantity =<< b .: "number") <*> (quantity =<< b .: "timestamp") <*> (quantity =<< b .: "baseFeePerGas")
-- | Nothing while the transaction is not mined, or after the node pruned its receipt.
transactionReceipt :: ChainClient -> TxHash -> IO (Either ChainError (Maybe Receipt))
transactionReceipt c (TxHash h) =
rpc c "eth_getTransactionReceipt" [J.String $ hex h] $ nullable $ J.withObject "receipt" $ \r ->
Receipt <$> (status =<< r .: "status") <*> (quantity =<< r .: "blockNumber")
where
body = J.encode $ J.object ["jsonrpc" .= ("2.0" :: Text), "id" .= (1 :: Int), "method" .= method, "params" .= params]
response = J.withObject "JSON-RPC response" $ \o -> o .:? "error" >>= maybe (Right <$> (parseResult =<< o .: "result")) rpcError
rpcError = J.withObject "JSON-RPC error" $ \e -> Left . ChainError <$> e .: "message"
status =
quantity >=> \case
(1 :: Word64) -> pure True
0 -> pure False
_ -> fail "not a receipt status"
quantity :: (Eq a, Num a) => J.Value -> JT.Parser a
-- | Nothing when the node does not know the transaction.
transactionByHash :: ChainClient -> TxHash -> IO (Either ChainError (Maybe TxState))
transactionByHash c (TxHash h) =
rpc c "eth_getTransactionByHash" [J.String $ hex h] $ nullable $ J.withObject "transaction" $ \t ->
maybe TxPending TxMined <$> (traverse quantity =<< t .:? "blockNumber")
transactionCount :: ChainClient -> Address -> BlockTag -> IO (Either ChainError Word64)
transactionCount c a tag = rpc c "eth_getTransactionCount" [J.toJSON a, blockTagParam tag] quantity
blockTagParam :: BlockTag -> J.Value
blockTagParam = \case
Latest -> "latest"
Pending -> "pending"
AtBlock number -> J.String $ "0x" <> T.pack (showHex number "")
-- | The dry run of a registrar transaction; an estimate above the configured cap is refused.
estimateGas :: ChainClient -> Address -> ByteString -> IO (Either ChainError Word64)
estimateGas c@ChainClient {ccRegistrar, ccConfig = ChainConfig {cGasLimitCap}} to calldata =
(>>= capped) <$> rpc c "eth_estimateGas" [J.object ["from" .= ccRegistrar, "to" .= to, "data" .= hex calldata], "pending"] quantity
where
capped gas
| gas > cGasLimitCap = Left $ ChainGasAboveCap gas
| otherwise = Right gas
maxPriorityFee :: ChainClient -> IO (Either ChainError Word64)
maxPriorityFee c = rpc c "eth_maxPriorityFeePerGas" [] quantity
signTransaction :: TVar ChaChaDRG -> ChainClient -> TxRequest -> IO (Either String SignedTx)
signTransaction g ChainClient {ccConfig = ChainConfig {cChainId, cServiceKey}} TxRequest {trTo, trData, trNonce, trGasLimit, trMaxFeePerGas, trMaxPriorityFeePerGas} =
fmap signed <$> signEip1559Tx g cServiceKey tx
where
tx =
Eip1559Tx
{ txChainId = cChainId,
txNonce = trNonce,
txMaxPriorityFeePerGas = fromIntegral trMaxPriorityFeePerGas,
txMaxFeePerGas = fromIntegral trMaxFeePerGas,
txGasLimit = trGasLimit,
txTo = trTo,
txValue = 0,
txData = trData
}
signed raw = SignedTx {stRaw = raw, stHash = TxHash $ keccak256 raw}
eip1559TxType :: Word8
eip1559TxType = 2
-- | The request a raw transaction from 'signTransaction' was signed from.
decodeSignedTx :: ByteString -> Either String TxRequest
decodeSignedTx raw = case B.uncons raw of
Just (txType, encoded) | txType == eip1559TxType -> case rlpItem encoded of
Right (RLPList [_chainId, nonce, tip, maxFee, gas, RLPBytes to, _value, RLPBytes trData, _accessList, _yParity, _r, _s], "") -> do
trTo <- maybe (Left "transaction: not an address") Right $ addressFromBytes to
TxRequest trTo trData <$> scalar nonce <*> scalar gas <*> scalar maxFee <*> scalar tip
Right _ -> Left "transaction: not a signed EIP-1559 transaction"
Left e -> Left e
_ -> Left "transaction: not an EIP-1559 transaction"
where
scalar = \case
RLPBytes b | B.length b <= 8 -> Right $ fromInteger $ os2ip b
_ -> Left "transaction: not a 64-bit scalar"
rlpItem :: ByteString -> Either String (RLPItem, ByteString)
rlpItem s = case B.uncons s of
Nothing -> Left "RLP: no item"
Just (prefix, rest)
| prefix < 0x80 -> Right (RLPBytes $ B.singleton prefix, rest)
| prefix <= 0xb7 -> bytesItem (fromIntegral $ prefix - 0x80) rest
| prefix < 0xc0 -> longLength (fromIntegral $ prefix - 0xb7) rest >>= uncurry bytesItem
| prefix <= 0xf7 -> listItem (fromIntegral $ prefix - 0xc0) rest
| otherwise -> longLength (fromIntegral $ prefix - 0xf7) rest >>= uncurry listItem
where
bytesItem n r = (\(payload, r') -> (RLPBytes payload, r')) <$> split n r
listItem n r = split n r >>= \(payload, r') -> (\items -> (RLPList items, r')) <$> rlpItems payload
rlpItems payload
| B.null payload = Right []
| otherwise = rlpItem payload >>= \(item, r) -> (item :) <$> rlpItems r
longLength n r = split n r >>= \(len, r') -> (,r') <$> fits (os2ip len) r'
fits len r
| len <= toInteger (B.length r) = Right $ fromInteger len
| otherwise = Left "RLP: truncated"
split n r
| n <= B.length r = Right $ B.splitAt n r
| otherwise = Left "RLP: truncated"
sendRawTransaction :: ChainClient -> ByteString -> IO (Either ChainError TxHash)
sendRawTransaction c raw = rpc c "eth_sendRawTransaction" [J.String $ hex raw] (fmap TxHash . bytes)
-- | The answer is parsed within the timeout, so a slow parse is bounded too.
rpc :: ChainClient -> Text -> [J.Value] -> (J.Value -> JT.Parser a) -> IO (Either ChainError a)
rpc ChainClient {ccManager, ccConfig = ChainConfig {cRpcUrl}, ccTimeout} method params parseResult =
timeout ccTimeout (try $ post >>= evaluate . answer) >>= \case
Nothing -> pure $ Left $ unavailable "timed out"
Just (Left (e :: HTTP.HttpException)) -> do
logWarn $ "chain RPC " <> method <> " failed: " <> httpFailureDetail cRpcUrl e
pure $ Left $ unavailable $ httpFailure e
Just (Right r) -> pure r
where
answer (status, body)
| LB.length body > fromIntegral maxRpcResponseBytes = Left $ unavailable $ "response over " <> tshow maxRpcResponseBytes <> " bytes"
| otherwise = case J.eitherDecode body of
Left _ -> refused Nothing
Right v -> either (refused . Just) id $ JT.parseEither response v
where
refused parseError
| not (statusIsSuccessful status) = Left $ unavailable $ "HTTP " <> tshow (statusCode status)
-- aeson's decode error quotes the body, which can be any page a proxy answers with
| otherwise = Left $ unavailable $ "not a JSON-RPC response" <> maybe "" ((": " <>) . T.pack) parseError
post = do
req <- HTTP.parseRequest cRpcUrl
HTTP.withResponse
req
{ HTTP.method = methodPost,
HTTP.redirectCount = 0,
HTTP.requestHeaders = (hContentType, "application/json") : HTTP.requestHeaders req,
HTTP.requestBody = HTTP.RequestBodyLBS requestBody
}
ccManager
$ \resp -> (HTTP.responseStatus resp,) <$> HTTP.brReadSome (HTTP.responseBody resp) (maxRpcResponseBytes + 1)
requestBody = J.encode $ J.object ["jsonrpc" .= ("2.0" :: Text), "id" .= (1 :: Int), "method" .= method, "params" .= params]
response = J.withObject "JSON-RPC response" $ \o -> o .:? "error" >>= maybe (Right <$> (parseResult =<< o .: "result")) (fmap Left . rpcError)
rpcError = J.withObject "JSON-RPC error" $ \e -> do
code <- e .: "code"
message <- e .: "message"
revertData <- e .:? "data"
pure $
if code == revertCode || revertMessage `T.isPrefixOf` message
then ChainReverted $ maybe (dataless message) (decodeRevert <=< JT.parseMaybe bytes) revertData
else unavailable $ "error " <> tshow code <> ": " <> T.take maxNodeMessageLength message
unavailable reason = ChainUnavailable $ method <> ": " <> reason
-- a node or proxy that drops the data can keep a reason in the message, as in "execution reverted: ERC721: invalid token ID"
dataless message
| message == revertMessage = Just RNWithoutData
| otherwise = Nothing
-- | Only the kind of failure, for callers: an exception's text can hold the URL or its host.
httpFailure :: HTTP.HttpException -> Text
httpFailure = \case
HTTP.InvalidUrlException {} -> "invalid RPC URL"
HTTP.HttpExceptionRequest _ content -> case content of
HTTP.ResponseTimeout -> "timed out"
HTTP.ConnectionTimeout -> "connection timed out"
HTTP.ConnectionFailure _ -> "connection failed"
_ -> "request failed"
-- | The failure's detail for the service log, with the RPC URL and its host, path and query replaced, since they can carry a provider's key.
httpFailureDetail :: String -> HTTP.HttpException -> Text
httpFailureDetail rpcUrl e = foldl' (\t secret -> T.replace secret "<redacted>" t) detail secrets
where
detail = case e of
HTTP.InvalidUrlException _ reason -> "invalid URL: " <> T.pack reason
HTTP.HttpExceptionRequest _ content -> tshow content
secrets = filter ((> 1) . T.length) $ T.pack rpcUrl : maybe [] urlParts (HTTP.parseRequest rpcUrl)
urlParts req = map decodeLatin1 [HTTP.host req, HTTP.path req, HTTP.queryString req]
nullable :: (J.Value -> JT.Parser a) -> J.Value -> JT.Parser (Maybe a)
nullable p = \case
J.Null -> pure Nothing
v -> Just <$> p v
quantity :: forall a. (Integral a, Bounded a) => J.Value -> JT.Parser a
quantity = J.withText "quantity" $ \t -> case T.stripPrefix "0x" t of
Just h | [(n, "")] <- readHex (T.unpack h) -> pure n
Just h | T.length h <= maxQuantityDigits, [(n, "")] <- readHex (T.unpack h), n <= toInteger (maxBound :: a) -> pure $ fromInteger n
_ -> fail "not a quantity"
bytes :: J.Value -> JT.Parser ByteString
bytes = J.withText "data" $ \t -> case T.stripPrefix "0x" t of
Just h | Right bs <- convertFromBase Base16 (encodeUtf8 h) -> pure bs
_ -> fail "not hex data"
hex :: ByteString -> Text
hex bs = "0x" <> decodeLatin1 (convertToBase Base16 bs)
@@ -0,0 +1,211 @@
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
module StoreService.Names.Contracts
( Contracts (ctDeadline),
NameStatus (..),
RegisteredName (..),
NameRecords (..),
CommitmentAges (..),
newContracts,
secondsPerYear,
nameStatus,
nameRecords,
textRecord,
chainPriceCents,
sponsorNonce,
resolverNonce,
ownerOfToken,
nameExpires,
commitmentTime,
controllerAvailable,
commitmentAges,
)
where
import Control.Concurrent.Async (Concurrently (..))
import Control.Monad.Except (ExceptT (..), runExceptT)
import Data.Bifunctor (first)
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as B
import Data.Functor.Compose (Compose (..))
import Data.IORef (IORef, atomicWriteIORef, newIORef, readIORef)
import Data.Maybe (fromMaybe)
import Data.Text (Text)
import Data.Text.Encoding (decodeLatin1, encodeUtf8)
import Data.Word (Word64)
import Simplex.Messaging.Eth.Address (Address)
import Simplex.Messaging.SimplexName (LabelHash (..), SimplexTLD)
import Simplex.Messaging.Util (tshow)
import StoreService.Config (ChainConfig (..))
import StoreService.Names.Abi
import StoreService.Names.Chain (Block (..), BlockTag (..), ChainClient (..), ChainError (..), ethCallAt, latestBlock)
import StoreService.Names.Registration (channelRecordKey, contactRecordKey, labelNode, nodeBytes)
import StoreService.Names.Revert (RevertName (..))
import System.Timeout (timeout)
data Contracts = Contracts
{ ctChain :: ChainClient,
ctTLD :: SimplexTLD,
ctRegistrar :: IORef (Maybe RegistrarConstants),
ctCommitmentAges :: IORef (Maybe CommitmentAges),
-- | microseconds for all the reads of one name status or of one name's records
ctDeadline :: Int
}
data RegistrarConstants = RegistrarConstants {rcRegistry :: Address, rcGracePeriod :: Integer}
data NameStatus = NSAvailable | NSReserved | NSRegistered RegisteredName
deriving (Eq, Show)
data RegisteredName = RegisteredName
{ rnOwner :: Address,
rnResolver :: Address,
rnExpiresAt :: Word64,
rnGracePeriod :: Integer
}
deriving (Eq, Show)
-- | The default resolver's records ("" when unset) and the owner's nonce for the next edit.
data NameRecords = NameRecords {rdContact :: Text, rdChannel :: Text, rdNonce :: Word64}
deriving (Eq, Show)
data CommitmentAges = CommitmentAges {caMin :: Integer, caMax :: Integer}
deriving (Eq, Show)
secondsPerYear :: Integer
secondsPerYear = 31536000
attoUsdPerCent :: Integer
attoUsdPerCent = 10 ^ (16 :: Int)
-- | One call's timeout, so a node that hangs fails a status or a records read once, not once per read.
nameReadsDeadline :: Int
nameReadsDeadline = 10000000
-- | Reads nothing: the registrar's constants and the commitment ages are read on first use and kept once read.
newContracts :: SimplexTLD -> ChainClient -> IO Contracts
newContracts ctTLD ctChain = do
ctRegistrar <- newIORef Nothing
ctCommitmentAges <- newIORef Nothing
pure Contracts {ctChain, ctTLD, ctRegistrar, ctCommitmentAges, ctDeadline = nameReadsDeadline}
-- | Registered while @nameExpires + GRACE_PERIOD@ is not before the latest block's time.
nameStatus :: Contracts -> LabelHash -> IO (Either ChainError NameStatus)
nameStatus ct@Contracts {ctChain} lh = withinDeadline ct "name status" $ runExceptT $ do
(RegistrarConstants {rcRegistry, rcGracePeriod}, expires, Block {blockTimestamp}) <-
ExceptT $ together $ (,,) <$> concurrent (registrarConstants ct) <*> concurrent (nameExpires ct Latest lh) <*> concurrent (latestBlock ctChain)
if toInteger expires + rcGracePeriod >= toInteger blockTimestamp
then do
let node = nodeArg ct lh
registryRead signature = concurrent $ call ct rcRegistry (signature, node) decodeAddress
(rnOwner, rnResolver) <- ExceptT $ together $ (,) <$> registryRead "owner(bytes32)" <*> registryRead "resolver(bytes32)"
pure $ NSRegistered RegisteredName {rnOwner, rnResolver, rnExpiresAt = expires, rnGracePeriod = rcGracePeriod}
else do
reason <- ExceptT $ call ct (controller ct) ("reservedNames(bytes32)", labelHashArg lh) decodeUint256
pure $ if reason /= 0 then NSReserved else NSAvailable
-- | Nothing for a name on another resolver contract, or none: the service reads no records from a contract it does not know.
nameRecords :: Contracts -> LabelHash -> RegisteredName -> IO (Either ChainError (Maybe NameRecords))
nameRecords ct lh RegisteredName {rnOwner, rnResolver}
| rnResolver /= resolver ct = pure $ Right Nothing
| otherwise =
withinDeadline ct "name records" $ together $
(\rdContact rdChannel rdNonce -> Just NameRecords {rdContact, rdChannel, rdNonce})
<$> concurrent (textRecord ct lh contactRecordKey)
<*> concurrent (textRecord ct lh channelRecordKey)
<*> concurrent (resolverNonce ct rnOwner)
-- | The default resolver's record, "" when unset.
textRecord :: Contracts -> LabelHash -> ByteString -> IO (Either ChainError Text)
textRecord ct lh key = call ct (resolver ct) ("text(bytes32,string)", abiTuple [Static $ nodeArg ct lh, Dynamic $ abiBytes key]) decodeString
-- | Cents for a label of this length and these years. The oracle prices by length only,
-- so a placeholder label of that length keeps the label from the RPC node.
chainPriceCents :: Contracts -> Int -> Int -> IO (Either ChainError Int)
chainPriceCents ct len years = call ct (controller ct) ("rentPriceUSD(string,uint256)", args) $ \ret -> do
base <- decodeUint256 ret
let cents = base `div` attoUsdPerCent
if cents <= toInteger (maxBound :: Int) then Right (fromInteger cents) else Left AERange
where
args = abiTuple [Dynamic $ abiBytes $ B.replicate len 'a', Static $ uint256 $ toInteger years * secondsPerYear]
sponsorNonce :: Contracts -> Address -> IO (Either ChainError Word64)
sponsorNonce ct owner = call ct (cSponsor $ chainConfig ct) ("nonces(address)", addressWord owner) decodeWord64
resolverNonce :: Contracts -> Address -> IO (Either ChainError Word64)
resolverNonce ct owner = call ct (resolver ct) ("nonces(address)", addressWord owner) decodeWord64
-- | Nothing when nobody holds the name: @ownerOf@ then fails the registrar's bare @require@ on the expiry,
-- a revert without data. Any other revert is a failed read.
ownerOfToken :: Contracts -> BlockTag -> LabelHash -> IO (Either ChainError (Maybe Address))
ownerOfToken ct tag lh =
callAt ct tag (baseRegistrar ct) ("ownerOf(uint256)", labelHashArg lh) decodeAddress >>= \case
Left (ChainReverted (Just RNWithoutData)) -> pure $ Right Nothing
r -> pure $ Just <$> r
nameExpires :: Contracts -> BlockTag -> LabelHash -> IO (Either ChainError Word64)
nameExpires ct tag lh = callAt ct tag (baseRegistrar ct) ("nameExpires(uint256)", labelHashArg lh) decodeWord64
-- | The block time of the commitment, Nothing when the controller holds none.
commitmentTime :: Contracts -> ByteString -> IO (Either ChainError (Maybe Word64))
commitmentTime ct commitment = fmap nonZero <$> call ct (controller ct) ("commitments(bytes32)", commitment) decodeWord64
where
nonZero t = if t == 0 then Nothing else Just t
controllerAvailable :: Contracts -> Text -> IO (Either ChainError Bool)
controllerAvailable ct label = call ct (controller ct) ("available(string)", abiTuple [Dynamic $ abiBytes $ encodeUtf8 label]) decodeBool
commitmentAges :: Contracts -> IO (Either ChainError CommitmentAges)
commitmentAges ct@Contracts {ctCommitmentAges} = readOnce ctCommitmentAges $ runExceptT $ do
caMin <- ExceptT $ call ct (controller ct) ("minCommitmentAge()", "") decodeUint256
caMax <- ExceptT $ call ct (controller ct) ("maxCommitmentAge()", "") decodeUint256
pure CommitmentAges {caMin, caMax}
registrarConstants :: Contracts -> IO (Either ChainError RegistrarConstants)
registrarConstants ct@Contracts {ctRegistrar} = readOnce ctRegistrar $ runExceptT $ do
rcRegistry <- ExceptT $ call ct (baseRegistrar ct) ("ens()", "") decodeAddress
rcGracePeriod <- ExceptT $ call ct (baseRegistrar ct) ("GRACE_PERIOD()", "") decodeUint256
pure RegistrarConstants {rcRegistry, rcGracePeriod}
-- | Concurrent first uses may each read; they read the same immutable values.
readOnce :: IORef (Maybe a) -> IO (Either ChainError a) -> IO (Either ChainError a)
readOnce ref readChain =
readIORef ref >>= \case
Just a -> pure $ Right a
Nothing -> readChain >>= either (pure . Left) (\a -> Right a <$ atomicWriteIORef ref (Just a))
-- | Reads run at once; the first failure in argument order is the answer.
together :: Compose Concurrently (Either ChainError) a -> IO (Either ChainError a)
together = runConcurrently . getCompose
concurrent :: IO (Either ChainError a) -> Compose Concurrently (Either ChainError) a
concurrent = Compose . Concurrently
withinDeadline :: Contracts -> Text -> IO (Either ChainError a) -> IO (Either ChainError a)
withinDeadline Contracts {ctDeadline} what action = fromMaybe (Left $ ChainUnavailable $ what <> ": timed out") <$> timeout ctDeadline action
call :: Contracts -> Address -> (ByteString, ByteString) -> (ByteString -> Either AbiError a) -> IO (Either ChainError a)
call ct = callAt ct Latest
-- | An answer that does not decode is a node failure, as an RPC error is.
callAt :: Contracts -> BlockTag -> Address -> (ByteString, ByteString) -> (ByteString -> Either AbiError a) -> IO (Either ChainError a)
callAt Contracts {ctChain} tag to (signature, args) decode =
(>>= first malformed . decode) <$> ethCallAt ctChain tag to (selector signature <> args)
where
malformed e = ChainUnavailable $ "eth_call: " <> decodeLatin1 signature <> " answered " <> tshow e
labelHashArg :: LabelHash -> ByteString
labelHashArg (LabelHash h) = h
nodeArg :: Contracts -> LabelHash -> ByteString
nodeArg Contracts {ctTLD} = nodeBytes . labelNode ctTLD
chainConfig :: Contracts -> ChainConfig
chainConfig = ccConfig . ctChain
controller, resolver, baseRegistrar :: Contracts -> Address
controller = cController . chainConfig
resolver = cResolver . chainConfig
baseRegistrar = cBaseRegistrar . chainConfig
@@ -4,6 +4,12 @@
module StoreService.Names.Registration
( Registration (..),
RegisterIntent (..),
Node,
nodeBytes,
namehash,
labelNode,
contactRecordKey,
channelRecordKey,
sponsorDomain,
makeCommitment,
commitCalldata,
@@ -17,8 +23,8 @@ import Control.Monad (unless, when)
import Control.Monad.Except (ExceptT (..), runExceptT, throwError)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.Maybe (catMaybes)
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Encoding (encodeUtf8)
import Data.Word (Word64)
import Simplex.Messaging.Crypto (keccak256)
@@ -26,7 +32,7 @@ import Simplex.Messaging.Crypto.Secp256k1 (RecoverableSignature)
import Simplex.Messaging.Encoding.String (strEncode)
import Simplex.Messaging.Eth.Address (Address, recoverAddress)
import Simplex.Messaging.Eth.EIP712 (Eip712Domain (..), Eip712Value (..), hashTypedData, serializeSignature)
import Simplex.Messaging.SimplexName (SimplexTLD)
import Simplex.Messaging.SimplexName (LabelHash (..), SimplexTLD)
import StoreService.Names.Abi (AbiValue (..), abiArray, abiBytes, abiTuple, addressWord, selector, uint256)
data Registration = Registration
@@ -36,10 +42,20 @@ data Registration = Registration
rDuration :: Word64,
rSecret :: ByteString,
rResolver :: Address,
rContactLinks :: [Text],
rChannelLinks :: [Text]
rContactLink :: Maybe Text,
rChannelLink :: Maybe Text
}
-- | Only built by 'labelNode', so it always holds 32 bytes.
newtype Node = Node ByteString
nodeBytes :: Node -> ByteString
nodeBytes (Node node) = node
contactRecordKey, channelRecordKey :: ByteString
contactRecordKey = "simplex.contact"
channelRecordKey = "simplex.channel"
data RegisterIntent = RegisterIntent
{ riRegistration :: Registration,
riNonce :: Word64,
@@ -104,15 +120,18 @@ registrationTuple r@Registration {rLabel, rOwner, rDuration, rSecret, rResolver}
referrer = B.replicate 32 0
recordCalls :: Registration -> [ByteString]
recordCalls Registration {rLabel, rTLD, rContactLinks, rChannelLinks} =
[setText key ls | (key, ls) <- [("simplex.contact", rContactLinks), ("simplex.channel", rChannelLinks)], not (null ls)]
recordCalls Registration {rLabel, rTLD, rContactLink, rChannelLink} =
catMaybes [setText contactRecordKey <$> rContactLink, setText channelRecordKey <$> rChannelLink]
where
setText key ls =
setText key link =
selector "setText(bytes32,string,string)"
<> abiTuple [Static node, Dynamic $ abiBytes key, Dynamic $ abiBytes $ encodeUtf8 $ T.intercalate ";" ls]
node = namehash rTLD rLabel
<> abiTuple [Static node, Dynamic $ abiBytes key, Dynamic $ abiBytes $ encodeUtf8 link]
Node node = namehash rTLD rLabel
namehash :: SimplexTLD -> Text -> ByteString
namehash tld label = keccak256 $ tldNode <> keccak256 (encodeUtf8 label)
namehash :: SimplexTLD -> Text -> Node
namehash tld = labelNode tld . LabelHash . keccak256 . encodeUtf8
labelNode :: SimplexTLD -> LabelHash -> Node
labelNode tld (LabelHash h) = Node $ keccak256 $ tldNode <> h
where
tldNode = keccak256 $ B.replicate 32 0 <> keccak256 (B.drop 1 $ strEncode tld)
@@ -0,0 +1,119 @@
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
module StoreService.Names.Revert (RevertName (..), decodeRevert) where
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import StoreService.Names.Abi (selector)
-- | The custom errors of SimplexController, SimplexSponsor, BaseRegistrarImplementation and SimplexResolver.
-- The sponsor passes the controller's and the base registrar's reverts through, so any call can revert with any of them.
data RevertName
= RNAlreadyFrozen
| RNCommitmentNotFound
| RNCommitmentTooNew
| RNCommitmentTooOld
| RNDurationTooShort
| RNFrozen
| RNInsufficientAllowance
| RNInsufficientValue
| RNInvalidEVMAddress
| RNInvalidNonce
| RNInvalidSignature
| RNLabelTooLong
| RNMaxCommitmentAgeTooHigh
| RNMaxCommitmentAgeTooLow
| RNMinCharLengthCanOnlyDecrease
| RNMinCharLengthZero
| RNMinCommitmentAgeZero
| RNNameNotAvailable
| RNNameNotReserved
| RNNameReserved
| RNNameTooShort
| RNNftGateCanOnlyBeDisabled
| RNNftRequired
| RNNodeNotOwnedByRegistrar
| RNNotBeneficiary
| RNNotNameOwner
| RNNotOffered
| RNNotOwnerOrBeneficiary
| RNNotSponsor
| RNNotSubnameRegistrar
| RNOffsetOutOfBoundsError
| RNOwnerMustBeCaller
| RNPublicSalesClosed
| RNReasonRequired
| RNRecipientMustBeCaller
| RNReentrantCall
| RNResolverRequiredWhenDataSupplied
| RNReverseRecordNotSupported
| RNSignatureExpired
| RNTransferFailed
| RNTransferToSelf
| RNUnexpiredCommitmentExists
| RNZeroAddress
| -- | a revert with empty or no data, as a bare @require@ or @revert()@ gives
RNWithoutData
deriving (Eq, Show, Enum, Bounded)
-- | Nothing for a revert without data, which has no selector.
revertSignature :: RevertName -> Maybe ByteString
revertSignature = \case
RNAlreadyFrozen -> Just "AlreadyFrozen()"
RNCommitmentNotFound -> Just "CommitmentNotFound(bytes32)"
RNCommitmentTooNew -> Just "CommitmentTooNew(bytes32,uint256,uint256)"
RNCommitmentTooOld -> Just "CommitmentTooOld(bytes32,uint256,uint256)"
RNDurationTooShort -> Just "DurationTooShort(uint256)"
RNFrozen -> Just "Frozen()"
RNInsufficientAllowance -> Just "InsufficientAllowance(uint256,uint256)"
RNInsufficientValue -> Just "InsufficientValue()"
RNInvalidEVMAddress -> Just "InvalidEVMAddress(bytes)"
RNInvalidNonce -> Just "InvalidNonce()"
RNInvalidSignature -> Just "InvalidSignature()"
RNLabelTooLong -> Just "LabelTooLong(uint256,uint256)"
RNMaxCommitmentAgeTooHigh -> Just "MaxCommitmentAgeTooHigh()"
RNMaxCommitmentAgeTooLow -> Just "MaxCommitmentAgeTooLow()"
RNMinCharLengthCanOnlyDecrease -> Just "MinCharLengthCanOnlyDecrease()"
RNMinCharLengthZero -> Just "MinCharLengthZero()"
RNMinCommitmentAgeZero -> Just "MinCommitmentAgeZero()"
RNNameNotAvailable -> Just "NameNotAvailable(string)"
RNNameNotReserved -> Just "NameNotReserved(string)"
RNNameReserved -> Just "NameReserved(string)"
RNNameTooShort -> Just "NameTooShort(string,uint8)"
RNNftGateCanOnlyBeDisabled -> Just "NftGateCanOnlyBeDisabled()"
RNNftRequired -> Just "NftRequired()"
RNNodeNotOwnedByRegistrar -> Just "NodeNotOwnedByRegistrar()"
RNNotBeneficiary -> Just "NotBeneficiary()"
RNNotNameOwner -> Just "NotNameOwner()"
RNNotOffered -> Just "NotOffered()"
RNNotOwnerOrBeneficiary -> Just "NotOwnerOrBeneficiary()"
RNNotSponsor -> Just "NotSponsor()"
RNNotSubnameRegistrar -> Just "NotSubnameRegistrar()"
RNOffsetOutOfBoundsError -> Just "OffsetOutOfBoundsError(uint256,uint256)"
RNOwnerMustBeCaller -> Just "OwnerMustBeCaller()"
RNPublicSalesClosed -> Just "PublicSalesClosed()"
RNReasonRequired -> Just "ReasonRequired()"
RNRecipientMustBeCaller -> Just "RecipientMustBeCaller()"
RNReentrantCall -> Just "ReentrantCall()"
RNResolverRequiredWhenDataSupplied -> Just "ResolverRequiredWhenDataSupplied()"
RNReverseRecordNotSupported -> Just "ReverseRecordNotSupported()"
RNSignatureExpired -> Just "SignatureExpired()"
RNTransferFailed -> Just "TransferFailed()"
RNTransferToSelf -> Just "TransferToSelf()"
RNUnexpiredCommitmentExists -> Just "UnexpiredCommitmentExists(bytes32)"
RNZeroAddress -> Just "ZeroAddress()"
RNWithoutData -> Nothing
revertSelectors :: Map ByteString RevertName
revertSelectors = M.fromList [(selector signature, n) | n <- [minBound .. maxBound], Just signature <- [revertSignature n]]
-- | The error a revert's data names by its selector, if it is one of the contracts' errors.
decodeRevert :: ByteString -> Maybe RevertName
decodeRevert revertData
| B.null revertData = Just RNWithoutData
| otherwise = M.lookup (B.take selectorSize revertData) revertSelectors
where
selectorSize = 4
+4
View File
@@ -762,7 +762,9 @@ test-suite simplex-chat-test
Bots.StoreService.GroupIntegrationTests
Bots.StoreService.GroupTests
Bots.StoreService.NameRegistrationTests
Bots.StoreService.NamesChainTests
Bots.StoreService.NamesCodesTests
Bots.StoreService.NamesContractsTests
Bots.StoreService.NamesLabelTests
Bots.StoreService.StoreVerifierTests
Bots.StoreService.StripeTests
@@ -789,8 +791,10 @@ test-suite simplex-chat-test
StoreService.Names.Abi
StoreService.Names.Chain
StoreService.Names.Codes
StoreService.Names.Contracts
StoreService.Names.Label
StoreService.Names.Registration
StoreService.Names.Revert
StoreService.Names.Store
StoreService.Names.Turns
StoreService.Options
+190 -31
View File
@@ -1,44 +1,92 @@
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
module Bots.StoreService.FakeEthNode
( FakeEthNode (..),
CallAnswer (..),
Fault (..),
withFakeEthNode,
revertCalls,
fakeChainConfig,
answerCall,
setFault,
clearFault,
setBlock,
mine,
sentTransactions,
revertFault,
fakeChainId,
fakeController,
fakeSponsor,
fakeBaseRegistrar,
fakeResolver,
fakeRegistrarKey,
fakeGas,
fakeTip,
fakeBaseFee,
)
where
import Control.Concurrent (threadDelay)
import Control.Concurrent.STM
import Control.Exception (finally)
import Data.Aeson ((.:), (.=))
import qualified Data.Aeson as J
import qualified Data.Aeson.Types as JT
import Data.ByteArray.Encoding (Base (Base16), convertFromBase, convertToBase)
import qualified Data.ByteArray as BA
import Data.ByteArray.Encoding (Base (Base16), convertFromBase)
import Data.ByteString (ByteString)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Encoding (decodeLatin1, encodeUtf8)
import Network.HTTP.Client (Manager)
import qualified Network.HTTP.Client as HTTP
import Network.HTTP.Types (badRequest400, hContentType, ok200)
import Data.Text.Encoding (encodeUtf8)
import Data.Word (Word64)
import Network.HTTP.Types (badGateway502, badRequest400, hContentType, ok200)
import Network.Wai (Application, responseLBS, strictRequestBody)
import qualified Network.Wai.Handler.Warp as Warp
import Numeric (showHex)
import Simplex.Messaging.Crypto (keccak256)
import qualified Simplex.Messaging.Crypto.Secp256k1 as S
import Simplex.Messaging.Encoding.String (strDecode)
import Simplex.Messaging.Eth.Address (Address, unAddress)
import Simplex.Messaging.Util (eitherToMaybe)
import StoreService.Config (ChainConfig (..))
import StoreService.Names.Abi (hex)
import StoreService.Names.Chain (TxRequest (..), decodeSignedTx)
data FakeEthNode = FakeEthNode
{ fnUrl :: String,
fnManager :: Manager,
fnState :: TVar FakeState
}
data CallAnswer = Returns ByteString | Reverts ByteString
data Fault
= RpcError Int Text (Maybe ByteString)
| -- | answers only once the node is closed
Hang
| HttpFailure
| -- | a 200 page that is not JSON, as a proxy may answer
NotJson
| Answers J.Value
| -- | answers as usual after this many microseconds
Slow Int
data FakeState = FakeState
{ fsRevert :: Bool,
fsSent :: [ByteString]
{ fsCalls :: Map (ByteString, ByteString) CallAnswer,
fsFaults :: Map Text Fault,
-- | every raw transaction received, newest first
fsSent :: [ByteString],
-- | the transactions the node knows and has not mined, by nonce
fsPool :: Map Word64 ByteString,
fsReceipts :: Map ByteString (Bool, Word64),
-- | the key's transaction count at the latest block
fsUsed :: Word64,
fsBlock :: (Word64, Word64),
-- | the suggested tip and the base fee
fsFees :: (Word64, Word64),
fsClosed :: Bool
}
fakeGas, fakeTip, fakeBaseFee :: Num a => a
@@ -46,51 +94,162 @@ fakeGas = 200000
fakeTip = 1000000000
fakeBaseFee = 2000000000
fakeChainId :: Word64
fakeChainId = 31337
fakeController, fakeSponsor, fakeBaseRegistrar, fakeResolver :: Address
fakeController = address "0x0165878a594ca255338adfa4d48449f69242eb8f"
fakeSponsor = address "0x9a676e781a523b5d0c0e43731313a708cb607508"
fakeBaseRegistrar = address "0xe7f1725e7734ce288f8367e1bb143e90bb3f0512"
fakeResolver = address "0x2279b7a0a67db372996a5fab50d91eaa73d2ebe6"
fakeRegistrarKey :: S.Secp256k1PrivateKey
fakeRegistrarKey = either error id $ S.mkPrivateKey $ BA.replicate 32 0x46
-- | 2026-01-01, block 1; each mined block is this many seconds later.
genesisTime, blockSeconds :: Word64
genesisTime = 1767225600
blockSeconds = 12
withFakeEthNode :: (FakeEthNode -> IO a) -> IO a
withFakeEthNode action = do
fnState <- newTVarIO FakeState {fsRevert = False, fsSent = []}
fnManager <- HTTP.newManager HTTP.defaultManagerSettings
fnState <-
newTVarIO
FakeState
{ fsCalls = M.empty,
fsFaults = M.empty,
fsSent = [],
fsPool = M.empty,
fsReceipts = M.empty,
fsUsed = 0,
fsBlock = (1, genesisTime),
fsFees = (fakeTip, fakeBaseFee),
fsClosed = False
}
Warp.testWithApplication (pure $ fakeApp fnState) $ \port ->
action FakeEthNode {fnUrl = "http://127.0.0.1:" <> show port, fnManager, fnState}
action FakeEthNode {fnUrl = "http://127.0.0.1:" <> show port, fnState}
`finally` atomically (modifyTVar' fnState $ \s -> s {fsClosed = True})
revertCalls :: FakeEthNode -> IO ()
revertCalls FakeEthNode {fnState} = atomically $ modifyTVar' fnState $ \s -> s {fsRevert = True}
fakeChainConfig :: FakeEthNode -> ChainConfig
fakeChainConfig FakeEthNode {fnUrl} =
ChainConfig
{ cRpcUrl = fnUrl,
cChainId = fakeChainId,
cController = fakeController,
cSponsor = fakeSponsor,
cBaseRegistrar = fakeBaseRegistrar,
cResolver = fakeResolver,
cServiceKey = fakeRegistrarKey,
cGasLimitCap = 8000000
}
answerCall :: FakeEthNode -> Address -> ByteString -> CallAnswer -> IO ()
answerCall FakeEthNode {fnState} to calldata a = atomically $ modifyTVar' fnState $ \s -> s {fsCalls = M.insert (unAddress to, calldata) a $ fsCalls s}
-- | Every request for the method fails this way until 'clearFault'.
setFault :: FakeEthNode -> Text -> Fault -> IO ()
setFault FakeEthNode {fnState} method f = atomically $ modifyTVar' fnState $ \s -> s {fsFaults = M.insert method f $ fsFaults s}
clearFault :: FakeEthNode -> Text -> IO ()
clearFault FakeEthNode {fnState} method = atomically $ modifyTVar' fnState $ \s -> s {fsFaults = M.delete method $ fsFaults s}
revertFault :: ByteString -> Fault
revertFault = RpcError 3 "execution reverted" . Just
-- | Sets the latest block's number and time.
setBlock :: FakeEthNode -> Word64 -> Word64 -> IO ()
setBlock FakeEthNode {fnState} number time = atomically $ modifyTVar' fnState $ \s -> s {fsBlock = (number, time)}
-- | Mines a new block with these transaction hashes and receipt statuses, and returns its number.
-- A mined transaction of the pool uses its nonce, and the pool loses every transaction below it.
mine :: FakeEthNode -> [(ByteString, Bool)] -> IO Word64
mine FakeEthNode {fnState} txs = atomically $ do
s@FakeState {fsBlock = (number, time), fsReceipts, fsPool, fsUsed} <- readTVar fnState
let number' = number + 1
mined = M.fromList [(h, (ok, number')) | (h, ok) <- txs]
used = maximum $ fsUsed : [nonce + 1 | (nonce, raw) <- M.toList fsPool, keccak256 raw `M.member` mined]
writeTVar fnState s {fsBlock = (number', time + blockSeconds), fsReceipts = M.union mined fsReceipts, fsPool = M.dropWhileAntitone (< used) fsPool, fsUsed = used}
pure number'
-- | The raw transactions in the order they were sent.
sentTransactions :: FakeEthNode -> IO [ByteString]
sentTransactions FakeEthNode {fnState} = fsSent <$> readTVarIO fnState
sentTransactions FakeEthNode {fnState} = reverse . fsSent <$> readTVarIO fnState
fakeApp :: TVar FakeState -> Application
fakeApp st req respond = do
body <- strictRequestBody req
case JT.parseMaybe request =<< J.decode body of
Just (method, params) -> do
reply <- atomically $ answer st method params
respond $ responseLBS ok200 [(hContentType, "application/json")] $ J.encode $ J.object $ ["jsonrpc" .= ("2.0" :: Text), "id" .= (1 :: Int)] <> reply
Just (method, params) ->
fault method >>= \case
Just HttpFailure -> respond $ responseLBS badGateway502 [] "bad gateway"
Just Hang -> do
atomically $ readTVar st >>= check . fsClosed
reply $ rpcError (-32000) "node closed" Nothing
Just (RpcError code message revertData) -> reply $ rpcError code message revertData
Just NotJson -> respond $ responseLBS ok200 [] "<html>Sign in to provider-api-key</html>"
Just (Answers v) -> reply ["result" .= v]
Just (Slow delay) -> threadDelay delay >> answered method params
Nothing -> answered method params
Nothing -> respond $ responseLBS badRequest400 [] "not a JSON-RPC request"
where
request = J.withObject "request" $ \o -> (,) <$> o .: "method" <*> o .: "params"
fault method = M.lookup method . fsFaults <$> readTVarIO st
answered method params = reply =<< atomically (answer st method params)
reply r = respond $ responseLBS ok200 [(hContentType, "application/json")] $ J.encode $ J.object $ ["jsonrpc" .= ("2.0" :: Text), "id" .= (1 :: Int)] <> r
answer :: TVar FakeState -> Text -> [J.Value] -> STM [JT.Pair]
answer st method params = do
s@FakeState {fsRevert, fsSent} <- readTVar st
s@FakeState {fsCalls, fsSent, fsPool, fsReceipts, fsUsed, fsBlock = (number, time), fsFees = (tip, baseFee)} <- readTVar st
case (method, params) of
("eth_estimateGas", _) -> pure $ if fsRevert then reverted else result $ quantity fakeGas
("eth_getTransactionCount", _) -> pure $ result $ quantity $ toInteger $ length fsSent
("eth_maxPriorityFeePerGas", _) -> pure $ result $ quantity fakeTip
("eth_getBlockByNumber", _) -> pure $ result $ J.object ["baseFeePerGas" .= quantity fakeBaseFee]
("eth_sendRawTransaction", [J.String raw]) | Just tx <- fromHex raw -> do
writeTVar st s {fsSent = tx : fsSent}
pure $ result $ hex $ keccak256 tx
_ -> pure ["error" .= J.object ["code" .= (-32601 :: Int), "message" .= ("method not found" :: Text)]]
("eth_call", [call, _])
| Just (to, calldata) <- JT.parseMaybe callTarget call ->
pure $ case M.lookup (unAddress to, calldata) fsCalls of
Just (Returns ret) -> result $ hex ret
Just (Reverts revertData) -> rpcError 3 "execution reverted" (Just revertData)
Nothing -> rpcError (-32000) "no fake answer for this call" Nothing
("eth_estimateGas", _) -> pure $ result $ quantity fakeGas
("eth_getTransactionCount", [_, J.String "latest"]) -> pure $ result $ quantity $ toInteger fsUsed
("eth_getTransactionCount", [_, J.String "pending"]) ->
pure $ result $ quantity $ toInteger $ fsUsed + fromIntegral (length $ takeWhile (`M.member` fsPool) [fsUsed ..])
("eth_maxPriorityFeePerGas", _) -> pure $ result $ quantity $ toInteger tip
("eth_getBlockByNumber", [J.String "latest", _]) -> pure $ result $ blockJson baseFee number time
("eth_getTransactionReceipt", [J.String h]) | Just hash <- fromHex h -> pure $ result $ case M.lookup hash fsReceipts of
Just (ok, block) -> J.object ["transactionHash" .= h, "status" .= quantity (if ok then 1 else 0), "blockNumber" .= quantity (toInteger block)]
Nothing -> J.Null
("eth_getTransactionByHash", [J.String h]) | Just hash <- fromHex h -> pure $ result $ case M.lookup hash fsReceipts of
Just (_, block) -> J.object ["hash" .= h, "blockNumber" .= quantity (toInteger block)]
Nothing
| any ((== hash) . keccak256) fsPool -> J.object ["hash" .= h, "blockNumber" .= J.Null]
| otherwise -> J.Null
("eth_sendRawTransaction", [J.String raw])
| Just tx <- fromHex raw,
Right TxRequest {trNonce, trMaxFeePerGas, trMaxPriorityFeePerGas} <- decodeSignedTx tx -> do
let accept = (result $ hex $ keccak256 tx) <$ writeTVar st s {fsSent = tx : fsSent, fsPool = M.insert trNonce tx fsPool}
case M.lookup trNonce fsPool of
_ | trNonce < fsUsed -> pure $ rpcError (-32000) "nonce too low" Nothing
Just known
| known == tx -> pure $ rpcError (-32000) "already known" Nothing
-- geth and reth replace a pending transaction only when both its fees are at least 10% higher
| Right TxRequest {trMaxFeePerGas = knownMax, trMaxPriorityFeePerGas = knownTip} <- decodeSignedTx known,
trMaxFeePerGas * 10 < knownMax * 11 || trMaxPriorityFeePerGas * 10 < knownTip * 11 ->
pure $ rpcError (-32000) "replacement transaction underpriced" Nothing
_ -> accept
_ -> pure $ rpcError (-32601) "method not found" Nothing
where
result v = ["result" .= v]
reverted = ["error" .= J.object ["code" .= (3 :: Int), "message" .= ("execution reverted" :: Text)]]
callTarget = J.withObject "call" $ \o -> (,) <$> o .: "to" <*> (maybe (fail "not hex data") pure . fromHex =<< o .: "data")
blockJson :: Word64 -> Word64 -> Word64 -> J.Value
blockJson baseFee number time = J.object ["number" .= quantity (toInteger number), "timestamp" .= quantity (toInteger time), "baseFeePerGas" .= quantity (toInteger baseFee)]
rpcError :: Int -> Text -> Maybe ByteString -> [JT.Pair]
rpcError code message revertData = ["error" .= J.object (["code" .= code, "message" .= message] <> maybe [] (\d -> ["data" .= hex d]) revertData)]
quantity :: Integer -> Text
quantity n = "0x" <> T.pack (showHex n "")
hex :: ByteString -> Text
hex bs = "0x" <> decodeLatin1 (convertToBase Base16 bs)
fromHex :: Text -> Maybe ByteString
fromHex t = T.stripPrefix "0x" t >>= eitherToMaybe . convertFromBase Base16 . encodeUtf8
address :: ByteString -> Address
address = either error id . strDecode
@@ -5,18 +5,17 @@ module Bots.StoreService.NameRegistrationTests (badgeNameRegistrationTests) wher
import StoreService.Names.Chain
import StoreService.Names.Registration
import StoreService.Names.Revert (RevertName (..))
import Bots.StoreService.FakeEthNode
import Bots.StoreService.WebUIMock
import Control.Concurrent.STM (TVar)
import Crypto.Random (ChaChaDRG)
import qualified Data.ByteArray as BA
import Data.ByteArray.Encoding (Base (Base16), convertToBase)
import Data.ByteArray.Encoding (Base (Base16), convertFromBase, convertToBase)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.Text (Text)
import Data.Word (Word64)
import qualified Simplex.Messaging.Crypto as C
import qualified Simplex.Messaging.Crypto.Secp256k1 as S
import Simplex.Messaging.Encoding.String (strDecode)
import Simplex.Messaging.Eth.Address (Address)
import Simplex.Messaging.Eth.EIP712 (Eip712Domain)
@@ -25,7 +24,7 @@ import Simplex.Messaging.SimplexName (SimplexTLD (..))
import Test.Hspec
badgeNameRegistrationTests :: Spec
badgeNameRegistrationTests = describe "store service name registration" $ do
badgeNameRegistrationTests = describe "StoreService names: registration" $ do
g <- runIO C.newRandom
-- expected encodings and signatures are viem's, against the SimplexController, SimplexSponsor and SimplexResolver ABIs
describe "encoding" $ do
@@ -36,24 +35,24 @@ badgeNameRegistrationTests = describe "store service name registration" $ do
it "rejects an intent signed by another wallet" $ testVerifyOtherSigner g
it "rejects an intent past its deadline" $ testVerifyExpired g
it "rejects a secret that is not 32 bytes" $ testVerifyShortSecret g
it "sends nothing when the dry run reverts" $ testRevertedDryRun g
it "reads the register's dry run reverting as the sponsor's error" $ testRevertedDryRun g
it "registers a name the client committed to without revealing it" $ testCommitThenRegister g
testRegisterCalldataWithRecords :: TVar ChaChaDRG -> IO ()
testRegisterCalldataWithRecords g = do
intent <- knownIntent g knownRegistration
toHex (registerWithCreditCalldata intent)
`shouldBe` "c4bd2ab50000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f4865700000000000000000000000000000000000000000000000000000000000000048000000000000000000000000000000000000000000000000000000000000001000000000000000000000000009858effd232b4033e47d90003d41ec34ecaeda940000000000000000000000000000000000000000000000000000000003c2670011111111111111111111111111111111111111111111111111111111111111110000000000000000000000002279b7a0a67db372996a5fab50d91eaa73d2ebe6000000000000000000000000000000000000000000000000000000000000014000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000762616b657279310000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000016000000000000000000000000000000000000000000000000000000000000000e410f13a8c58c186cadf476923d25ea4950487d1aaf21906ba5574c87f5b9435b61b994370000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000000f73696d706c65782e636f6e746163740000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002068747470733a2f2f736d702e73696d706c65782e696d2f6123636f6e7461637400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010410f13a8c58c186cadf476923d25ea4950487d1aaf21906ba5574c87f5b9435b61b994370000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000000f73696d706c65782e6368616e6e656c0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003b68747470733a2f2f736d70312e73696d706c65782e696d2f63236f6e653b68747470733a2f2f736d70322e73696d706c65782e696d2f632374776f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000417caacde8c40eab73721947d6d811746266da03d0cb50da2e7efea9c7c926b7124cc612132c7c5e178fcf75afcc709994ca96b16ef30d9763ab22102192e9ac441b00000000000000000000000000000000000000000000000000000000000000"
`shouldBe` "c4bd2ab50000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f4865700000000000000000000000000000000000000000000000000000000000000046000000000000000000000000000000000000000000000000000000000000001000000000000000000000000009858effd232b4033e47d90003d41ec34ecaeda940000000000000000000000000000000000000000000000000000000003c2670011111111111111111111111111111111111111111111111111111111111111110000000000000000000000002279b7a0a67db372996a5fab50d91eaa73d2ebe6000000000000000000000000000000000000000000000000000000000000014000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000762616b657279310000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000016000000000000000000000000000000000000000000000000000000000000000e410f13a8c58c186cadf476923d25ea4950487d1aaf21906ba5574c87f5b9435b61b994370000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000000f73696d706c65782e636f6e746163740000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002068747470733a2f2f736d702e73696d706c65782e696d2f6123636f6e746163740000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e410f13a8c58c186cadf476923d25ea4950487d1aaf21906ba5574c87f5b9435b61b994370000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000000f73696d706c65782e6368616e6e656c0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001d68747470733a2f2f736d70312e73696d706c65782e696d2f63236f6e65000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000041f310b273d0e0ab0975a66d383fe818a5ec3474fcd922dbf3fe70094a3c0ceae86559b13ea0728a330613c6fe236a89a026daf345dcc8c0616e9eda2c69cbeb091b00000000000000000000000000000000000000000000000000000000000000"
testRegisterCalldataWithoutRecords :: TVar ChaChaDRG -> IO ()
testRegisterCalldataWithoutRecords g = do
intent <- knownIntent g knownRegistration {rContactLinks = [], rChannelLinks = []}
intent <- knownIntent g knownRegistration {rContactLink = Nothing, rChannelLink = Nothing}
toHex (registerWithCreditCalldata intent)
`shouldBe` "c4bd2ab50000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f486570000000000000000000000000000000000000000000000000000000000000001e000000000000000000000000000000000000000000000000000000000000001000000000000000000000000009858effd232b4033e47d90003d41ec34ecaeda940000000000000000000000000000000000000000000000000000000003c2670011111111111111111111111111111111111111111111111111111111111111110000000000000000000000002279b7a0a67db372996a5fab50d91eaa73d2ebe6000000000000000000000000000000000000000000000000000000000000014000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000762616b6572793100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000411d0b3a477c99fbcadada2937b71127bf6da202f5cd25856649829653d8cf6a8c0ce0afb8505e398e23b3b01fcb3b17ffcf82d8ba6d24e9b854506894b2864ecf1c00000000000000000000000000000000000000000000000000000000000000"
testCommitCalldata :: IO ()
testCommitCalldata =
toHex (commitCalldata $ makeCommitment knownRegistration) `shouldBe` "f14fcbc843aeb4617085160f4dc7ad495d1119f39bca441276b1990123fd3ecb8a40a360"
toHex (commitCalldata $ makeCommitment knownRegistration) `shouldBe` "f14fcbc8810f0645b8d9839e3744bb956f9da4fa12bb51ec97459e08739c576a36cba0df"
testVerifyOtherSigner :: TVar ChaChaDRG -> IO ()
testVerifyOtherSigner g = do
@@ -73,23 +72,41 @@ testVerifyShortSecret g = do
testRevertedDryRun :: TVar ChaChaDRG -> IO ()
testRevertedDryRun g = withFakeEthNode $ \node -> do
revertCalls node
-- viem's encodeErrorResult of InsufficientAllowance(10000, 2500)
setFault node "eth_estimateGas" $ revertFault $ fromHex "2a1b2dd8000000000000000000000000000000000000000000000000000000000000271000000000000000000000000000000000000000000000000000000000000009c4"
intent <- knownIntent g knownRegistration
sendRegister g (chainClient node) intent `shouldReturn` Left (ChainError "execution reverted")
sentTransactions node `shouldReturn` []
c <- newChainClient g $ fakeChainConfig node
estimateGas c fakeSponsor (registerWithCreditCalldata intent) `shouldReturn` Left (ChainReverted $ Just RNInsufficientAllowance)
testCommitThenRegister :: TVar ChaChaDRG -> IO ()
testCommitThenRegister g = withFakeEthNode $ \node -> do
c <- newChainClient g $ fakeChainConfig node
w <- newEphemeralWallet g
ewAddress <$> walletFromCode g (redemptionCode w) `shouldReturn` ewAddress w
let registration = knownRegistration {rOwner = ewAddress w}
commitment = makeCommitment registration
commitTx <- expectedTransaction g 0 controller $ commitCalldata commitment
sendCommit g (chainClient node) commitment `shouldReturn` Right (TxHash $ C.keccak256 commitTx)
commitCall = commitCalldata $ makeCommitment registration
commitTx <- expectedTransaction g 0 fakeController commitCall
send g c fakeController commitCall `shouldReturn` SignedTx commitTx (TxHash $ C.keccak256 commitTx)
intent <- signRegisterIntent g domain w registration deadline
verifyRegisterIntent domain deadline intent `shouldReturn` Right ()
registerTx <- expectedTransaction g 1 sponsor $ registerWithCreditCalldata intent
sendRegister g (chainClient node) intent `shouldReturn` Right (TxHash $ C.keccak256 registerTx)
let registerCall = registerWithCreditCalldata intent
registerTx <- expectedTransaction g 1 fakeSponsor registerCall
send g c fakeSponsor registerCall `shouldReturn` SignedTx registerTx (TxHash $ C.keccak256 registerTx)
sentTransactions node `shouldReturn` [commitTx, registerTx]
-- | The dry run, the registrar's next nonce and the fees, then the signed transaction sent and its hash checked.
send :: TVar ChaChaDRG -> ChainClient -> Address -> ByteString -> IO SignedTx
send g c@ChainClient {ccRegistrar} to calldata = do
gas <- right' =<< estimateGas c to calldata
nonce <- right' =<< transactionCount c ccRegistrar Pending
tip <- right' =<< maxPriorityFee c
Block {blockBaseFee} <- right' =<< latestBlock c
tx@SignedTx {stRaw, stHash} <-
right <$> signTransaction g c TxRequest {trTo = to, trData = calldata, trNonce = nonce, trGasLimit = gas, trMaxFeePerGas = 2 * blockBaseFee + tip, trMaxPriorityFeePerGas = tip}
sendRawTransaction c stRaw `shouldReturn` Right stHash
pure tx
where
right' = either (fail . show) pure
-- fixtures
@@ -102,8 +119,8 @@ knownRegistration =
rDuration = 63072000,
rSecret = B.replicate 32 0x11,
rResolver = address "0x2279b7a0a67db372996a5fab50d91eaa73d2ebe6",
rContactLinks = ["https://smp.simplex.im/a#contact"],
rChannelLinks = ["https://smp1.simplex.im/c#one", "https://smp2.simplex.im/c#two"]
rContactLink = Just "https://smp.simplex.im/a#contact",
rChannelLink = Just "https://smp1.simplex.im/c#one"
}
knownIntent :: TVar ChaChaDRG -> Registration -> IO RegisterIntent
@@ -114,34 +131,20 @@ knownIntent g r = do
knownCode :: Text
knownCode = "SN-00000-00000-00000-00000-00000-0VME2"
controller, sponsor :: Address
controller = address "0x0165878a594ca255338adfa4d48449f69242eb8f"
sponsor = address "0x9a676e781a523b5d0c0e43731313a708cb607508"
domain :: Eip712Domain
domain = sponsorDomain chainId sponsor
chainId :: Word64
chainId = 31337
domain = sponsorDomain fakeChainId fakeSponsor
deadline :: Word64
deadline = 4102444800
registrarKey :: S.Secp256k1PrivateKey
registrarKey = right $ S.mkPrivateKey $ BA.replicate 32 0x46
chainClient :: FakeEthNode -> ChainClient
chainClient FakeEthNode {fnUrl, fnManager} =
ChainClient {ccManager = fnManager, ccRpcUrl = fnUrl, ccChainId = chainId, ccController = controller, ccSponsor = sponsor, ccRegistrarKey = registrarKey}
expectedTransaction :: TVar ChaChaDRG -> Word64 -> Address -> ByteString -> IO ByteString
expectedTransaction g nonce to calldata =
right
<$> signEip1559Tx
g
registrarKey
fakeRegistrarKey
Eip1559Tx
{ txChainId = chainId,
{ txChainId = fakeChainId,
txNonce = nonce,
txMaxPriorityFeePerGas = fakeTip,
txMaxFeePerGas = 2 * fakeBaseFee + fakeTip,
@@ -157,5 +160,8 @@ address = right . strDecode
toHex :: ByteString -> ByteString
toHex = convertToBase Base16
fromHex :: ByteString -> ByteString
fromHex = right . convertFromBase Base16
right :: Either String a -> a
right = either (error . ("unexpected Left: " <>)) id
+292
View File
@@ -0,0 +1,292 @@
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
module Bots.StoreService.NamesChainTests (namesChainTests) where
import Bots.StoreService.FakeEthNode
import Control.Concurrent.STM (TVar)
import Control.Exception (toException, try)
import Crypto.Random (ChaChaDRG)
import qualified Data.Aeson as J
import Data.ByteArray.Encoding (Base (Base16), convertFromBase)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.Text as T
import Data.Time.Clock (diffUTCTime, getCurrentTime)
import Data.Word (Word64)
import qualified Network.HTTP.Client as HTTP
import qualified Simplex.Messaging.Crypto as C
import StoreService.Config (ChainConfig (..))
import StoreService.Names.Abi (selector, uint256)
import StoreService.Names.Chain
import StoreService.Names.Revert
import Test.Hspec
namesChainTests :: Spec
namesChainTests = describe "StoreService names: chain" $ do
g <- runIO C.newRandom
describe "reverts" $ do
it "names every contract error by the selector viem encodes it with" testRevertSelectors
it "reads a dry run's revert with data by its name" $ testDryRunRevertNamed g
it "reads an eth_call revert with data by its name" $ testCallRevertNamed g
it "reads ownerOf of a name nobody holds as a revert" $ testOwnerOfRevert g
it "reads a bare revert message without data as a revert without data, and one with a reason as unknown" $ testRevertWithoutData g
it "reads a revert of an unknown error as an unnamed revert" $ testUnknownRevert g
describe "failures" $ do
it "reads an RPC error as unavailable, without the URL" $ testRpcError g
it "gives up on a node that does not answer within the call's timeout" $ testTimeout g
it "reads an HTTP failure as unavailable" $ testHttpFailure g
it "reads a refused connection as unavailable, without the URL" $ testRefused g
it "refuses an answer over the size bound" $ testOversized g
it "reads a 2xx answer that is not JSON as unavailable, without quoting it" $ testNotJson g
it "cuts a node's long error message" $ testLongNodeMessage g
it "refuses a quantity over 256 bits, and a long one within the call's timeout" $ testLongQuantity g
it "keeps an HTTP failure's detail for the log, with the URL's host, path and query redacted" testFailureDetail
describe "reads" $ do
it "answers eth_call from the node by contract and calldata" $ testEthCall g
it "reads the latest block's number, time and base fee" $ testLatestBlock g
it "follows a transaction from sent to mined with its receipt and the nonces" $ testFollowTransaction g
describe "transactions" $ do
it "signs a transaction whose hash is the node's keccak256 of the raw bytes" $ testSignedHash g
it "refuses a gas estimate above the cap" $ testGasCap g
-- | The custom errors of the four contracts' compiled ABIs, with viem's encodeErrorResult selectors.
viemSelectors :: [(ByteString, RevertName)]
viemSelectors =
[ ("5289653e", RNAlreadyFrozen),
("836588c9", RNCommitmentNotFound),
("74480cc9", RNCommitmentTooNew),
("256e2216", RNCommitmentTooOld),
("9a71997b", RNDurationTooShort),
("a8cab3d1", RNFrozen),
("2a1b2dd8", RNInsufficientAllowance),
("11011294", RNInsufficientValue),
("8d666f60", RNInvalidEVMAddress),
("756688fe", RNInvalidNonce),
("8baa579f", RNInvalidSignature),
("21134988", RNLabelTooLong),
("2d0c6794", RNMaxCommitmentAgeTooHigh),
("3e5aa838", RNMaxCommitmentAgeTooLow),
("ace8f2ce", RNMinCharLengthCanOnlyDecrease),
("ce47b48d", RNMinCharLengthZero),
("6357b884", RNMinCommitmentAgeZero),
("477707e8", RNNameNotAvailable),
("d17ee357", RNNameNotReserved),
("e1bf11bf", RNNameReserved),
("c4295eb6", RNNameTooShort),
("70f8a4c9", RNNftGateCanOnlyBeDisabled),
("6b1578c1", RNNftRequired),
("c30734cc", RNNodeNotOwnedByRegistrar),
("644d871f", RNNotBeneficiary),
("42f058b4", RNNotNameOwner),
("ff43b88f", RNNotOffered),
("4632a8bf", RNNotOwnerOrBeneficiary),
("df4795c7", RNNotSponsor),
("9a0aeacd", RNNotSubnameRegistrar),
("8a3c1cfb", RNOffsetOutOfBoundsError),
("a9efcc18", RNOwnerMustBeCaller),
("40866499", RNPublicSalesClosed),
("bc7fd331", RNReasonRequired),
("2bea818f", RNRecipientMustBeCaller),
("37ed32e8", RNReentrantCall),
("d3f605c4", RNResolverRequiredWhenDataSupplied),
("27af646c", RNReverseRecordNotSupported),
("0819bdcd", RNSignatureExpired),
("90b8ec18", RNTransferFailed),
("bf2f44f5", RNTransferToSelf),
("0a059d71", RNUnexpiredCommitmentExists),
("d92e233d", RNZeroAddress)
]
testRevertSelectors :: IO ()
testRevertSelectors = do
map snd viemSelectors `shouldBe` filter (/= RNWithoutData) [minBound .. maxBound]
[(n, decodeRevert $ unhex sel <> uint256 (0 :: Int)) | (sel, n) <- viemSelectors] `shouldBe` [(n, Just n) | (_, n) <- viemSelectors]
decodeRevert (B.take 3 $ unhex "74480cc9") `shouldBe` Nothing
decodeRevert "" `shouldBe` Just RNWithoutData
testDryRunRevertNamed :: TVar ChaChaDRG -> IO ()
testDryRunRevertNamed g = withChain g $ \node c -> do
setFault node "eth_estimateGas" $ revertFault insufficientAllowance
estimateGas c fakeSponsor "\x01\x02\x03\x04" `shouldReturn` Left (ChainReverted $ Just RNInsufficientAllowance)
sentTransactions node `shouldReturn` []
testCallRevertNamed :: TVar ChaChaDRG -> IO ()
testCallRevertNamed g = withChain g $ \node c -> do
answerCall node fakeController availableCall $ Reverts nameNotAvailable
ethCall c fakeController availableCall `shouldReturn` Left (ChainReverted $ Just RNNameNotAvailable)
testOwnerOfRevert :: TVar ChaChaDRG -> IO ()
testOwnerOfRevert g = withChain g $ \node c@ChainClient {ccConfig = ChainConfig {cBaseRegistrar}} -> do
let ownerOf = selector "ownerOf(uint256)" <> C.keccak256 "bakery1"
answerCall node cBaseRegistrar ownerOf $ Reverts ""
ethCall c cBaseRegistrar ownerOf `shouldReturn` Left (ChainReverted $ Just RNWithoutData)
testRevertWithoutData :: TVar ChaChaDRG -> IO ()
testRevertWithoutData g = withChain g $ \node c -> do
setFault node "eth_call" $ RpcError (-32000) "execution reverted" Nothing
ethCall c fakeController availableCall `shouldReturn` Left (ChainReverted $ Just RNWithoutData)
-- a reason kept in the message names a revert that had data, so it is not read as one without
setFault node "eth_call" $ RpcError 3 "execution reverted: ERC721: invalid token ID" Nothing
ethCall c fakeController availableCall `shouldReturn` Left (ChainReverted Nothing)
testUnknownRevert :: TVar ChaChaDRG -> IO ()
testUnknownRevert g = withChain g $ \node c -> do
-- viem's encodeErrorResult of Error("ERC721: invalid token ID"), not one of the contracts' own errors
setFault node "eth_call" $ revertFault $ unhex "08c379a0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000184552433732313a20696e76616c696420746f6b656e2049440000000000000000"
ethCall c fakeController availableCall `shouldReturn` Left (ChainReverted Nothing)
testRpcError :: TVar ChaChaDRG -> IO ()
testRpcError g = withChain g $ \node c -> do
setFault node "eth_call" $ RpcError (-32000) "header not found" Nothing
r <- ethCall c fakeController availableCall
r `shouldBe` Left (ChainUnavailable "eth_call: error -32000: header not found")
r `shouldNotSatisfy` mentionsUrl c
testTimeout :: TVar ChaChaDRG -> IO ()
testTimeout g = withChain g $ \node c -> do
ccTimeout c `shouldBe` 10000000
setFault node "eth_getBlockByNumber" Hang
let short = c {ccTimeout = 300000}
start <- getCurrentTime
r <- latestBlock short
elapsed <- (`diffUTCTime` start) <$> getCurrentTime
r `shouldBe` Left (ChainUnavailable "eth_getBlockByNumber: timed out")
elapsed `shouldSatisfy` (< 2)
testHttpFailure :: TVar ChaChaDRG -> IO ()
testHttpFailure g = withChain g $ \node c -> do
setFault node "eth_maxPriorityFeePerGas" HttpFailure
maxPriorityFee c `shouldReturn` Left (ChainUnavailable "eth_maxPriorityFeePerGas: HTTP 502")
testRefused :: TVar ChaChaDRG -> IO ()
testRefused g = withFakeEthNode $ \node -> do
-- port 1 is privileged and nothing listens on it in the test container
c <- newChainClient g (fakeChainConfig node) {cRpcUrl = "http://127.0.0.1:1" <> secretPath}
r <- latestBlock c
r `shouldBe` Left (ChainUnavailable "eth_getBlockByNumber: connection failed")
r `shouldNotSatisfy` mentionsUrl c
testOversized :: TVar ChaChaDRG -> IO ()
testOversized g = withChain g $ \node c -> do
answerCall node fakeController availableCall $ Returns $ B.replicate (512 * 1024) 0
ethCall c fakeController availableCall `shouldReturn` Left (ChainUnavailable "eth_call: response over 1048576 bytes")
testNotJson :: TVar ChaChaDRG -> IO ()
testNotJson g = withChain g $ \node c -> do
setFault node "eth_call" NotJson
ethCall c fakeController availableCall `shouldReturn` Left (ChainUnavailable "eth_call: not a JSON-RPC response")
testLongNodeMessage :: TVar ChaChaDRG -> IO ()
testLongNodeMessage g = withChain g $ \node c -> do
setFault node "eth_call" $ RpcError (-32000) (T.replicate 1000 "x") Nothing
ethCall c fakeController availableCall `shouldReturn` Left (ChainUnavailable $ "eth_call: error -32000: " <> T.replicate 200 "x")
testLongQuantity :: TVar ChaChaDRG -> IO ()
testLongQuantity g = withChain g $ \node c -> do
let fee digits = setFault node "eth_maxPriorityFeePerGas" (Answers $ J.String $ "0x" <> digits) >> maxPriorityFee c {ccTimeout = 300000}
notQuantity = Left (ChainUnavailable "eth_maxPriorityFeePerGas: not a JSON-RPC response: Error in $: not a quantity")
fee (T.replicate 63 "0" <> "7") `shouldReturn` Right 7
fee (T.replicate 64 "0" <> "7") `shouldReturn` notQuantity
start <- getCurrentTime
fee (T.replicate 1000000 "f") `shouldReturn` notQuantity
elapsed <- (`diffUTCTime` start) <$> getCurrentTime
elapsed `shouldSatisfy` (< 1)
testFailureDetail :: IO ()
testFailureDetail = do
let url = "https://provider.example/v2/provider-api-key?key=abc"
req <- HTTP.parseRequest url
let detail = httpFailureDetail url . HTTP.HttpExceptionRequest req
redacted t = (t, filter (`T.isInfixOf` t) ["provider.example", "provider-api-key", "key=abc"]) `shouldBe` (t, [])
redacted $ detail $ HTTP.InvalidDestinationHost "provider.example"
redacted $ detail $ HTTP.ConnectionFailure $ toException $ userError $ "connect to " <> url
redacted $ httpFailureDetail url $ HTTP.InvalidUrlException url "Invalid URL"
manager <- HTTP.newManager HTTP.defaultManagerSettings
-- port 1 is privileged and nothing listens on it in the test container
let refusedUrl = "http://127.0.0.1:1" <> secretPath
refused <- try $ HTTP.parseRequest refusedUrl >>= (`HTTP.httpLbs` manager)
case refused of
Left e -> httpFailureDetail refusedUrl e `shouldSatisfy` ("ConnectionFailure" `T.isPrefixOf`)
Right _ -> expectationFailure "connected to port 1"
testEthCall :: TVar ChaChaDRG -> IO ()
testEthCall g = withChain g $ \node c -> do
answerCall node fakeController availableCall $ Returns $ uint256 (1 :: Int)
answerCall node fakeSponsor availableCall $ Returns $ uint256 (0 :: Int)
ethCall c fakeController availableCall `shouldReturn` Right (uint256 (1 :: Int))
ethCall c fakeSponsor availableCall `shouldReturn` Right (uint256 (0 :: Int))
ethCall c fakeController (selector "available(string)") `shouldReturn` Left (ChainUnavailable "eth_call: error -32000: no fake answer for this call")
testLatestBlock :: TVar ChaChaDRG -> IO ()
testLatestBlock g = withChain g $ \node c -> do
setBlock node 21000000 1798761600
latestBlock c `shouldReturn` Right Block {blockNumber = 21000000, blockTimestamp = 1798761600, blockBaseFee = fakeBaseFee}
testFollowTransaction :: TVar ChaChaDRG -> IO ()
testFollowTransaction g = withChain g $ \node c@ChainClient {ccRegistrar} -> do
let unknown = TxHash $ B.replicate 32 0xee
transactionByHash c unknown `shouldReturn` Right Nothing
transactionReceipt c unknown `shouldReturn` Right Nothing
SignedTx {stRaw, stHash = hash@(TxHash h)} <- signed g c 0
sendRawTransaction c stRaw `shouldReturn` Right hash
transactionByHash c hash `shouldReturn` Right (Just TxPending)
transactionReceipt c hash `shouldReturn` Right Nothing
transactionCount c ccRegistrar Latest `shouldReturn` Right 0
transactionCount c ccRegistrar Pending `shouldReturn` Right 1
block <- mine node [(h, False)]
transactionByHash c hash `shouldReturn` Right (Just $ TxMined block)
transactionReceipt c hash `shouldReturn` Right (Just Receipt {receiptSuccess = False, receiptBlock = block})
transactionCount c ccRegistrar Latest `shouldReturn` Right 1
testSignedHash :: TVar ChaChaDRG -> IO ()
testSignedHash g = withChain g $ \node c -> do
SignedTx {stRaw, stHash} <- signed g c 7
stHash `shouldBe` TxHash (C.keccak256 stRaw)
sendRawTransaction c stRaw `shouldReturn` Right stHash
sentTransactions node `shouldReturn` [stRaw]
testGasCap :: TVar ChaChaDRG -> IO ()
testGasCap g = withFakeEthNode $ \node -> do
let config = fakeChainConfig node
atCap <- newChainClient g config {cGasLimitCap = fakeGas}
estimateGas atCap fakeController availableCall `shouldReturn` Right fakeGas
belowCap <- newChainClient g config {cGasLimitCap = fakeGas - 1}
estimateGas belowCap fakeController availableCall `shouldReturn` Left (ChainGasAboveCap fakeGas)
-- fixtures
withChain :: TVar ChaChaDRG -> (FakeEthNode -> ChainClient -> IO a) -> IO a
withChain g action = withFakeEthNode $ \node -> do
c <- newChainClient g (fakeChainConfig node) {cRpcUrl = fnUrl node <> secretPath}
action node c
-- | Where a provider puts its API key.
secretPath :: String
secretPath = "/v2/provider-api-key"
mentionsUrl :: ChainClient -> Either ChainError a -> Bool
mentionsUrl ChainClient {ccConfig = ChainConfig {cRpcUrl}} = \case
Left (ChainUnavailable t) -> any (`T.isInfixOf` t) [T.pack cRpcUrl, T.pack secretPath, "127.0.0.1"]
_ -> False
signed :: TVar ChaChaDRG -> ChainClient -> Word64 -> IO SignedTx
signed g c nonce =
either error id
<$> signTransaction g c TxRequest {trTo = fakeController, trData = availableCall, trNonce = nonce, trGasLimit = fakeGas, trMaxFeePerGas = 2 * fakeBaseFee + fakeTip, trMaxPriorityFeePerGas = fakeTip}
-- | controller.available("bakery1"), viem's encodeFunctionData
availableCall :: ByteString
availableCall = unhex "aeb8ce9b0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000762616b6572793100000000000000000000000000000000000000000000000000"
-- | viem's encodeErrorResult of InsufficientAllowance(10000, 2500)
insufficientAllowance :: ByteString
insufficientAllowance = unhex "2a1b2dd8000000000000000000000000000000000000000000000000000000000000271000000000000000000000000000000000000000000000000000000000000009c4"
-- | viem's encodeErrorResult of NameNotAvailable("bakery1")
nameNotAvailable :: ByteString
nameNotAvailable = unhex "477707e80000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000762616b6572793100000000000000000000000000000000000000000000000000"
unhex :: ByteString -> ByteString
unhex = either error id . convertFromBase Base16
@@ -0,0 +1,376 @@
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
module Bots.StoreService.NamesContractsTests
( namesContractsTests,
withContracts,
answerRegistrar,
answerRegistered,
registrarOf,
resolverOf,
rentPriceCall,
rentPriceAnswer,
now,
year,
gracePeriod,
otherResolver,
nameExpiresCall,
reservedNamesCall,
contactTextCall,
channelTextCall,
noncesCall,
alice,
availableCall,
minCommitmentAgeCall,
maxCommitmentAgeCall,
unhex,
)
where
import Bots.StoreService.FakeEthNode
import Control.Concurrent.STM (TVar)
import Control.Monad (forM_)
import Crypto.Random (ChaChaDRG)
import Data.ByteArray.Encoding (Base (Base16), convertFromBase)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.Time.Clock (NominalDiffTime, diffUTCTime, getCurrentTime)
import Data.Word (Word64)
import qualified Simplex.Messaging.Crypto as C
import Simplex.Messaging.Encoding.String (strDecode)
import Simplex.Messaging.Eth.Address (Address)
import Simplex.Messaging.SimplexName (LabelHash, SimplexTLD (..), labelHash)
import StoreService.Config (ChainConfig (..))
import StoreService.Names.Abi
import StoreService.Names.Chain
import StoreService.Names.Contracts
import StoreService.Names.Registration (labelNode, namehash, nodeBytes)
import StoreService.Names.Revert (RevertName (..))
import Test.Hspec
namesContractsTests :: Spec
namesContractsTests = describe "StoreService names: contracts" $ do
-- the calldata and answers marked viem are viem 2.33.3's encodeFunctionData and encodeFunctionResult
-- with the ABIs of ens-contracts PR #36, so a read the fake node answers sends viem's calldata
g <- runIO C.newRandom
it "builds a name's node from its label hash as viem's namehash" testNode
describe "status" $ do
it "reads a name nobody holds or reserved as available" $ testAvailable g
it "reads a reserved name" $ testReserved g
it "reads a registered name with the registry's owner and resolver" $ testRegistered g
it "keeps a name registered to the last second of its grace period" $ testGracePeriod g
it "reads the registry and the grace period once, and again after a failed read" $ testRegistrarOnce g
describe "records" $ do
it "reads the default resolver's records and the owner's nonce" $ testRecords g
it "reads no records from another resolver" $ testOtherResolver g
describe "prices" $ do
it "quotes 6, 7 and 12 letters at the launch list for 2 years" $ testLaunchPrices g
describe "other reads" $ do
it "reads the sponsor's and the resolver's nonces from their own contracts" $ testNonces g
it "reads ownerOf's revert without data as nobody" $ testOwnerOfNobody g
it "reads any other ownerOf revert or failure as a failed read" $ testOwnerOfFailed g
it "reads a commitment's time, none as Nothing" $ testCommitmentTime g
it "reads the controller's availability and the name's expiry" $ testAvailability g
it "reads the commitment ages once" $ testCommitmentAges g
describe "failures" $ do
it "fails a status on a failed read, never reading it as available" $ testFailedRead g
it "fails a read whose answer does not decode or does not fit" $ testMalformed g
it "fails a status within its deadline when one method hangs" $ testStatusDeadline g
it "fails records within their deadline when the calls hang" $ testRecordsDeadline g
it "reads a status and records within a deadline only concurrent reads meet" $ testConcurrentReads g
testNode :: IO ()
testNode = do
nodeBytes (labelNode TLDSimplex $ labelHash "alicebakery") `shouldBe` aliceNode
nodeBytes (namehash TLDSimplex "alicebakery") `shouldBe` aliceNode
testAvailable :: TVar ChaChaDRG -> IO ()
testAvailable g = withContracts g $ \node ct -> do
answerRegistrar node
setBlock node 100 now
answerCall node (registrarOf node) nameExpiresCall $ Returns $ uint256 (0 :: Int)
answerCall node fakeController reservedNamesCall $ Returns $ uint256 (0 :: Int)
nameStatus ct alice `shouldReturn` Right NSAvailable
testReserved :: TVar ChaChaDRG -> IO ()
testReserved g = withContracts g $ \node ct -> do
answerRegistrar node
setBlock node 100 now
answerCall node (registrarOf node) nameExpiresCall $ Returns $ uint256 (0 :: Int)
-- viem: reservedNames answering Reason 1
answerCall node fakeController reservedNamesCall $ Returns $ unhex "0000000000000000000000000000000000000000000000000000000000000001"
nameStatus ct alice `shouldReturn` Right NSReserved
testRegistered :: TVar ChaChaDRG -> IO ()
testRegistered g = withContracts g $ \node ct -> do
answerRegistrar node
answerRegistered node (resolverOf node)
setBlock node 100 now
answerCall node (registrarOf node) nameExpiresCall $ Returns $ uint256 (now + year)
nameStatus ct alice `shouldReturn` Right (NSRegistered $ registeredAlice (resolverOf node) (now + year))
testGracePeriod :: TVar ChaChaDRG -> IO ()
testGracePeriod g = withContracts g $ \node ct -> do
answerRegistrar node
answerRegistered node (resolverOf node)
answerCall node fakeController reservedNamesCall $ Returns $ uint256 (0 :: Int)
let expired = now - year
answerCall node (registrarOf node) nameExpiresCall $ Returns $ uint256 expired
setBlock node 100 $ expired + gracePeriod
nameStatus ct alice `shouldReturn` Right (NSRegistered $ registeredAlice (resolverOf node) expired)
setBlock node 101 $ expired + gracePeriod + 1
nameStatus ct alice `shouldReturn` Right NSAvailable
testRegistrarOnce :: TVar ChaChaDRG -> IO ()
testRegistrarOnce g = withContracts g $ \node ct -> do
setBlock node 100 now
answerCall node (registrarOf node) nameExpiresCall $ Returns $ uint256 (0 :: Int)
answerCall node fakeController reservedNamesCall $ Returns $ uint256 (0 :: Int)
nameStatus ct alice `shouldReturn` Left (ChainUnavailable "eth_call: error -32000: no fake answer for this call")
answerRegistrar node
nameStatus ct alice `shouldReturn` Right NSAvailable
answerCall node (registrarOf node) ensCall $ Reverts ""
answerCall node (registrarOf node) gracePeriodCall $ Reverts ""
nameStatus ct alice `shouldReturn` Right NSAvailable
testRecords :: TVar ChaChaDRG -> IO ()
testRecords g = withContracts g $ \node ct -> do
let resolver = resolverOf node
answerCall node resolver contactTextCall $ Returns contactTextAnswer
-- an unset record is the empty string
answerCall node resolver channelTextCall $ Returns $ abiTuple [Dynamic $ abiBytes ""]
answerCall node resolver noncesCall $ Returns $ uint256 (3 :: Int)
nameRecords ct alice (registeredAlice resolver $ now + year)
`shouldReturn` Right (Just NameRecords {rdContact = "https://smp8.simplex.im/a#Y8m3", rdChannel = "", rdNonce = 3})
textRecord ct alice "simplex.contact" `shouldReturn` Right "https://smp8.simplex.im/a#Y8m3"
testOtherResolver :: TVar ChaChaDRG -> IO ()
testOtherResolver g = withContracts g $ \_ ct -> do
nameRecords ct alice (registeredAlice otherResolver $ now + year) `shouldReturn` Right Nothing
testLaunchPrices :: TVar ChaChaDRG -> IO ()
testLaunchPrices g = withContracts g $ \node ct -> do
-- viem: rentPriceUSD answering {base: 40000 * 10^16, premium: 0}
answerCall node fakeController (rentPriceCall 6) $ Returns $ unhex "000000000000000000000000000000000000000000000015af1d78b58c4000000000000000000000000000000000000000000000000000000000000000000000"
answerCall node fakeController (rentPriceCall 7) $ Returns $ rentPriceAnswer 20000
answerCall node fakeController (rentPriceCall 12) $ Returns $ rentPriceAnswer 10000
mapM (\len -> chainPriceCents ct len 2) [6, 7, 12] `shouldReturn` [Right 40000, Right 20000, Right 10000]
testNonces :: TVar ChaChaDRG -> IO ()
testNonces g = withContracts g $ \node ct -> do
answerCall node fakeSponsor noncesCall $ Returns $ uint256 (5 :: Int)
answerCall node (resolverOf node) noncesCall $ Returns $ uint256 (3 :: Int)
sponsorNonce ct owner `shouldReturn` Right 5
resolverNonce ct owner `shouldReturn` Right 3
testOwnerOfNobody :: TVar ChaChaDRG -> IO ()
testOwnerOfNobody g = withContracts g $ \node ct -> do
answerCall node (registrarOf node) ownerOfCall $ Returns $ addressWord owner
ownerOfToken ct Latest alice `shouldReturn` Right (Just owner)
-- the registrar's require(expiries[tokenId] > block.timestamp), as anvil answers it with "0x" and reth without data
answerCall node (registrarOf node) ownerOfCall $ Reverts ""
ownerOfToken ct Latest alice `shouldReturn` Right Nothing
setFault node "eth_call" $ RpcError 3 "execution reverted" Nothing
ownerOfToken ct Latest alice `shouldReturn` Right Nothing
testOwnerOfFailed :: TVar ChaChaDRG -> IO ()
testOwnerOfFailed g = withContracts g $ \node ct -> do
-- viem's encodeErrorResult of Error("ERC721: invalid token ID")
answerCall node (registrarOf node) ownerOfCall $ Reverts $ unhex "08c379a0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000184552433732313a20696e76616c696420746f6b656e2049440000000000000000"
ownerOfToken ct Latest alice `shouldReturn` Left (ChainReverted Nothing)
-- viem's encodeErrorResult of ReentrantCall()
answerCall node (registrarOf node) ownerOfCall $ Reverts $ unhex "37ed32e8"
ownerOfToken ct Latest alice `shouldReturn` Left (ChainReverted $ Just RNReentrantCall)
-- a node or proxy that keeps the reason in the message but drops the data
setFault node "eth_call" $ RpcError (-32000) "execution reverted: ERC721: invalid token ID" Nothing
ownerOfToken ct Latest alice `shouldReturn` Left (ChainReverted Nothing)
setFault node "eth_call" HttpFailure
ownerOfToken ct Latest alice `shouldReturn` Left (ChainUnavailable "eth_call: HTTP 502")
testCommitmentTime :: TVar ChaChaDRG -> IO ()
testCommitmentTime g = withContracts g $ \node ct -> do
answerCall node fakeController commitmentsCall $ Returns $ uint256 (0 :: Int)
commitmentTime ct commitment `shouldReturn` Right Nothing
answerCall node fakeController commitmentsCall $ Returns $ uint256 now
commitmentTime ct commitment `shouldReturn` Right (Just now)
testAvailability :: TVar ChaChaDRG -> IO ()
testAvailability g = withContracts g $ \node ct -> do
answerCall node fakeController availableCall $ Returns $ uint256 (1 :: Int)
controllerAvailable ct "alicebakery" `shouldReturn` Right True
answerCall node fakeController availableCall $ Returns $ uint256 (0 :: Int)
controllerAvailable ct "alicebakery" `shouldReturn` Right False
answerCall node (registrarOf node) nameExpiresCall $ Returns $ uint256 (now + year)
nameExpires ct Latest alice `shouldReturn` Right (now + year)
testCommitmentAges :: TVar ChaChaDRG -> IO ()
testCommitmentAges g = withContracts g $ \node ct -> do
answerCall node fakeController minCommitmentAgeCall $ Returns $ uint256 (60 :: Int)
answerCall node fakeController maxCommitmentAgeCall $ Returns $ uint256 (86400 :: Int)
commitmentAges ct `shouldReturn` Right CommitmentAges {caMin = 60, caMax = 86400}
answerCall node fakeController maxCommitmentAgeCall $ Returns $ uint256 (3600 :: Int)
commitmentAges ct `shouldReturn` Right CommitmentAges {caMin = 60, caMax = 86400}
testFailedRead :: TVar ChaChaDRG -> IO ()
testFailedRead g = withContracts g $ \node ct -> do
answerRegistrar node
setBlock node 100 now
answerCall node fakeController reservedNamesCall $ Returns $ uint256 (0 :: Int)
answerCall node (registrarOf node) nameExpiresCall $ Reverts ""
nameStatus ct alice `shouldReturn` Left (ChainReverted $ Just RNWithoutData)
answerCall node (registrarOf node) nameExpiresCall $ Returns $ uint256 (0 :: Int)
setFault node "eth_getBlockByNumber" HttpFailure
nameStatus ct alice `shouldReturn` Left (ChainUnavailable "eth_getBlockByNumber: HTTP 502")
clearFault node "eth_getBlockByNumber"
answerCall node fakeController reservedNamesCall $ Reverts ""
nameStatus ct alice `shouldReturn` Left (ChainReverted $ Just RNWithoutData)
testMalformed :: TVar ChaChaDRG -> IO ()
testMalformed g = withContracts g $ \node ct -> do
answerCall node (registrarOf node) nameExpiresCall $ Returns $ B.replicate 31 0
nameExpires ct Latest alice `shouldReturn` Left (ChainUnavailable "eth_call: nameExpires(uint256) answered AEShort")
answerCall node fakeSponsor noncesCall $ Returns $ uint256 (toInteger (maxBound :: Word64) + 1)
sponsorNonce ct owner `shouldReturn` Left (ChainUnavailable "eth_call: nonces(address) answered AERange")
testStatusDeadline :: TVar ChaChaDRG -> IO ()
testStatusDeadline g = withContracts g $ \node ct -> do
answerRegistrar node
answerCall node (registrarOf node) nameExpiresCall $ Returns $ uint256 (0 :: Int)
answerCall node fakeController reservedNamesCall $ Returns $ uint256 (0 :: Int)
setFault node "eth_getBlockByNumber" Hang
elapsed <- timed $ nameStatus ct {ctDeadline = testDeadline} alice `shouldReturn` Left (ChainUnavailable "name status: timed out")
elapsed `shouldSatisfy` (< 2)
clearFault node "eth_getBlockByNumber"
nameStatus ct {ctDeadline = testDeadline} alice `shouldReturn` Right NSAvailable
testRecordsDeadline :: TVar ChaChaDRG -> IO ()
testRecordsDeadline g = withContracts g $ \node ct -> do
setFault node "eth_call" Hang
elapsed <- timed $ nameRecords ct {ctDeadline = testDeadline} alice (registeredAlice (resolverOf node) $ now + year) `shouldReturn` Left (ChainUnavailable "name records: timed out")
elapsed `shouldSatisfy` (< 2)
-- | Each slow read takes a third of the deadline or more, so the status's reads in sequence (four) or the records' (three)
-- pass it, while their concurrent rounds (two and one) meet it.
testConcurrentReads :: TVar ChaChaDRG -> IO ()
testConcurrentReads g = withContracts g $ \node ct -> do
let resolver = resolverOf node
ct' = ct {ctDeadline = concurrentDeadline}
registered = registeredAlice resolver (now + year)
answerRegistrar node
answerRegistered node resolver
setBlock node 100 now
answerCall node (registrarOf node) nameExpiresCall $ Returns $ uint256 (now + year)
answerCall node resolver contactTextCall $ Returns contactTextAnswer
answerCall node resolver channelTextCall $ Returns $ abiTuple [Dynamic $ abiBytes ""]
answerCall node resolver noncesCall $ Returns $ uint256 (3 :: Int)
-- the registrar's constants are read once, so this read takes them out of the timed ones
nameStatus ct alice `shouldReturn` Right (NSRegistered registered)
forM_ ["eth_call", "eth_getBlockByNumber"] $ \m -> setFault node m $ Slow $ concurrentDeadline * 2 `div` 5
nameStatus ct' alice `shouldReturn` Right (NSRegistered registered)
forM_ ["eth_call", "eth_getBlockByNumber"] $ \m -> setFault node m $ Slow $ concurrentDeadline * 3 `div` 5
nameRecords ct' alice registered `shouldReturn` Right (Just NameRecords {rdContact = "https://smp8.simplex.im/a#Y8m3", rdChannel = "", rdNonce = 3})
-- fixtures
concurrentDeadline :: Int
concurrentDeadline = 1500000
-- | Far below a call's 10-second timeout, so only the deadline can end a hung read in time.
testDeadline :: Int
testDeadline = 300000
timed :: IO () -> IO NominalDiffTime
timed action = do
start <- getCurrentTime
action
(`diffUTCTime` start) <$> getCurrentTime
withContracts :: TVar ChaChaDRG -> (FakeEthNode -> Contracts -> IO a) -> IO a
withContracts g action = withFakeEthNode $ \node -> do
ct <- newContracts TLDSimplex =<< newChainClient g (fakeChainConfig node)
action node ct
answerRegistrar :: FakeEthNode -> IO ()
answerRegistrar node = do
answerCall node (registrarOf node) ensCall $ Returns $ addressWord registry
answerCall node (registrarOf node) gracePeriodCall $ Returns $ uint256 gracePeriod
answerRegistered :: FakeEthNode -> Address -> IO ()
answerRegistered node resolver = do
answerCall node registry registryOwnerCall $ Returns $ addressWord owner
answerCall node registry registryResolverCall $ Returns $ addressWord resolver
registeredAlice :: Address -> Word64 -> RegisteredName
registeredAlice rnResolver rnExpiresAt = RegisteredName {rnOwner = owner, rnResolver, rnExpiresAt, rnGracePeriod = toInteger gracePeriod}
registrarOf, resolverOf :: FakeEthNode -> Address
registrarOf = cBaseRegistrar . fakeChainConfig
resolverOf = cResolver . fakeChainConfig
rentPriceAnswer :: Integer -> ByteString
rentPriceAnswer cents = uint256 (cents * 10 ^ (16 :: Int)) <> uint256 (0 :: Int)
-- viem: text answering "https://smp8.simplex.im/a#Y8m3"
contactTextAnswer :: ByteString
contactTextAnswer = unhex "0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000001e68747470733a2f2f736d70382e73696d706c65782e696d2f612359386d330000"
-- 2027-01-01, the term start
now :: Word64
now = 1798761600
year, gracePeriod :: Word64
year = 31536000
gracePeriod = 7776000
alice :: LabelHash
alice = labelHash "alicebakery"
-- viem: namehash("alicebakery.simplex")
aliceNode :: ByteString
aliceNode = unhex "0f4104919a21c22f566d9c7947c7c7d8addbf546c973851a7e449276ea54ec1a"
commitment :: ByteString
commitment = unhex "f8096c3f3cfbadc9f3a108d2c586ccc816c0510711c8d6228aa4fa507324d30c"
owner, registry, otherResolver :: Address
owner = address "0x014f9c09cceedef1b713110d04d3a07d5b5d9b73"
registry = address "0x5fbdb2315678afecb367f032d93f642f64180aa3"
otherResolver = address "0x4826533b4897376654bb4d4ad88b7fafd0c98528"
-- viem's calldata for the reads
ensCall, gracePeriodCall, nameExpiresCall, ownerOfCall, reservedNamesCall, registryOwnerCall, registryResolverCall :: ByteString
ensCall = unhex "3f15457f"
gracePeriodCall = unhex "c1a287e2"
nameExpiresCall = unhex "d6e4fa86bcc46b7948ff6be55bc3ff4db5bc4be16638f29e818a89244dae11caaed7c9c6"
ownerOfCall = unhex "6352211ebcc46b7948ff6be55bc3ff4db5bc4be16638f29e818a89244dae11caaed7c9c6"
reservedNamesCall = unhex "389c0748bcc46b7948ff6be55bc3ff4db5bc4be16638f29e818a89244dae11caaed7c9c6"
registryOwnerCall = unhex "02571be30f4104919a21c22f566d9c7947c7c7d8addbf546c973851a7e449276ea54ec1a"
registryResolverCall = unhex "0178b8bf0f4104919a21c22f566d9c7947c7c7d8addbf546c973851a7e449276ea54ec1a"
contactTextCall, channelTextCall, noncesCall :: ByteString
contactTextCall = unhex "59d1d43c0f4104919a21c22f566d9c7947c7c7d8addbf546c973851a7e449276ea54ec1a0000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000f73696d706c65782e636f6e746163740000000000000000000000000000000000"
channelTextCall = unhex "59d1d43c0f4104919a21c22f566d9c7947c7c7d8addbf546c973851a7e449276ea54ec1a0000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000f73696d706c65782e6368616e6e656c0000000000000000000000000000000000"
noncesCall = unhex "7ecebe00000000000000000000000000014f9c09cceedef1b713110d04d3a07d5b5d9b73"
-- | rentPriceUSD("a" × length, 2 years)
rentPriceCall :: Int -> ByteString
rentPriceCall = \case
6 -> unhex "9ff7ec0900000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000003c2670000000000000000000000000000000000000000000000000000000000000000066161616161610000000000000000000000000000000000000000000000000000"
7 -> unhex "9ff7ec0900000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000003c2670000000000000000000000000000000000000000000000000000000000000000076161616161616100000000000000000000000000000000000000000000000000"
11 -> unhex "9ff7ec0900000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000003c26700000000000000000000000000000000000000000000000000000000000000000b6161616161616161616161000000000000000000000000000000000000000000"
12 -> unhex "9ff7ec0900000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000003c26700000000000000000000000000000000000000000000000000000000000000000c6161616161616161616161610000000000000000000000000000000000000000"
len -> error $ "no viem vector for length " <> show len
commitmentsCall, availableCall, minCommitmentAgeCall, maxCommitmentAgeCall :: ByteString
commitmentsCall = unhex "839df945f8096c3f3cfbadc9f3a108d2c586ccc816c0510711c8d6228aa4fa507324d30c"
availableCall = unhex "aeb8ce9b0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000b616c69636562616b657279000000000000000000000000000000000000000000"
minCommitmentAgeCall = unhex "8d839ffe"
maxCommitmentAgeCall = unhex "ce1e09c0"
unhex :: ByteString -> ByteString
unhex = either error id . convertFromBase Base16
address :: ByteString -> Address
address = either error id . strDecode
+5
View File
@@ -10,7 +10,9 @@ import Bots.StoreService.ConfigTests
import Bots.StoreService.GroupIntegrationTests
import Bots.StoreService.GroupTests
import Bots.StoreService.NameRegistrationTests
import Bots.StoreService.NamesChainTests
import Bots.StoreService.NamesCodesTests
import Bots.StoreService.NamesContractsTests
import Bots.StoreService.NamesLabelTests
import Bots.StoreService.StoreVerifierTests
import Bots.StoreService.StripeTests
@@ -90,7 +92,10 @@ main = do
badgeStripeTests
badgeNameRegistrationTests
badgeStoreVerifierTests
namesConfigTests
namesChainTests
namesCodesTests
namesContractsTests
namesLabelTests
describe "SimpleX chat markdown" markdownTests
describe "JSON Tests" jsonTests