mirror of
https://github.com/simplex-chat/simplex-chat.git
synced 2026-11-22 15:38:23 +00:00
name registration service and client functions and mocks (#7693)
* name registration service and client functions and mocks * 2 rounds of goal iter * write a plan doc * 7 rounds of /goal * adapt contract updates * intent signature includes duration of reservation. verify field before submitting the tx * round 11 converged --------- Co-authored-by: Evgeny Poberezkin <evgeny@poberezkin.com> Co-authored-by: shum <github.shum@liber.li>
This commit is contained in:
10 files changed
+773
-1
No files matched your search
@@ -0,0 +1,109 @@
|
||||
{-# LANGUAGE NamedFieldPuns #-}
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
{-# LANGUAGE ScopedTypeVariables #-}
|
||||
|
||||
module BadgeService.Names.Chain
|
||||
( ChainClient (..),
|
||||
ChainError (..),
|
||||
TxHash (..),
|
||||
sendCommit,
|
||||
sendRegister,
|
||||
)
|
||||
where
|
||||
|
||||
import BadgeService.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 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.ByteString (ByteString)
|
||||
import Data.Text (Text)
|
||||
import qualified Data.Text as T
|
||||
import Data.Text.Encoding (decodeLatin1, encodeUtf8)
|
||||
import Data.Word (Word64)
|
||||
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 Simplex.Messaging.Eth.Address (Address, addressFromPrivateKey)
|
||||
import Simplex.Messaging.Eth.Transaction (Eip1559Tx (..), signEip1559Tx)
|
||||
import Simplex.Messaging.Util (liftError', tshow)
|
||||
|
||||
data ChainClient = ChainClient
|
||||
{ ccManager :: Manager,
|
||||
ccRpcUrl :: String,
|
||||
ccChainId :: Word64,
|
||||
ccController :: Address,
|
||||
ccSponsor :: Address,
|
||||
ccRegistrarKey :: Secp256k1PrivateKey
|
||||
}
|
||||
|
||||
newtype ChainError = ChainError Text
|
||||
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
|
||||
|
||||
sendRegister :: TVar ChaChaDRG -> ChainClient -> RegisterIntent -> IO (Either ChainError TxHash)
|
||||
sendRegister g c@ChainClient {ccSponsor} = sendTransaction g c ccSponsor . registerWithCreditCalldata
|
||||
|
||||
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
|
||||
|
||||
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)
|
||||
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"
|
||||
|
||||
quantity :: (Eq a, Num 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
|
||||
_ -> 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,145 @@
|
||||
{-# LANGUAGE LambdaCase #-}
|
||||
{-# LANGUAGE NamedFieldPuns #-}
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
|
||||
module BadgeService.Names.Registration
|
||||
( Registration (..),
|
||||
RegisterIntent (..),
|
||||
sponsorDomain,
|
||||
makeCommitment,
|
||||
commitCalldata,
|
||||
registerWithCreditCalldata,
|
||||
registerIntentDigest,
|
||||
verifyRegisterIntent,
|
||||
)
|
||||
where
|
||||
|
||||
import Control.Monad (unless, when)
|
||||
import Control.Monad.Except (ExceptT (..), runExceptT, throwError)
|
||||
import Crypto.Number.Serialize (i2ospOf_)
|
||||
import Data.ByteString (ByteString)
|
||||
import qualified Data.ByteString as B
|
||||
import Data.List (mapAccumL)
|
||||
import Data.Text (Text)
|
||||
import qualified Data.Text as T
|
||||
import Data.Text.Encoding (encodeUtf8)
|
||||
import Data.Word (Word64)
|
||||
import Simplex.Messaging.Crypto (keccak256)
|
||||
import Simplex.Messaging.Crypto.Secp256k1 (RecoverableSignature)
|
||||
import Simplex.Messaging.Encoding.String (strEncode)
|
||||
import Simplex.Messaging.Eth.Address (Address, recoverAddress, unAddress)
|
||||
import Simplex.Messaging.Eth.EIP712 (Eip712Domain (..), Eip712Value (..), hashTypedData, serializeSignature)
|
||||
import Simplex.Messaging.SimplexName (SimplexTLD)
|
||||
|
||||
data Registration = Registration
|
||||
{ rLabel :: Text,
|
||||
rTLD :: SimplexTLD,
|
||||
rOwner :: Address,
|
||||
rDuration :: Word64,
|
||||
rSecret :: ByteString,
|
||||
rResolver :: Address,
|
||||
rContactLinks :: [Text],
|
||||
rChannelLinks :: [Text]
|
||||
}
|
||||
|
||||
data RegisterIntent = RegisterIntent
|
||||
{ riRegistration :: Registration,
|
||||
riNonce :: Word64,
|
||||
riDeadline :: Word64,
|
||||
riSignature :: RecoverableSignature
|
||||
}
|
||||
|
||||
sponsorDomain :: Word64 -> Address -> Eip712Domain
|
||||
sponsorDomain edChainId edVerifyingContract = Eip712Domain {edName = "SimplexSponsor", edVersion = "1", edChainId, edVerifyingContract}
|
||||
|
||||
makeCommitment :: Registration -> ByteString
|
||||
makeCommitment r = keccak256 $ abiTuple [Dynamic $ registrationTuple r]
|
||||
|
||||
commitCalldata :: ByteString -> ByteString
|
||||
commitCalldata commitment = selector "commit(bytes32)" <> commitment
|
||||
|
||||
registerWithCreditCalldata :: RegisterIntent -> ByteString
|
||||
registerWithCreditCalldata RegisterIntent {riRegistration, riNonce, riDeadline, riSignature} =
|
||||
selector "registerWithCredit((string,address,uint256,bytes32,address,bytes[],uint8,bytes32),uint256,uint256,bytes)"
|
||||
<> abiTuple
|
||||
[ Dynamic $ registrationTuple riRegistration,
|
||||
Static $ uint256 riNonce,
|
||||
Static $ uint256 riDeadline,
|
||||
Dynamic $ abiBytes $ serializeSignature riSignature
|
||||
]
|
||||
|
||||
registerIntentDigest :: Eip712Domain -> Registration -> Word64 -> Word64 -> ByteString
|
||||
registerIntentDigest domain r@Registration {rLabel, rOwner, rDuration, rResolver} nonce deadline =
|
||||
hashTypedData
|
||||
domain
|
||||
"RegisterName(string label,address owner,uint256 duration,address resolver,bytes[] data,uint256 nonce,uint256 deadline)"
|
||||
[ VBytes $ encodeUtf8 rLabel,
|
||||
VAddress rOwner,
|
||||
VUint $ fromIntegral rDuration,
|
||||
VAddress rResolver,
|
||||
VArray $ map VBytes $ recordCalls r,
|
||||
VUint $ fromIntegral nonce,
|
||||
VUint $ fromIntegral deadline
|
||||
]
|
||||
|
||||
verifyRegisterIntent :: Eip712Domain -> Word64 -> RegisterIntent -> IO (Either String ())
|
||||
verifyRegisterIntent domain now RegisterIntent {riRegistration = r@Registration {rOwner, rSecret}, riNonce, riDeadline, riSignature} = runExceptT $ do
|
||||
unless (B.length rSecret == 32) $ throwError "secret: expected 32 bytes"
|
||||
when (now > riDeadline) $ throwError "intent expired"
|
||||
signer <- ExceptT $ recoverAddress riSignature $ registerIntentDigest domain r riNonce riDeadline
|
||||
unless (signer == rOwner) $ throwError "intent is not signed by the owner"
|
||||
|
||||
registrationTuple :: Registration -> ByteString
|
||||
registrationTuple r@Registration {rLabel, rOwner, rDuration, rSecret, rResolver} =
|
||||
abiTuple
|
||||
[ Dynamic $ abiBytes $ encodeUtf8 rLabel,
|
||||
Static $ addressWord rOwner,
|
||||
Static $ uint256 rDuration,
|
||||
Static rSecret,
|
||||
Static $ addressWord rResolver,
|
||||
Dynamic $ abiArray $ map abiBytes $ recordCalls r,
|
||||
Static reverseRecord,
|
||||
Static referrer
|
||||
]
|
||||
where
|
||||
reverseRecord = uint256 (0 :: Int)
|
||||
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)]
|
||||
where
|
||||
setText key ls =
|
||||
selector "setText(bytes32,string,string)"
|
||||
<> abiTuple [Static node, Dynamic $ abiBytes key, Dynamic $ abiBytes $ encodeUtf8 $ T.intercalate ";" ls]
|
||||
node = namehash rTLD rLabel
|
||||
|
||||
namehash :: SimplexTLD -> Text -> ByteString
|
||||
namehash tld label = keccak256 $ tldNode <> keccak256 (encodeUtf8 label)
|
||||
where
|
||||
tldNode = keccak256 $ B.replicate 32 0 <> keccak256 (B.drop 1 $ strEncode tld)
|
||||
|
||||
data AbiValue = Static ByteString | Dynamic ByteString
|
||||
|
||||
abiTuple :: [AbiValue] -> ByteString
|
||||
abiTuple values = B.concat heads <> B.concat [tl | Dynamic tl <- values]
|
||||
where
|
||||
heads = snd $ mapAccumL encodeHead (32 * 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
|
||||
|
||||
abiArray :: [ByteString] -> ByteString
|
||||
abiArray items = uint256 (length items) <> abiTuple (map Dynamic items)
|
||||
|
||||
uint256 :: Integral a => a -> ByteString
|
||||
uint256 = i2ospOf_ 32 . toInteger
|
||||
|
||||
addressWord :: Address -> ByteString
|
||||
addressWord a = B.replicate 12 0 <> unAddress a
|
||||
|
||||
selector :: ByteString -> ByteString
|
||||
selector = B.take 4 . keccak256
|
||||
@@ -0,0 +1,128 @@
|
||||
# SimpleX names: registration through the sponsor service
|
||||
|
||||
Branch: `ab/names-registration-primitives-sponsored`, with simplexmq branch `ab/name-registration-primitives-sponsored` (PR #1941 into `names`).
|
||||
|
||||
Contracts: `SimplexController`, `SimplexSponsor` and `SimplexResolver` from ens-contracts `simplex` with PR #35, and branch `ab/sponsor-sign-duration` (PR #36), which adds the duration to `RegisterName`.
|
||||
|
||||
## Contents
|
||||
|
||||
1. Summary
|
||||
2. User story
|
||||
3. Scope
|
||||
4. The flow
|
||||
5. Code
|
||||
6. Tests
|
||||
7. Left to the plumbing PR
|
||||
|
||||
## 1. Summary
|
||||
|
||||
A user buys a `.simplex` name on the web, before the app supports wallets or name purchases, and without a browser wallet extension. The web UI makes a new wallet for the name, the service registers the name to that wallet and pays the gas, and the user keeps a redemption code from which the wallet's key is derived. Later the user redeems the code in the app.
|
||||
|
||||
This PR adds the functions this needs and tests that run the whole flow against a fake Ethereum node. It adds no plumbing: no worker, database, ini section or HTTP API.
|
||||
|
||||
## 2. User story
|
||||
|
||||
1. The user opens the names web UI, picks a name and pays.
|
||||
2. The web UI generates a wallet for this one name.
|
||||
3. The web UI shows a redemption code, `SN-XXXXX-XXXXX-XXXXX-XXXXX-XXXXX-XXXXX`. The wallet's key is derived from the code, so whoever has the code controls the name.
|
||||
4. The service registers the name to the wallet's address. The user pays no gas and holds no ETH.
|
||||
5. Later, once the app supports wallets, the user enters the code in the app, and the name is transferred to the app's wallet.
|
||||
|
||||
## 3. Scope
|
||||
|
||||
In this PR:
|
||||
|
||||
- name codes: generating, formatting and parsing the redemption code;
|
||||
- the registration: its ABI encoding, the commitment, the `commit` and `registerWithCredit` calldata, and the owner's EIP-712 `RegisterName` intent and its verification;
|
||||
- a JSON-RPC client that dry-runs, signs and sends the `commit` and `registerWithCredit` transactions;
|
||||
- in simplexmq: EIP-712 hashing, signature serialization for the contract, and recovering the signer's address;
|
||||
- test mocks for the web UI and for an Ethereum node, and tests.
|
||||
|
||||
Not in this PR:
|
||||
|
||||
- the web UI itself (simplexmq PR #1942), payments, and the service's worker, database, ini section and HTTP API;
|
||||
- redeeming the code in the app. After PR #35 a name is transferred only with its recipient's consent: the code's wallet offers it (`approveWithSig`) and the app's wallet claims it (`claimWithSig`), both relayed by the service.
|
||||
|
||||
## 4. The flow
|
||||
|
||||
1. **Wallet and code (web UI).** The wallet's entropy is 128 random bits. Its key is the BIP-44 key at `m/44'/60'/0'/0/0` of the 12-word BIP-39 phrase with this entropy, so a BIP-44 wallet app can import it from that phrase. The code is `SN-` and 30 Crockford base32 characters: the entropy and the first 22 bits of its SHA-256.
|
||||
2. **Commitment (web UI).** The web UI generates a 32-byte secret and builds the registration: label, TLD, owner (the wallet's address), duration, secret, resolver, and the `simplex.contact` and `simplex.channel` records. Records are `setText` calls on the resolver, `simplex.contact` then `simplex.channel`, links joined with `;`, and no call for a key without links. The commitment is `keccak256(abi.encode(Registration))`, as `SimplexController.makeCommitment` computes it.
|
||||
3. **Commit (service).** The web UI sends only the commitment, so the name is not revealed. The service sends `commit(commitment)` to the controller.
|
||||
4. **Intent (web UI).** The wallet signs `RegisterName(string label,address owner,uint256 duration,address resolver,bytes[] data,uint256 nonce,uint256 deadline)` under the `SimplexSponsor` EIP-712 domain. The nonce is the owner's count of intents the sponsor has used, so it is 0 for the new wallet. The web UI sends the registration, the nonce, the deadline and the signature.
|
||||
5. **Verify (service).** The service checks that the secret is 32 bytes, the deadline has not passed, and the owner signed the intent.
|
||||
6. **Register (service).** At least `minCommitmentAge` after the commit, the service sends `registerWithCredit(registration, nonce, deadline, signature)` to the sponsor. The sponsor checks the deadline, the nonce and the signature, spends the registrar's allowance, and the controller registers the name to the owner with its records.
|
||||
|
||||
Every transaction is first dry-run with `eth_estimateGas`; if it reverts, nothing is sent. The service signs EIP-1559 transactions with its registrar key: gas limit from the estimate, nonce from the registrar's pending transaction count, priority fee from `eth_maxPriorityFeePerGas`, maximum fee twice the latest base fee plus the priority fee.
|
||||
|
||||
## 5. Code
|
||||
|
||||
simplex-chat:
|
||||
|
||||
- `src/Simplex/Chat/Badges/Code.hs`: `NameCode`, `randomNameCode`, `parseNameCode`, `formatNameCode`, `nameCodeEntropy`, next to the badge codes and sharing their alphabet and parsing rules.
|
||||
- `apps/simplex-badge-service/src/BadgeService/Names/Registration.hs`: `Registration`, `RegisterIntent`, `sponsorDomain`, `makeCommitment`, `commitCalldata`, `registerWithCreditCalldata`, `registerIntentDigest`, `verifyRegisterIntent`.
|
||||
- `apps/simplex-badge-service/src/BadgeService/Names/Chain.hs`: `ChainClient`, `ChainError`, `TxHash`, `sendCommit`, `sendRegister`.
|
||||
|
||||
simplexmq:
|
||||
|
||||
- `Simplex.Messaging.Eth.EIP712`: `hashTypedData` and `serializeSignature`.
|
||||
- `recoverPublicKey` in `Simplex.Messaging.Crypto.Secp256k1` and `recoverAddress` in `Simplex.Messaging.Eth.Address`.
|
||||
|
||||
Test mocks:
|
||||
|
||||
- `tests/Bots/BadgeService/WebUIMock.hs`, the web UI's side: `newEphemeralWallet`, `redemptionCode`, `walletFromCode`, `signRegisterIntent`.
|
||||
- `tests/Bots/BadgeService/FakeEthNode.hs`, a JSON-RPC node that answers the five calls `sendCommit` and `sendRegister` make, records the transactions sent, and reverts the dry run on request.
|
||||
|
||||
## 6. Tests
|
||||
|
||||
`tests/Bots/BadgeService/NameRegistrationTests.hs`:
|
||||
|
||||
- the `commit` calldata of a registration's commitment, and the `registerWithCredit` calldata with and without records, against expected bytes;
|
||||
- verification fails for an intent signed by another wallet, an intent past its deadline, and a secret that is not 32 bytes;
|
||||
- nothing is sent when the dry run reverts;
|
||||
- the whole flow: a new wallet, its code read back to the same wallet, the commit, the signed intent, its verification, and the registration, each transaction checked against the expected bytes sent to the controller and the sponsor.
|
||||
|
||||
`tests/BadgeTests.hs`: name code vectors, and a code with a wrong character does not parse.
|
||||
|
||||
simplexmq `tests/CoreTests/EthCryptoTests.hs`: an EIP-712 digest, the serialized signature, the recovered address, and every error in `recoverPublicKey`.
|
||||
|
||||
Expected values come from independent implementations:
|
||||
|
||||
- the commitment and calldata from viem, against the ABIs compiled from `ab/sponsor-sign-duration`, with the addresses and chain id of its test deployment;
|
||||
- the simplexmq digest and signature from viem;
|
||||
- name codes from a separate Python implementation.
|
||||
|
||||
Checked once against the contracts, outside CI:
|
||||
|
||||
- with the `ab/sponsor-sign-duration` test fixture, a call with the exact calldata the tests expect registered the name to the owner with both records, and the same call with one signature byte changed reverted with `InvalidSignature()`;
|
||||
- on a local hardhat node with the `ab/sponsor-sign-duration` contracts, `sendCommit` and `sendRegister` registered the name over JSON-RPC.
|
||||
|
||||
Run:
|
||||
|
||||
```
|
||||
cabal build -w ghc-9.6.3 test:simplex-chat-test
|
||||
$(cabal list-bin -w ghc-9.6.3 test:simplex-chat-test) -m "name codes" -m "badge service name registration"
|
||||
```
|
||||
|
||||
## 7. Left to the plumbing PR
|
||||
|
||||
- Call `verifyRegisterIntent` before `sendRegister`. The sponsor checks no signature, nonce or deadline when the owner is the registrar, and a secret that is not 32 bytes can change what the contract decodes.
|
||||
- Parse the commit request's commitment as exactly 32 bytes. `commitCalldata` appends whatever it is given.
|
||||
- Check the signed duration and the price against what was paid. The sponsor spends the registrar's allowance on the duration the owner signs. Price the order from the label's length in the oracle's price list, not with `rentPriceUSD(label, …)`, which sends the label to the node.
|
||||
- Send `commit` only for a paid order. It costs the registrar gas, and the service cannot check a name the commitment hides.
|
||||
- Register only the registration whose `makeCommitment` equals the commitment of the paid order the request names, once per order, and reject a commitment that is already in another order. Otherwise anyone can commit registrations of their own and have the sponsor spend the registrar's allowance on them.
|
||||
- Accept only the default resolver, only a contact short link in `simplex.contact` and a channel short link in `simplex.channel`, as the app's `firstNameLink` reads them, bound their size, reject a `;` in a link, and cap the gas limit. The client sets the resolver and the links, the controller calls that resolver with the records, readers split a record into links at `;`, and the registrar pays for the gas the transaction uses, up to the estimate.
|
||||
- Cap the priority fee and the maximum fee per gas. Both are set from the node's replies, and the registrar pays up to the maximum fee for each unit of gas used. Send `registerWithCredit` only while the current fees are within the caps, and replace it at market fees if it is not mined within a block or two: its calldata reveals the name, and once it has been pending for `minCommitmentAge` anyone can commit to the name and register it first.
|
||||
- Accept only a label the web UI accepts: 6 to 63 letters a-z, digits 0-9 and single hyphens between them. The label is signed and committed as sent, so the service cannot normalize it, and resolution looks it up lower-cased.
|
||||
- Take the TLD, `.simplex`, from the configuration, not from the request, and build the EIP-712 domain from the chain id and sponsor of the `ChainClient` passed to `sendRegister`.
|
||||
- Parse the client's signature with v 27 or 28 and a low s, as the sponsor's ECDSA requires. libsecp256k1 also recovers a signer from a signature the sponsor rejects, such as one with a high s.
|
||||
- Reject an intent whose deadline leaves too little time to commit, wait `minCommitmentAge` and register. The web UI sets the deadline from the browser's clock, an hour ahead, and a Bitcoin payment can take longer.
|
||||
- Let the user sign again when a paid order's intent expired unused: the web UI rebuilds the wallet from the code, fetches the order's expired register request from the service, uses its label, links and secret only if its signature verifies under the rebuilt wallet's key for the web UI's own chain, sponsor, resolver, duration and TLD, shows the label and links for the user to confirm, and signs with a new deadline and the owner's sponsor nonce. The commitment covers neither, so it does not change.
|
||||
- Send from one registrar key one transaction at a time, since the nonce is the registrar's pending transaction count.
|
||||
- Store each signed transaction with its order before sending it. After an ambiguous error, send the same transaction again; replace one that is not mined only at its nonce, with higher fees within the caps. Before a new transaction for an order, check the commitment and the owner's sponsor nonce on chain, and the name only once its commitment has aged.
|
||||
- Reconcile the sponsor's `RegistrarAllowanceSpent` and the controller's registrations with the orders, alert the guardian on a mismatch, and top up the allowance in small steps. Whoever holds a leaked registrar key can register any name they learn to a wallet of their own.
|
||||
- Wait until the controller has the commitment, then `minCommitmentAge`, before registering, and register only while the commitment is more than a margin away from `maxCommitmentAge`; otherwise commit it again after it expires. Anyone can send the same commitment first, and then the registrar's own commit reverts.
|
||||
- Call `sendRegister` only once the commitment has aged, as its dry run already sends the calldata to the node, and keep the label out of payment metadata and logs until the name is registered. The calldata reveals the name, and whoever sees it can commit to the name too. The same holds for any call with the label or its hash, such as `available`, `nameExpires` or `ownerOf`.
|
||||
- Accept only an https or loopback RPC URL, bound the size of RPC responses, reject quantities that overflow their type, and check `eth_chainId` against the configured chain.
|
||||
- Read the revert reason from `error.data` to tell a revert from a failed call, after checking that reth returns it there. A hardhat node does not when the revert comes from the controller through the sponsor.
|
||||
- Keep the RPC URL out of logged errors, as it can contain an API key, and bound the node's error messages.
|
||||
- Add `BadgeService.Names.Chain` and `BadgeService.Names.Registration` to the `simplex-badge-service` executable in `simplex-chat.cabal`; this PR adds them only to the test suite.
|
||||
@@ -761,6 +761,8 @@ test-suite simplex-chat-test
|
||||
BadgeService.Group
|
||||
BadgeService.Group.Command
|
||||
BadgeService.Log
|
||||
BadgeService.Names.Chain
|
||||
BadgeService.Names.Registration
|
||||
BadgeService.Options
|
||||
BadgeService.Orders
|
||||
BadgeService.Poller
|
||||
@@ -783,15 +785,18 @@ test-suite simplex-chat-test
|
||||
Bots.BadgeService.ConfigTests
|
||||
Bots.BadgeService.FakeAppStore
|
||||
Bots.BadgeService.FakeBTCPay
|
||||
Bots.BadgeService.FakeEthNode
|
||||
Bots.BadgeService.FakePlay
|
||||
Bots.BadgeService.FakeStore
|
||||
Bots.BadgeService.FakeStripe
|
||||
Bots.BadgeService.GroupIntegrationTests
|
||||
Bots.BadgeService.GroupTests
|
||||
Bots.BadgeService.NameRegistrationTests
|
||||
Bots.BadgeService.StoreVerifierTests
|
||||
Bots.BadgeService.StripeTests
|
||||
Bots.BadgeService.WaitersTests
|
||||
Bots.BadgeService.WebTests
|
||||
Bots.BadgeService.WebUIMock
|
||||
Broadcast.Bot
|
||||
Broadcast.Options
|
||||
Directory.BlockedWords
|
||||
|
||||
@@ -6,6 +6,9 @@
|
||||
-- A code is "SB-" and 20 Crockford base32 characters in four groups of five:
|
||||
-- 19 payload characters and a final check character.
|
||||
--
|
||||
-- A name code is "SN-" and 30 characters in six groups of five: the 128-bit wallet
|
||||
-- entropy and the first 22 bits of its SHA-256.
|
||||
--
|
||||
-- Reading folds the characters the alphabet omits so that a code copied by hand still
|
||||
-- verifies: it is case-insensitive and maps 'I' and 'L' to '1' and 'O' to '0'.
|
||||
--
|
||||
@@ -23,19 +26,29 @@ module Simplex.Chat.Badges.Code
|
||||
badgeCodeText,
|
||||
badgeCodeHash,
|
||||
formatBadgeCode,
|
||||
NameCode,
|
||||
randomNameCode,
|
||||
parseNameCode,
|
||||
formatNameCode,
|
||||
nameCodeEntropy,
|
||||
)
|
||||
where
|
||||
|
||||
import Control.Concurrent.STM
|
||||
import Control.Monad (guard)
|
||||
import Crypto.Number.Serialize (i2ospOf_, os2ip)
|
||||
import Crypto.Random (ChaChaDRG)
|
||||
import Data.Bits (shiftR)
|
||||
import Data.ByteString.Char8 (ByteString)
|
||||
import qualified Data.ByteString.Char8 as B
|
||||
import Data.Char (isAlphaNum, toUpper)
|
||||
import Data.List (elemIndex)
|
||||
import Data.List (elemIndex, foldl')
|
||||
import Data.Text (Text)
|
||||
import qualified Data.Text as T
|
||||
import Data.Text.Encoding (encodeUtf8)
|
||||
import qualified Simplex.Messaging.Crypto as C
|
||||
import Simplex.Messaging.Crypto.BIP39 (EntropyStrength (..), WalletEntropy, mkEntropy, randomEntropy, unEntropy)
|
||||
import Simplex.Messaging.Util (eitherToMaybe)
|
||||
|
||||
-- | A code that has passed its check character, in canonical form: 'codePrefix' followed by
|
||||
-- 20 upper-case alphabet characters, without separators.
|
||||
@@ -116,3 +129,39 @@ formatBadgeCode (BadgeCode t) = T.intercalate "-" $ codePrefix : groups (T.drop
|
||||
groups s
|
||||
| T.null s = []
|
||||
| otherwise = let (g, rest) = T.splitAt groupLength s in g : groups rest
|
||||
|
||||
newtype NameCode = NameCode WalletEntropy
|
||||
|
||||
nameCodeLength :: Int
|
||||
nameCodeLength = 30
|
||||
|
||||
nameCodePrefix :: Text
|
||||
nameCodePrefix = "SN"
|
||||
|
||||
nameCodeChecksumBits :: Int
|
||||
nameCodeChecksumBits = 22
|
||||
|
||||
randomNameCode :: TVar ChaChaDRG -> IO NameCode
|
||||
randomNameCode drg = NameCode <$> atomically (randomEntropy ES128 drg)
|
||||
|
||||
parseNameCode :: Text -> Maybe NameCode
|
||||
parseNameCode t = do
|
||||
body <- T.stripPrefix nameCodePrefix $ T.toUpper $ T.filter isAlphaNum t
|
||||
vs <- mapM charValue $ T.unpack body
|
||||
guard $ length vs == nameCodeLength
|
||||
let (payload, checksum) = foldl' (\acc v -> acc * toInteger base + toInteger v) 0 vs `divMod` (2 ^ nameCodeChecksumBits)
|
||||
guard $ checksum == nameCodeChecksum payload
|
||||
NameCode <$> eitherToMaybe (mkEntropy $ i2ospOf_ 16 payload)
|
||||
|
||||
formatNameCode :: NameCode -> Text
|
||||
formatNameCode (NameCode e) = T.intercalate "-" $ nameCodePrefix : T.chunksOf groupLength (T.pack $ map valueChar values)
|
||||
where
|
||||
payload = os2ip $ unEntropy e
|
||||
n = payload * 2 ^ nameCodeChecksumBits + nameCodeChecksum payload
|
||||
values = reverse $ take nameCodeLength $ map (fromInteger . (`mod` toInteger base)) $ iterate (`div` toInteger base) n
|
||||
|
||||
nameCodeEntropy :: NameCode -> WalletEntropy
|
||||
nameCodeEntropy (NameCode e) = e
|
||||
|
||||
nameCodeChecksum :: Integer -> Integer
|
||||
nameCodeChecksum = (`shiftR` (256 - nameCodeChecksumBits)) . os2ip . C.sha256Hash . i2ospOf_ 16
|
||||
@@ -16,6 +16,8 @@ import Control.Concurrent (forkIO, killThread, threadDelay)
|
||||
import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar)
|
||||
import Control.Concurrent.STM (atomically)
|
||||
import Control.Exception (SomeAsyncException, SomeException, catch, fromException, throwIO)
|
||||
import Control.Monad (forM_)
|
||||
import Data.ByteArray.Encoding (Base (Base16), convertToBase)
|
||||
import Data.ByteString.Char8 (ByteString)
|
||||
import qualified Data.ByteString.Base64.URL as B64U
|
||||
import qualified Data.ByteString.Lazy as LB
|
||||
@@ -47,6 +49,7 @@ import Simplex.Chat.Types (BoolDef (..))
|
||||
import Simplex.Messaging.Agent.Protocol (AgentErrorType (..), AgentServiceError (..), SMPAgentError (..))
|
||||
import Simplex.Messaging.Agent.RetryInterval (RetryInterval (..), nextRetryDelay)
|
||||
import Simplex.Messaging.Crypto.BBS
|
||||
import Simplex.Messaging.Crypto.BIP39 (unEntropy)
|
||||
import Simplex.Messaging.Encoding.String
|
||||
import Simplex.Messaging.Protocol (BrokerErrorType (..), ErrorType (AUTH), NetworkError (..))
|
||||
import Simplex.Messaging.Util (safeDecodeUtf8, tshow)
|
||||
@@ -72,6 +75,9 @@ badgeTests = do
|
||||
it "reads a code as typed - any case, separators, ambiguous characters" testCodeNormalisation
|
||||
it "rejects a code whose check character does not match" testCodeCheckCharacter
|
||||
it "hashes the canonical form, whatever was typed" testCodeHash
|
||||
describe "name codes" $ do
|
||||
it "encodes the entropy and its checksum" testNameCodeVectors
|
||||
it "rejects a name code with a wrong character" testNameCodeChecksum
|
||||
describe "ledger transitions" $ do
|
||||
it "issues a twelve month code one month at a time, and no thirteenth" testTwelveMonths
|
||||
it "lapses only the elapsed months after a gap, leaving paidThrough unchanged" testLapseAfterGap
|
||||
@@ -364,6 +370,25 @@ testCodeHash = do
|
||||
Just typed <- pure $ parseBadgeCode $ T.toLower $ formatBadgeCode code
|
||||
badgeCodeHash typed `shouldBe` badgeCodeHash code
|
||||
|
||||
testNameCodeVectors :: IO ()
|
||||
testNameCodeVectors =
|
||||
forM_ nameCodeVectors $ \(entropy, formatted) -> do
|
||||
let code = parseNameCode formatted
|
||||
formatNameCode <$> code `shouldBe` Just formatted
|
||||
convertToBase Base16 . unEntropy . nameCodeEntropy <$> code `shouldBe` Just entropy
|
||||
|
||||
testNameCodeChecksum :: IO ()
|
||||
testNameCodeChecksum =
|
||||
formatNameCode <$> parseNameCode "SN-KT45V-59ATD-HCNTT-EZRTA-HT8VT-8A0BV" `shouldBe` Nothing
|
||||
|
||||
-- entropy and its name code, computed by a separate Python implementation of the format
|
||||
nameCodeVectors :: [(ByteString, T.Text)]
|
||||
nameCodeVectors =
|
||||
[ ("00000000000000000000000000000000", "SN-00000-00000-00000-00000-00000-0VME2"),
|
||||
("ffffffffffffffffffffffffffffffff", "SN-ZZZZZ-ZZZZZ-ZZZZZ-ZZZZZ-ZZZZZ-XDCD9"),
|
||||
("9e885d952ad362caeb4efe34a8e91bd2", "SN-KT45V-59ATD-HCNTT-EZRTA-HT8VT-8A0BT")
|
||||
]
|
||||
|
||||
-- Ledger transitions, against plans/2026-07-30-supporter-badges-v3-ux.md §3
|
||||
|
||||
at :: Integer -> Int -> Int -> UTCTime
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
{-# LANGUAGE NamedFieldPuns #-}
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
|
||||
module Bots.BadgeService.FakeEthNode
|
||||
( FakeEthNode (..),
|
||||
withFakeEthNode,
|
||||
revertCalls,
|
||||
sentTransactions,
|
||||
fakeGas,
|
||||
fakeTip,
|
||||
fakeBaseFee,
|
||||
)
|
||||
where
|
||||
|
||||
import Control.Concurrent.STM
|
||||
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.ByteString (ByteString)
|
||||
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 Network.Wai (Application, responseLBS, strictRequestBody)
|
||||
import qualified Network.Wai.Handler.Warp as Warp
|
||||
import Numeric (showHex)
|
||||
import Simplex.Messaging.Crypto (keccak256)
|
||||
import Simplex.Messaging.Util (eitherToMaybe)
|
||||
|
||||
data FakeEthNode = FakeEthNode
|
||||
{ fnUrl :: String,
|
||||
fnManager :: Manager,
|
||||
fnState :: TVar FakeState
|
||||
}
|
||||
|
||||
data FakeState = FakeState
|
||||
{ fsRevert :: Bool,
|
||||
fsSent :: [ByteString]
|
||||
}
|
||||
|
||||
fakeGas, fakeTip, fakeBaseFee :: Num a => a
|
||||
fakeGas = 200000
|
||||
fakeTip = 1000000000
|
||||
fakeBaseFee = 2000000000
|
||||
|
||||
withFakeEthNode :: (FakeEthNode -> IO a) -> IO a
|
||||
withFakeEthNode action = do
|
||||
fnState <- newTVarIO FakeState {fsRevert = False, fsSent = []}
|
||||
fnManager <- HTTP.newManager HTTP.defaultManagerSettings
|
||||
Warp.testWithApplication (pure $ fakeApp fnState) $ \port ->
|
||||
action FakeEthNode {fnUrl = "http://127.0.0.1:" <> show port, fnManager, fnState}
|
||||
|
||||
revertCalls :: FakeEthNode -> IO ()
|
||||
revertCalls FakeEthNode {fnState} = atomically $ modifyTVar' fnState $ \s -> s {fsRevert = True}
|
||||
|
||||
sentTransactions :: FakeEthNode -> IO [ByteString]
|
||||
sentTransactions FakeEthNode {fnState} = 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
|
||||
Nothing -> respond $ responseLBS badRequest400 [] "not a JSON-RPC request"
|
||||
where
|
||||
request = J.withObject "request" $ \o -> (,) <$> o .: "method" <*> o .: "params"
|
||||
|
||||
answer :: TVar FakeState -> Text -> [J.Value] -> STM [JT.Pair]
|
||||
answer st method params = do
|
||||
s@FakeState {fsRevert, fsSent} <- 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)]]
|
||||
where
|
||||
result v = ["result" .= v]
|
||||
reverted = ["error" .= J.object ["code" .= (3 :: Int), "message" .= ("execution reverted" :: Text)]]
|
||||
|
||||
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
|
||||
@@ -0,0 +1,161 @@
|
||||
{-# LANGUAGE NamedFieldPuns #-}
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
|
||||
module Bots.BadgeService.NameRegistrationTests (badgeNameRegistrationTests) where
|
||||
|
||||
import BadgeService.Names.Chain
|
||||
import BadgeService.Names.Registration
|
||||
import Bots.BadgeService.FakeEthNode
|
||||
import Bots.BadgeService.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.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)
|
||||
import Simplex.Messaging.Eth.Transaction (Eip1559Tx (..), signEip1559Tx)
|
||||
import Simplex.Messaging.SimplexName (SimplexTLD (..))
|
||||
import Test.Hspec
|
||||
|
||||
badgeNameRegistrationTests :: Spec
|
||||
badgeNameRegistrationTests = describe "badge service name registration" $ do
|
||||
g <- runIO C.newRandom
|
||||
-- expected encodings and signatures are viem's, against the SimplexController, SimplexSponsor and SimplexResolver ABIs
|
||||
describe "encoding" $ do
|
||||
it "encodes registerWithCredit with records" $ testRegisterCalldataWithRecords g
|
||||
it "encodes registerWithCredit without records" $ testRegisterCalldataWithoutRecords g
|
||||
it "encodes commit with the commitment of a registration" testCommitCalldata
|
||||
describe "verifying the register intent" $ 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 "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"
|
||||
|
||||
testRegisterCalldataWithoutRecords :: TVar ChaChaDRG -> IO ()
|
||||
testRegisterCalldataWithoutRecords g = do
|
||||
intent <- knownIntent g knownRegistration {rContactLinks = [], rChannelLinks = []}
|
||||
toHex (registerWithCreditCalldata intent)
|
||||
`shouldBe` "c4bd2ab50000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f486570000000000000000000000000000000000000000000000000000000000000001e000000000000000000000000000000000000000000000000000000000000001000000000000000000000000009858effd232b4033e47d90003d41ec34ecaeda940000000000000000000000000000000000000000000000000000000003c2670011111111111111111111111111111111111111111111111111111111111111110000000000000000000000002279b7a0a67db372996a5fab50d91eaa73d2ebe6000000000000000000000000000000000000000000000000000000000000014000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000762616b6572793100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000411d0b3a477c99fbcadada2937b71127bf6da202f5cd25856649829653d8cf6a8c0ce0afb8505e398e23b3b01fcb3b17ffcf82d8ba6d24e9b854506894b2864ecf1c00000000000000000000000000000000000000000000000000000000000000"
|
||||
|
||||
testCommitCalldata :: IO ()
|
||||
testCommitCalldata =
|
||||
toHex (commitCalldata $ makeCommitment knownRegistration) `shouldBe` "f14fcbc843aeb4617085160f4dc7ad495d1119f39bca441276b1990123fd3ecb8a40a360"
|
||||
|
||||
testVerifyOtherSigner :: TVar ChaChaDRG -> IO ()
|
||||
testVerifyOtherSigner g = do
|
||||
other <- newEphemeralWallet g
|
||||
intent <- signRegisterIntent g domain other knownRegistration deadline
|
||||
verifyRegisterIntent domain deadline intent `shouldReturn` Left "intent is not signed by the owner"
|
||||
|
||||
testVerifyExpired :: TVar ChaChaDRG -> IO ()
|
||||
testVerifyExpired g = do
|
||||
intent <- knownIntent g knownRegistration
|
||||
verifyRegisterIntent domain (deadline + 1) intent `shouldReturn` Left "intent expired"
|
||||
|
||||
testVerifyShortSecret :: TVar ChaChaDRG -> IO ()
|
||||
testVerifyShortSecret g = do
|
||||
intent <- knownIntent g knownRegistration {rSecret = B.replicate 31 0x11}
|
||||
verifyRegisterIntent domain deadline intent `shouldReturn` Left "secret: expected 32 bytes"
|
||||
|
||||
testRevertedDryRun :: TVar ChaChaDRG -> IO ()
|
||||
testRevertedDryRun g = withFakeEthNode $ \node -> do
|
||||
revertCalls node
|
||||
intent <- knownIntent g knownRegistration
|
||||
sendRegister g (chainClient node) intent `shouldReturn` Left (ChainError "execution reverted")
|
||||
sentTransactions node `shouldReturn` []
|
||||
|
||||
testCommitThenRegister :: TVar ChaChaDRG -> IO ()
|
||||
testCommitThenRegister g = withFakeEthNode $ \node -> do
|
||||
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)
|
||||
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)
|
||||
|
||||
-- fixtures
|
||||
|
||||
knownRegistration :: Registration
|
||||
knownRegistration =
|
||||
Registration
|
||||
{ rLabel = "bakery1",
|
||||
rTLD = TLDSimplex,
|
||||
rOwner = address "0x9858EfFD232B4033E47d90003D41EC34EcaEda94",
|
||||
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"]
|
||||
}
|
||||
|
||||
knownIntent :: TVar ChaChaDRG -> Registration -> IO RegisterIntent
|
||||
knownIntent g r = do
|
||||
w <- walletFromCode g knownCode
|
||||
signRegisterIntent g domain w r deadline
|
||||
|
||||
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
|
||||
|
||||
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
|
||||
Eip1559Tx
|
||||
{ txChainId = chainId,
|
||||
txNonce = nonce,
|
||||
txMaxPriorityFeePerGas = fakeTip,
|
||||
txMaxFeePerGas = 2 * fakeBaseFee + fakeTip,
|
||||
txGasLimit = fakeGas,
|
||||
txTo = to,
|
||||
txValue = 0,
|
||||
txData = calldata
|
||||
}
|
||||
|
||||
address :: ByteString -> Address
|
||||
address = right . strDecode
|
||||
|
||||
toHex :: ByteString -> ByteString
|
||||
toHex = convertToBase Base16
|
||||
|
||||
right :: Either String a -> a
|
||||
right = either (error . ("unexpected Left: " <>)) id
|
||||
@@ -0,0 +1,52 @@
|
||||
{-# LANGUAGE NamedFieldPuns #-}
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
|
||||
module Bots.BadgeService.WebUIMock
|
||||
( EphemeralWallet (..),
|
||||
newEphemeralWallet,
|
||||
redemptionCode,
|
||||
walletFromCode,
|
||||
signRegisterIntent,
|
||||
)
|
||||
where
|
||||
|
||||
import BadgeService.Names.Registration (RegisterIntent (..), Registration, registerIntentDigest)
|
||||
import Control.Concurrent.STM (TVar)
|
||||
import Crypto.Random (ChaChaDRG)
|
||||
import Data.Text (Text)
|
||||
import Data.Word (Word64)
|
||||
import Simplex.Chat.Badges.Code (NameCode, formatNameCode, nameCodeEntropy, parseNameCode, randomNameCode)
|
||||
import Simplex.Messaging.Crypto.BIP32 (masterKey, xkKey)
|
||||
import Simplex.Messaging.Crypto.BIP39 (entropySeed)
|
||||
import Simplex.Messaging.Crypto.BIP44 (CoinType (..), bip44Path, mkAccountIndex)
|
||||
import Simplex.Messaging.Crypto.Secp256k1 (Secp256k1PrivateKey, signRecoverable)
|
||||
import Simplex.Messaging.Eth.Address (Address, deriveAddress)
|
||||
import Simplex.Messaging.Eth.EIP712 (Eip712Domain)
|
||||
|
||||
data EphemeralWallet = EphemeralWallet
|
||||
{ ewCode :: NameCode,
|
||||
ewKey :: Secp256k1PrivateKey,
|
||||
ewAddress :: Address
|
||||
}
|
||||
|
||||
newEphemeralWallet :: TVar ChaChaDRG -> IO EphemeralWallet
|
||||
newEphemeralWallet g = randomNameCode g >>= walletFromNameCode g
|
||||
|
||||
redemptionCode :: EphemeralWallet -> Text
|
||||
redemptionCode = formatNameCode . ewCode
|
||||
|
||||
walletFromCode :: TVar ChaChaDRG -> Text -> IO EphemeralWallet
|
||||
walletFromCode g = maybe (fail "invalid name code") (walletFromNameCode g) . parseNameCode
|
||||
|
||||
signRegisterIntent :: TVar ChaChaDRG -> Eip712Domain -> EphemeralWallet -> Registration -> Word64 -> IO RegisterIntent
|
||||
signRegisterIntent g domain EphemeralWallet {ewKey} r deadline =
|
||||
RegisterIntent r nonce deadline <$> (signRecoverable g ewKey (registerIntentDigest domain r nonce deadline) >>= either fail pure)
|
||||
where
|
||||
nonce = 0
|
||||
|
||||
walletFromNameCode :: TVar ChaChaDRG -> NameCode -> IO EphemeralWallet
|
||||
walletFromNameCode g ewCode = do
|
||||
master <- either fail pure $ masterKey $ entropySeed (nameCodeEntropy ewCode) ""
|
||||
account <- either fail pure $ mkAccountIndex 0
|
||||
(xk, ewAddress) <- deriveAddress g master (bip44Path Ethereum account) >>= either fail pure
|
||||
pure EphemeralWallet {ewCode, ewKey = xkKey xk, ewAddress}
|
||||
@@ -9,6 +9,7 @@ import Bots.BadgeService.CatalogTests
|
||||
import Bots.BadgeService.ConfigTests
|
||||
import Bots.BadgeService.GroupIntegrationTests
|
||||
import Bots.BadgeService.GroupTests
|
||||
import Bots.BadgeService.NameRegistrationTests
|
||||
import Bots.BadgeService.StoreVerifierTests
|
||||
import Bots.BadgeService.StripeTests
|
||||
import Bots.BadgeService.WaitersTests
|
||||
@@ -86,6 +87,7 @@ main = do
|
||||
badgeWaitersTests
|
||||
badgeBTCPayTests
|
||||
badgeStripeTests
|
||||
badgeNameRegistrationTests
|
||||
badgeStoreVerifierTests
|
||||
describe "SimpleX chat markdown" markdownTests
|
||||
describe "JSON Tests" jsonTests
|
||||
|
||||
Reference in new issue
Block a user