Files
simplex-chat/tests/Bots/StoreService/FakeEthNode.hs
T
ad75fe706f store: sell and register SimpleX names (#7979)
* core: add prepaid name codes and length bounds

* store: run the names migration after badges

* store: issue and revoke prepaid name codes

* store: document issuing prepaid name codes

* store: move the ABI helpers to Names.Abi

* store: read the [names] and [chain] settings

* store: add the names chain client and reads

* store: refuse group name codes while names are off

* store: search names and preview links

* store: serve each site on its own port

* scripts: deploy the badges and names sites

* store: document search and the two sites

* store: add the drop_taken_codes migration

* store: read the names codes_only setting

* store: add the names store and order signatures

* store: take name orders by card, crypto or code

* store: document name orders and codes-only

* store: add the names transaction sender

* store: commit and register queued orders

* store: reveal and retry an owner's order

* store: document the gas key

* store: add the name balance migrations

* store: read crypto units, rates and confirmations

* store: keep a taken order's money as a balance

* store: spend a balance on another name

* store: record refunds with //refund

* store: document balances and refunds

* store: add the agreed terms migration

* store: read the terms and community names

* store: answer community and terms in search

* store: sign and store the agreed terms

* store: document the terms and community names

* store: add the invoiced units migration

* store: read the crypto an invoice asks

* store: credit late and overpaid crypto by share

* store: document crediting late crypto by share

* store: add the record changes migration

* store: find an owner's orders and move one

* store: relay owners' link edits on chain

* store: document link edits

* store: move isLoopbackHost to Config

* store: trust dev issuer keys on the local chain

* scripts: build the names site from a submodule

* scripts: add the dev setup and contract run

* store: document the dev setup and names image

* store: send a Stripe idempotency key for names

* tests: wait until a relay lets go of its edit

* store: refuse a link edit deadline under 10 min

* store: count reverted link edits in the year limit

* store: require https for a remote chain node

* store: refuse zero chain confirmations

* store: set up the dev stack from the names branch

* store: rerun a failed unpaid cleanup next pass

* store: never replace a succeeded Stripe intent

* store: refuse an ini setting written as key: value

* store: note the webapp submodule's pinned branch

* store: document confirmLanded judging by ownerOf

* store: update the names webapp submodule

* store-service: register names under the name policy, every name accepting its terms on chain (#7889)

* store: accept each name's terms on chain under the name policy

* ci: run the reduced build on sh/names-deploy

* store: address review: policy re-read, terms reads and startup log

* store: never credit an unconfirmed extra

* store: alert money sent to a paid name invoice

* store: refuse to start on another chain's node

* store: keep orders while the allowance is used up

* store: replace a stalled transaction after 3 blocks

* store: judge a name taken at confirmation depth

* store: bind the template's listener to loopback

* store: scan only the ids of active name orders

* store: refuse unknown [names] and [chain] settings

* store: fetch the webapp submodule in upgrade steps

* store: delete definitions only tests use

* store: lock only name invoices at settlement

* store: retry an unexpired commitment as usual

* store: share the helpers defined twice

* store: test route limits on the running service

* store: fix tests that could not fail

* ci: test the store service on Postgres

* store: count IPv6 clients by their /64

* store: sweep invoices read alone past a list cap

* store: cap checkouts of all clients together

* store: cap the long polls held at once

* store: stop the old badge project at upgrade

* store: keep search lookups free of previews

* store: read the ini as UTF-8 in any locale

* ci: run Postgres store tests in a UTF-8 locale

* store: cap the transactions one order sends

* store: cancel a card intent after three declines

* store: refuse a name price under a cent

* store: send each transaction with gas headroom

* store: cap searches and read terms once per block

* store: never log the group join link

* store: mask the database password at startup

* store: run one instance per database

* store: limit name codes to admins, 100 a day

* store: refuse HighSpeed settlement with names

* store: no unverified receipts with a trusted key

* store: cap the log lines of refused webhooks

* store: check Apple certificates at the signed date

* store: refuse a malformed Stripe publishable key

* store: check the owner before a refund

* store: fold the names migrations into one

* store: read onion name links through the proxy

* store: refund money after paid once confirmed

* store: limit the allowance wait to a dry run

* store: bind loopback when upgrading

* ci: cache and widen the store Postgres job

* store: fix stale and duplicate names tests

* store: fix the submodule path in the upgrade

* store: refuse unpaid name codes on the CLI

* store: apply the review's names test list

* store: finish the review's names test list

* store: restore the base registration tests

* store: pass link hosts that do not resolve here

* store: refuse a move once its sends are used up

* store: take the shared checkout at the provider

* store: hold a search slot for chain reads only

* store: state which refunds are safe on a reference

* store: check a failed order's name before refusing its move (#8060)

* store: test and document the shared checkout cap for name orders

* store: check a failed order's name on chain before refusing its move

* store: test name links whose host lookup fails

* store: test that a search holds its slot through the chain reads only

* store: restore the signed transaction check in the chain tests

* store: remove the chain tests' copy of the signed transaction check

* store: correct the search slot texts and the README's balance endpoints

* docs: system and sequence diagrams of the names service (#8068)

---------

Co-authored-by: sh-agents <350651734+sh-agents@users.noreply.github.com>
Co-authored-by: Evgeny Poberezkin <evgeny@poberezkin.com>
Co-authored-by: brenzi-agent <brenzi-agent@brenzi.ch>
Co-authored-by: Evgeny @ SimpleX Chat <259188159+evgeny-simplex@users.noreply.github.com>
2026-11-07 10:45:19 +00:00

517 lines
24 KiB
Haskell

{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
module Bots.StoreService.FakeEthNode
( FakeEthNode (..),
address,
CallAnswer (..),
TextAnswer (..),
Fault (..),
Gate,
withFakeEthNode,
fakeChainConfig,
fakeChainClient,
answerCall,
answerCallOnce,
answerCallFrom,
forgetCall,
setFault,
clearFault,
releaseGate,
pausedAt,
setBlock,
nextBlock,
setFees,
revertDryRun,
mine,
dropTransaction,
pruneReceipt,
useNextNonce,
sentTransactions,
awaitSent,
revertFault,
fakeChainId,
fakeController,
fakeNamePolicy,
listCommunityName,
answerListing,
setGeneralTerms,
setCommunityTerms,
answerText,
servedText,
fetchedTexts,
fakeTermsLink,
fakeTermsPath,
fakeTermsHash,
plainTerms,
fakeGeneralTerms,
fakeGeneralTermsText,
fakeNewGeneralTermsText,
fakeNewGeneralTerms,
fakeCommunityTerms,
fakeCommunityTermsText,
fakeNewCommunityTermsText,
fakeNewCommunityTerms,
fakeSponsor,
fakeBaseRegistrar,
fakeResolver,
fakeRegistrarKey,
fakeGas,
fakeTip,
fakeBaseFee,
fakeMaxFeePerGas,
)
where
import Control.Applicative ((<|>))
import Control.Concurrent (threadDelay)
import Control.Concurrent.Async (Async, async, cancel)
import Control.Concurrent.STM
import Control.Exception (finally)
import Crypto.Random (ChaChaDRG)
import Data.Aeson ((.:), (.=))
import qualified Data.Aeson as J
import qualified Data.Aeson.Types as JT
import qualified Data.ByteArray as BA
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.Map.Strict (Map)
import qualified Data.Map.Strict as M
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Encoding (decodeUtf8, encodeUtf8)
import Data.Word (Word64)
import qualified Network.HTTP.Client as HTTP
import Network.HTTP.Types (ResponseHeaders, Status, badGateway502, badRequest400, hContentType, methodGet, notFound404, ok200)
import Network.Wai (Application, rawPathInfo, requestMethod, responseLBS, strictRequestBody)
import qualified Network.Wai.Handler.Warp as Warp
import Numeric (readHex, showHex)
import Simplex.Messaging.Crypto (keccak256, sha256Hash)
import qualified Simplex.Messaging.Crypto.Secp256k1 as S
import Simplex.Messaging.Encoding.String (strDecode)
import Simplex.Messaging.Eth.Address (Address, unAddress)
import Simplex.Messaging.SimplexName (LabelHash (..))
import Simplex.Messaging.Util (eitherToMaybe)
import StoreService.Config (ChainConfig (..))
import StoreService.Names.Abi (AbiValue (..), abiBytes, abiTuple, addressWord, hex, selector, uint256)
import StoreService.Names.Chain (ChainClient (..), TxRequest (..), decodeSignedTx, newChainClient)
import System.Timeout (timeout)
data FakeEthNode = FakeEthNode
{ fnUrl :: String,
fnPort :: Int,
fnState :: TVar FakeState
}
data CallAnswer = Returns ByteString | Reverts ByteString
data TextAnswer = TextAnswer Status ResponseHeaders LB.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
| -- | the next request waits at the gate until it is released, then answers as usual; later ones pass
Gated Gate
data Gate = Gate {gArrived :: TMVar (), gRelease :: TMVar ()}
data FakeState = FakeState
{ fsCalls :: Map (ByteString, ByteString) CallAnswer,
-- | answered once, before 'fsCalls'
fsCallsOnce :: Map (ByteString, ByteString) CallAnswer,
-- | answered from the block on, before 'fsCalls'
fsCallsFrom :: Map (ByteString, ByteString) (Word64, 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 revert data of the dry runs of these calldata
fsDryRuns :: Map ByteString ByteString,
-- | the key's transaction count at the latest block
fsUsed :: Word64,
fsBlock :: (Word64, Word64),
-- | the times of the blocks mined or set, by number
fsBlockTimes :: Map Word64 Word64,
-- | the suggested tip and the base fee
fsFees :: (Word64, Word64),
fsTexts :: Map Text TextAnswer,
fsFetched :: [Text],
fsClosed :: Bool
}
fakeGas, fakeTip, fakeBaseFee, fakeMaxFeePerGas :: Num a => a
fakeGas = 200000
fakeTip = 1000000000
fakeBaseFee = 2000000000
fakeMaxFeePerGas = 100000000000
fakeChainId :: Word64
fakeChainId = 31337
fakeController, fakeSponsor, fakeBaseRegistrar, fakeResolver :: Address
fakeController = address "0x0165878a594ca255338adfa4d48449f69242eb8f"
fakeSponsor = address "0x9a676e781a523b5d0c0e43731313a708cb607508"
fakeBaseRegistrar = address "0xe7f1725e7734ce288f8367e1bb143e90bb3f0512"
fakeResolver = address "0x2279b7a0a67db372996a5fab50d91eaa73d2ebe6"
-- | The controller's name policy; it lists no community name unless a test answers otherwise, and links the terms texts the node serves.
fakeNamePolicy :: Address
fakeNamePolicy = address "0x5fc8d32690cc91d4c39d9d3abcbd16989f875707"
fakeGeneralTermsText, fakeNewGeneralTermsText, fakeCommunityTermsText, fakeNewCommunityTermsText :: ByteString
fakeGeneralTermsText = "SimpleX general terms v1"
fakeNewGeneralTermsText = "SimpleX general terms v2"
fakeCommunityTermsText = "SimpleX community terms v1"
fakeNewCommunityTermsText = "SimpleX community terms v2"
fakeGeneralTerms, fakeNewGeneralTerms, fakeCommunityTerms, fakeNewCommunityTerms :: ByteString
fakeGeneralTerms = fakeTermsHash fakeGeneralTermsText
fakeNewGeneralTerms = fakeTermsHash fakeNewGeneralTermsText
fakeCommunityTerms = fakeTermsHash fakeCommunityTermsText
fakeNewCommunityTerms = fakeTermsHash fakeNewCommunityTermsText
fakeTermsLink :: ByteString -> Text
fakeTermsLink text = "https://git.simplex.chat" <> fakeTermsPath text <> "#sha256=" <> T.drop 2 (hex $ sha256Hash text)
fakeTermsPath :: ByteString -> Text
fakeTermsPath text = "/simplex-chat/simplex-chat/raw/commit/" <> T.take 40 (T.drop 2 $ hex $ keccak256 text) <> "/docs/terms.md"
fakeTermsHash :: ByteString -> ByteString
fakeTermsHash = keccak256 . encodeUtf8 . fakeTermsLink
plainTerms :: Text
plainTerms = T.drop 2 $ hex fakeGeneralTerms
-- | The policy lists the name as a community name.
listCommunityName :: FakeEthNode -> LabelHash -> IO ()
listCommunityName node lh = answerListing node lh $ Returns $ uint256 (1 :: Int)
-- | The policy's answer to whether the name is a community name.
answerListing :: FakeEthNode -> LabelHash -> CallAnswer -> IO ()
answerListing node (LabelHash lh) = answerCall node fakeNamePolicy (selector "communityNames(bytes32)" <> lh)
-- | The policy links this text, which the node serves; an empty text is a link not set.
setGeneralTerms, setCommunityTerms :: FakeEthNode -> ByteString -> IO ()
setGeneralTerms node = setTerms node "generalTermsLink()"
setCommunityTerms node = setTerms node "communityTermsLink()"
-- | In a block of its own, as a policy change is, since the service reads the terms links once per block.
setTerms :: FakeEthNode -> ByteString -> ByteString -> IO ()
setTerms node getter text = do
answerText node (fakeTermsPath text) (servedText text)
answerCall node fakeNamePolicy (selector getter) $ Returns $ linkAnswer $ if B.null text then "" else fakeTermsLink text
nextBlock node
-- | The next block, at the same time.
nextBlock :: FakeEthNode -> IO ()
nextBlock FakeEthNode {fnState} = atomically $ modifyTVar' fnState $ \s@FakeState {fsBlock = (number, time)} ->
s {fsBlock = (number + 1, time), fsBlockTimes = M.insert (number + 1) time $ fsBlockTimes s}
servedText :: ByteString -> TextAnswer
servedText text = TextAnswer ok200 [(hContentType, "text/markdown; charset=utf-8")] (LB.fromStrict text)
answerText :: FakeEthNode -> Text -> TextAnswer -> IO ()
answerText FakeEthNode {fnState} path a = atomically $ modifyTVar' fnState $ \s -> s {fsTexts = M.insert path a $ fsTexts s}
fetchedTexts :: FakeEthNode -> IO [Text]
fetchedTexts FakeEthNode {fnState} = fsFetched <$> readTVarIO fnState
linkAnswer :: Text -> ByteString
linkAnswer link = abiTuple [Dynamic $ abiBytes $ encodeUtf8 link]
defaultCall :: (ByteString, ByteString) -> Maybe CallAnswer
defaultCall (to, calldata)
| to == unAddress fakeController && calldata == selector "namePolicy()" = Just $ Returns $ addressWord fakeNamePolicy
| to == unAddress fakeNamePolicy && selector "communityNames(bytes32)" `B.isPrefixOf` calldata = Just $ Returns $ uint256 (0 :: Int)
| to == unAddress fakeNamePolicy && calldata == selector "generalTermsLink()" = Just $ Returns $ linkAnswer $ fakeTermsLink fakeGeneralTermsText
| to == unAddress fakeNamePolicy && calldata == selector "communityTermsLink()" = Just $ Returns $ linkAnswer $ fakeTermsLink fakeCommunityTermsText
| to == unAddress fakeNamePolicy && selector "acceptedTerms(bytes32,address)" `B.isPrefixOf` calldata = Just $ Returns $ B.replicate 32 0
| to == unAddress fakeNamePolicy && selector "nonces(address)" `B.isPrefixOf` calldata = Just $ Returns $ uint256 (0 :: Int)
| otherwise = Nothing
fakeRegistrarKey :: S.Secp256k1PrivateKey
fakeRegistrarKey = either error id $ S.mkPrivateKey $ BA.replicate 32 0x46
-- | 2026-01-01, block 1 after the genesis block 0; 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
{ fsCalls = M.empty,
fsCallsOnce = M.empty,
fsCallsFrom = M.empty,
fsFaults = M.empty,
fsSent = [],
fsPool = M.empty,
fsReceipts = M.empty,
fsDryRuns = M.empty,
fsUsed = 0,
fsBlock = (1, genesisTime),
fsBlockTimes = M.fromList [(0, genesisTime - blockSeconds), (1, genesisTime)],
fsFees = (fakeTip, fakeBaseFee),
fsTexts = M.fromList [(fakeTermsPath t, servedText t) | t <- [fakeGeneralTermsText, fakeNewGeneralTermsText, fakeCommunityTermsText, fakeNewCommunityTermsText]],
fsFetched = [],
fsClosed = False
}
Warp.testWithApplication (pure $ fakeApp fnState) $ \fnPort ->
action FakeEthNode {fnUrl = "http://127.0.0.1:" <> show fnPort, fnPort, fnState}
`finally` atomically (modifyTVar' fnState $ \s -> s {fsClosed = True})
fakeChainConfig :: FakeEthNode -> ChainConfig
fakeChainConfig FakeEthNode {fnUrl} =
ChainConfig
{ cRpcUrl = fnUrl,
cChainId = fakeChainId,
cController = fakeController,
cSponsor = fakeSponsor,
cBaseRegistrar = fakeBaseRegistrar,
cResolver = fakeResolver,
cServiceKey = fakeRegistrarKey,
cConfirmations = 3,
cGasLimitCap = 8000000,
cMaxFeePerGas = fakeMaxFeePerGas
}
fakeChainClient :: TVar ChaChaDRG -> FakeEthNode -> IO ChainClient
fakeChainClient g node@FakeEthNode {fnPort} = do
c <- newChainClient g $ fakeChainConfig node
connect <- HTTP.managerRawConnection HTTP.defaultManagerSettings
let toNode hostAddress _ _ = connect hostAddress "127.0.0.1" fnPort
ccManager <- HTTP.newManager HTTP.defaultManagerSettings {HTTP.managerRawConnection = pure toNode, HTTP.managerTlsConnection = pure toNode}
pure c {ccManager}
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}
-- | The next call only is answered this way, then the call answers as before.
answerCallOnce :: FakeEthNode -> Address -> ByteString -> CallAnswer -> IO ()
answerCallOnce FakeEthNode {fnState} to calldata a = atomically $ modifyTVar' fnState $ \s -> s {fsCallsOnce = M.insert (unAddress to, calldata) a $ fsCallsOnce s}
-- | At this block and later ones the call answers this way, at earlier blocks as before.
answerCallFrom :: FakeEthNode -> Word64 -> Address -> ByteString -> CallAnswer -> IO ()
answerCallFrom FakeEthNode {fnState} block to calldata a = atomically $ modifyTVar' fnState $ \s -> s {fsCallsFrom = M.insert (unAddress to, calldata) (block, a) $ fsCallsFrom s}
-- | The call has no answer any more, as if the node failed it.
forgetCall :: FakeEthNode -> Address -> ByteString -> IO ()
forgetCall FakeEthNode {fnState} to calldata = atomically $ modifyTVar' fnState $ \s -> s {fsCalls = M.delete (unAddress to, calldata) $ fsCalls s}
-- | Every request for the method fails this way until 'clearFault'.
setFault :: FakeEthNode -> Text -> Fault -> IO ()
setFault FakeEthNode {fnState} method f = atomically $ modifyTVar' fnState $ \s -> s {fsFaults = M.insert method f $ fsFaults s}
clearFault :: FakeEthNode -> Text -> IO ()
clearFault FakeEthNode {fnState} method = atomically $ modifyTVar' fnState $ \s -> s {fsFaults = M.delete method $ fsFaults s}
-- | The next request for the method stops at the gate it returns.
gateNext :: FakeEthNode -> Text -> IO Gate
gateNext node method = do
gate <- Gate <$> newEmptyTMVarIO <*> newEmptyTMVarIO
gate <$ setFault node method (Gated gate)
-- | Returns once a request is held at the gate.
awaitGate :: Gate -> IO ()
awaitGate Gate {gArrived} = atomically $ readTMVar gArrived
releaseGate :: Gate -> IO ()
releaseGate Gate {gRelease} = atomically $ putTMVar gRelease ()
-- | Far longer than a request takes to reach its first chain read.
gateArrival :: Int
gateArrival = 5000000
-- | The action, run until its first request for the method is held at the gate.
pausedAt :: FakeEthNode -> Text -> IO a -> IO (Async a, Gate)
pausedAt node method action = do
gate <- gateNext node method
inFlight <- async action
timeout gateArrival (awaitGate gate) >>= maybe (cancel inFlight >> fail ("no " <> T.unpack method <> " reached the gate")) (const $ pure (inFlight, gate))
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), fsBlockTimes = M.insert number time $ fsBlockTimes s}
-- | The dry run of this calldata reverts with this data, or passes again with Nothing.
revertDryRun :: FakeEthNode -> ByteString -> Maybe ByteString -> IO ()
revertDryRun FakeEthNode {fnState} calldata revertData = atomically $ modifyTVar' fnState $ \s -> s {fsDryRuns = M.alter (const revertData) calldata $ fsDryRuns s}
setFees :: FakeEthNode -> Word64 -> Word64 -> IO ()
setFees FakeEthNode {fnState} tip baseFee = atomically $ modifyTVar' fnState $ \s -> s {fsFees = (tip, baseFee)}
-- | 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), fsBlockTimes = M.insert number' (time + blockSeconds) $ fsBlockTimes s, fsReceipts = M.union mined fsReceipts, fsPool = M.dropWhileAntitone (< used) fsPool, fsUsed = used}
pure number'
-- | The node forgets a transaction it has not mined, as after its own restart.
dropTransaction :: FakeEthNode -> ByteString -> IO ()
dropTransaction FakeEthNode {fnState} hash = atomically $ modifyTVar' fnState $ \s -> s {fsPool = M.filter ((/= hash) . keccak256) $ fsPool s}
-- | The node forgets a receipt, as a pruned node does; the nonce stays used.
pruneReceipt :: FakeEthNode -> ByteString -> IO ()
pruneReceipt FakeEthNode {fnState} hash = atomically $ modifyTVar' fnState $ \s -> s {fsReceipts = M.delete hash $ fsReceipts s}
-- | The key's next nonce goes to a transaction the node shows nothing of, and the pool loses its own at that nonce.
useNextNonce :: FakeEthNode -> IO ()
useNextNonce FakeEthNode {fnState} = atomically $ modifyTVar' fnState $ \s@FakeState {fsUsed, fsPool} -> s {fsUsed = fsUsed + 1, fsPool = M.delete fsUsed fsPool}
-- | The raw transactions in the order they were sent.
sentTransactions :: FakeEthNode -> IO [ByteString]
sentTransactions FakeEthNode {fnState} = reverse . fsSent <$> readTVarIO fnState
-- | Waits until the node has received at least this many raw transactions, and returns them in the order they were sent.
awaitSent :: FakeEthNode -> Int -> IO [ByteString]
awaitSent FakeEthNode {fnState} n = atomically $ do
sent <- fsSent <$> readTVar fnState
check $ length sent >= n
pure $ reverse sent
fakeApp :: TVar FakeState -> Application
fakeApp st req respond = do
body <- strictRequestBody req
case JT.parseMaybe request =<< J.decode body of
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
Just (Gated Gate {gArrived, gRelease}) -> do
atomically $ putTMVar gArrived ()
atomically $ takeTMVar gRelease `orElse` (readTVar st >>= check . fsClosed)
answered method params
Nothing -> answered method params
Nothing
| requestMethod req == methodGet ->
fault "GET" >>= \case
Just (Slow delay) -> threadDelay delay >> text
_ -> text
| otherwise -> respond $ responseLBS badRequest400 [] "not a JSON-RPC request"
where
text = do
let path = decodeUtf8 $ rawPathInfo req
answer_ <- atomically $ do
s@FakeState {fsTexts, fsFetched} <- readTVar st
writeTVar st s {fsFetched = path : fsFetched}
pure $ M.lookup path fsTexts
respond $ case answer_ of
Just (TextAnswer status headers body) -> responseLBS status headers body
Nothing -> responseLBS notFound404 [] ""
request = J.withObject "request" $ \o -> (,) <$> o .: "method" <*> o .: "params"
-- a gate holds one request only
fault method = atomically $ do
s <- readTVar st
case M.lookup method $ fsFaults s of
f@(Just Gated {}) -> f <$ writeTVar st s {fsFaults = M.delete method $ fsFaults s}
f -> pure f
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 {fsCalls, fsCallsOnce, fsCallsFrom, fsSent, fsPool, fsReceipts, fsDryRuns, fsUsed, fsBlock = (number, time), fsBlockTimes, fsFees = (tip, baseFee)} <- readTVar st
case (method, params) of
("eth_call", [call, J.String tag])
| Just (to, calldata) <- JT.parseMaybe callTarget call,
Just at <- if tag == "latest" then Just number else fromQuantity tag ->
let key = (unAddress to, calldata)
callAnswer = \case
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
in case M.lookup key fsCallsOnce of
Just a -> callAnswer (Just a) <$ writeTVar st s {fsCallsOnce = M.delete key fsCallsOnce}
Nothing -> pure $ callAnswer $ case M.lookup key fsCallsFrom of
Just (from, a) | at >= from -> Just a
_ -> M.lookup key fsCalls <|> defaultCall key
("eth_estimateGas", call : _)
| Just (_, calldata) <- JT.parseMaybe callTarget call,
Just revertData <- M.lookup calldata fsDryRuns ->
pure $ rpcError 3 "execution reverted" (Just revertData)
("eth_estimateGas", _) -> pure $ result $ quantity fakeGas
("eth_getTransactionCount", [_, J.String "latest"]) -> pure $ result $ quantity $ toInteger fsUsed
("eth_getTransactionCount", [_, J.String "pending"]) ->
pure $ result $ quantity $ toInteger $ fsUsed + fromIntegral (length $ takeWhile (`M.member` fsPool) [fsUsed ..])
("eth_maxPriorityFeePerGas", _) -> pure $ result $ quantity $ toInteger tip
("eth_chainId", _) -> pure $ result $ quantity $ toInteger fakeChainId
("eth_getBlockByNumber", [J.String "latest", _]) -> pure $ result $ blockJson baseFee number time
-- a block not mined or set here has the time of the last one before it
("eth_getBlockByNumber", [J.String n, _])
| Just at <- fromQuantity n -> pure $ result $ case M.lookupLE at fsBlockTimes of
Just (_, t) | at <= number -> blockJson baseFee at t
_ -> J.Null
("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]
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 "")
fromQuantity :: Text -> Maybe Word64
fromQuantity t = case T.stripPrefix "0x" t of
Just h | [(n, "")] <- readHex (T.unpack h) -> Just n
_ -> Nothing
fromHex :: Text -> Maybe ByteString
fromHex t = T.stripPrefix "0x" t >>= eitherToMaybe . convertFromBase Base16 . encodeUtf8
address :: ByteString -> Address
address = either error id . strDecode