names-web example code to register names from web UI

This commit is contained in:
Alain Brenzikofer authored and Evgeny committed 2026-10-14 15:43:46 +01:00
1 parent 4e6f558614
commit 4eafc41c80
17 files changed
+642

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
node_modules/
dist/
dist-web/
package-lock.json
test-results/
+31
View File
@@ -0,0 +1,31 @@
# names-web
Prototype page for buying a SimpleX name in the browser, without a wallet extension. It makes a wallet for the name, shows its redemption code, and prepares the two requests the store service sends to the chain: the commitment to commit, and the registration with the owner's signed `RegisterName` intent.
## Setup
```bash
cd names-web
npm install
npm run build
```
## Running tests
```bash
# The TypeScript output against the Haskell implementation (from repo root)
cabal test --test-option=--match="/Names Web/"
# The page in headless Chromium
cd names-web && npm run test:page
# Also register the page's name on a hardhat node running the contracts,
# from a compiled checkout of ens-contracts PR #35
ENS_CONTRACTS_DIR=../path/to/ens-contracts npm run test:page
```
## Development
```bash
npm run dev
```
+26
View File
@@ -0,0 +1,26 @@
{
"name": "@simplex-chat/names-web",
"version": "0.1.0",
"description": "SimpleX names purchase page: wallet, redemption code and signed registration intent in the browser",
"license": "AGPL-3.0-only",
"private": true,
"type": "module",
"scripts": {
"build": "tsc",
"dev": "vite",
"test:page": "playwright test"
},
"devDependencies": {
"@playwright/test": "^1.50.0",
"@types/node": "^20.0.0",
"typescript": "^5.4.0",
"viem": "^2.57.5",
"vite": "^6.0.0"
},
"dependencies": {
"@noble/curves": "^1.9.7",
"@noble/hashes": "^1.8.0",
"@scure/bip32": "^1.7.0",
"@scure/bip39": "^1.6.0"
}
}
+15
View File
@@ -0,0 +1,15 @@
import {defineConfig} from "@playwright/test"
const ensContractsDir = process.env.ENS_CONTRACTS_DIR
export default defineConfig({
testDir: "./test",
use: {baseURL: "http://localhost:4173"},
webServer: [
{
command: "npx vite build && npx vite preview",
url: "http://localhost:4173",
},
...(ensContractsDir ? [{command: "npx hardhat node --port 8645", cwd: ensContractsDir, port: 8645}] : []),
],
})
+42
View File
@@ -0,0 +1,42 @@
import {sha256} from "@noble/hashes/sha2"
import {bytesToNumberBE, numberToBytesBE} from "@noble/curves/utils"
const ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
const PREFIX = "SN"
const CODE_LENGTH = 30
const CHECKSUM_BITS = 22n
const ENTROPY_BYTES = 16
export function formatNameCode(entropy: Uint8Array): string {
let n = (bytesToNumberBE(entropy) << CHECKSUM_BITS) + checksum(entropy)
let body = ""
for (let i = 0; i < CODE_LENGTH; i++) {
body = ALPHABET[Number(n % 32n)] + body
n /= 32n
}
return [PREFIX, ...body.match(/.{5}/g)!].join("-")
}
export function parseNameCode(code: string): Uint8Array | null {
const cleaned = code.replace(/[^\p{L}\p{N}]/gu, "").toUpperCase()
if (!cleaned.startsWith(PREFIX) || cleaned.length !== PREFIX.length + CODE_LENGTH) return null
let n = 0n
for (const c of cleaned.slice(PREFIX.length)) {
const v = charValue(c)
if (v === undefined) return null
n = n * 32n + BigInt(v)
}
const entropy = numberToBytesBE(n >> CHECKSUM_BITS, ENTROPY_BYTES)
return n % (1n << CHECKSUM_BITS) === checksum(entropy) ? entropy : null
}
function charValue(c: string): number | undefined {
if (c === "I" || c === "L") return 1
if (c === "O") return 0
const v = ALPHABET.indexOf(c)
return v < 0 ? undefined : v
}
function checksum(entropy: Uint8Array): bigint {
return bytesToNumberBE(sha256(entropy)) >> (256n - CHECKSUM_BITS)
}
+109
View File
@@ -0,0 +1,109 @@
import {concatBytes, numberToBytesBE, utf8ToBytes} from "@noble/curves/utils"
import {keccak_256} from "@noble/hashes/sha3"
export interface Registration {
label: string
tld: string
owner: Uint8Array
duration: bigint
secret: Uint8Array
resolver: Uint8Array
contactLinks: string[]
channelLinks: string[]
}
export function makeCommitment(r: Registration): Uint8Array {
return keccak_256(abiTuple([dynamic(registrationTuple(r))]))
}
export function registerIntentDigest(chainId: bigint, sponsor: Uint8Array, r: Registration, nonce: bigint, deadline: bigint): Uint8Array {
const domain = hashStruct("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)", [
keccak_256(utf8ToBytes("SimplexSponsor")),
keccak_256(utf8ToBytes("1")),
uint256(chainId),
addressWord(sponsor),
])
const intent = hashStruct("RegisterName(string label,address owner,address resolver,bytes[] data,uint256 nonce,uint256 deadline)", [
keccak_256(utf8ToBytes(r.label)),
addressWord(r.owner),
addressWord(r.resolver),
keccak_256(concatBytes(...recordCalls(r).map(keccak_256))),
uint256(nonce),
uint256(deadline),
])
return keccak_256(concatBytes(new Uint8Array([0x19, 0x01]), domain, intent))
}
function hashStruct(typeString: string, words: Uint8Array[]): Uint8Array {
return keccak_256(concatBytes(keccak_256(utf8ToBytes(typeString)), ...words))
}
function registrationTuple(r: Registration): Uint8Array {
return abiTuple([
dynamic(abiBytes(utf8ToBytes(r.label))),
fixed(addressWord(r.owner)),
fixed(uint256(r.duration)),
fixed(r.secret),
fixed(addressWord(r.resolver)),
dynamic(abiArray(recordCalls(r).map(abiBytes))),
fixed(uint256(0n)),
fixed(new Uint8Array(32)),
])
}
function recordCalls(r: Registration): Uint8Array[] {
const node = namehash(r.tld, r.label)
const records: [string, string[]][] = [["simplex.contact", r.contactLinks], ["simplex.channel", r.channelLinks]]
return records
.filter(([, links]) => links.length > 0)
.map(([key, links]) =>
concatBytes(
selector("setText(bytes32,string,string)"),
abiTuple([fixed(node), dynamic(abiBytes(utf8ToBytes(key))), dynamic(abiBytes(utf8ToBytes(links.join(";"))))]),
),
)
}
function namehash(tld: string, label: string): Uint8Array {
const tldNode = keccak_256(concatBytes(new Uint8Array(32), keccak_256(utf8ToBytes(tld))))
return keccak_256(concatBytes(tldNode, keccak_256(utf8ToBytes(label))))
}
interface AbiValue {
dynamic: boolean
bytes: Uint8Array
}
const fixed = (bytes: Uint8Array): AbiValue => ({dynamic: false, bytes})
const dynamic = (bytes: Uint8Array): AbiValue => ({dynamic: true, bytes})
function abiTuple(values: AbiValue[]): Uint8Array {
let offset = 32 * values.length
const heads = values.map(v => {
if (!v.dynamic) return v.bytes
const head = uint256(BigInt(offset))
offset += v.bytes.length
return head
})
return concatBytes(...heads, ...values.filter(v => v.dynamic).map(v => v.bytes))
}
function abiBytes(bytes: Uint8Array): Uint8Array {
return concatBytes(uint256(BigInt(bytes.length)), bytes, new Uint8Array((32 - (bytes.length % 32)) % 32))
}
function abiArray(items: Uint8Array[]): Uint8Array {
return concatBytes(uint256(BigInt(items.length)), abiTuple(items.map(dynamic)))
}
function uint256(n: bigint): Uint8Array {
return numberToBytesBE(n, 32)
}
function addressWord(address: Uint8Array): Uint8Array {
return concatBytes(new Uint8Array(12), address)
}
function selector(signature: string): Uint8Array {
return keccak_256(utf8ToBytes(signature)).slice(0, 4)
}
+23
View File
@@ -0,0 +1,23 @@
import {secp256k1} from "@noble/curves/secp256k1"
import {keccak_256} from "@noble/hashes/sha3"
import {HDKey} from "@scure/bip32"
import {entropyToMnemonic, mnemonicToSeedSync} from "@scure/bip39"
import {wordlist} from "@scure/bip39/wordlists/english"
export interface Wallet {
entropy: Uint8Array
privateKey: Uint8Array
address: Uint8Array
}
export function walletFromEntropy(entropy: Uint8Array): Wallet {
const seed = mnemonicToSeedSync(entropyToMnemonic(entropy, wordlist))
const privateKey = HDKey.fromMasterSeed(seed).derive("m/44'/60'/0'/0/0").privateKey!
const address = keccak_256(secp256k1.getPublicKey(privateKey, false).slice(1)).slice(12)
return {entropy, privateKey, address}
}
export function signDigest(privateKey: Uint8Array, digest: Uint8Array): Uint8Array {
const sig = secp256k1.sign(digest, privateKey)
return new Uint8Array([...sig.toBytes("compact"), 27 + sig.recovery])
}
+126
View File
@@ -0,0 +1,126 @@
import {expect, test} from "@playwright/test"
import {readFileSync} from "node:fs"
import {join} from "node:path"
import {
bytesToHex,
createPublicClient,
createWalletClient,
encodeFunctionData,
getAddress,
http,
labelhash,
namehash,
zeroAddress,
zeroHash,
type Abi,
type Address,
} from "viem"
import {hardhat} from "viem/chains"
import {resolver as pageResolver, sponsor as pageSponsor} from "../web/config"
interface Contract {
address: Address
abi: Abi
}
const ensContractsDir = process.env.ENS_CONTRACTS_DIR
const transport = http("http://127.0.0.1:8645")
const publicClient = createPublicClient({chain: hardhat, transport})
const walletClient = createWalletClient({chain: hardhat, transport})
test.skip(!ensContractsDir, "set ENS_CONTRACTS_DIR to a compiled checkout of ens-contracts PR #35")
test("registers the page's name through the sponsor on a hardhat node", async ({page}) => {
const [owner, guardian, registrar] = await walletClient.getAddresses()
const {baseRegistrar, controller, resolver, sponsor} = await deployNames(owner, guardian)
expect(sponsor.address).toBe(getAddress(bytesToHex(pageSponsor)))
expect(resolver.address).toBe(getAddress(bytesToHex(pageResolver)))
await write(guardian, sponsor, "setRegistrarAllowance", [registrar, 1000n * 10n ** 18n])
await page.goto("/")
await page.locator("#label").fill("bakery1")
await page.locator("#contact").fill("https://smp.simplex.im/a#contact")
await page.locator("#channel").fill("https://smp1.simplex.im/c#one\nhttps://smp2.simplex.im/c#two")
await page.locator("#register").click()
const {commitment} = JSON.parse(await page.locator("#commit-request").innerText())
const request = JSON.parse(await page.locator("#register-request").innerText())
await write(registrar, controller, "commit", [commitment])
const node = namehash(`${request.label}.${request.tld}`)
const records: [string, string[]][] = [["simplex.contact", request.contactLinks], ["simplex.channel", request.channelLinks]]
const data = records
.filter(([, links]) => links.length > 0)
.map(([key, links]) => encodeFunctionData({abi: resolver.abi, functionName: "setText", args: [node, key, links.join(";")]}))
const registration = {
label: request.label,
owner: request.owner,
duration: BigInt(request.duration),
secret: request.secret,
resolver: request.resolver,
data,
reverseRecord: 0,
referrer: zeroHash,
}
await write(registrar, sponsor, "registerWithCredit", [registration, BigInt(request.nonce), BigInt(request.deadline), request.signature])
expect(await read(baseRegistrar, "ownerOf", [BigInt(labelhash(request.label))])).toBe(getAddress(request.owner))
expect(await read(resolver, "text", [node, "simplex.contact"])).toBe("https://smp.simplex.im/a#contact")
expect(await read(resolver, "text", [node, "simplex.channel"])).toBe("https://smp1.simplex.im/c#one;https://smp2.simplex.im/c#two")
})
async function deployNames(owner: Address, guardian: Address) {
const tldNode = namehash("simplex")
const ens = await deploy(owner, "registry/ENSRegistry.sol/ENSRegistry.json", [])
const baseRegistrar = await deploy(owner, "ethregistrar/BaseRegistrarImplementation.sol/BaseRegistrarImplementation.json", [ens.address, tldNode])
await write(owner, ens, "setSubnodeOwner", [zeroHash, labelhash("simplex"), baseRegistrar.address])
const dummyOracle = await deploy(owner, "ethregistrar/DummyOracle.sol/DummyOracle.json", [100000000n])
const priceOracle = await deploy(owner, "simplex/SimplexPriceOracle.sol/SimplexPriceOracle.json", [dummyOracle.address, 8, 1000n, []])
const implementation = await deploy(owner, "simplex/SimplexController.sol/SimplexController.json", [])
const initData = encodeFunctionData({
abi: implementation.abi,
functionName: "initialize",
args: [
baseRegistrar.address,
priceOracle.address,
1n,
86400n,
ens.address,
{tldNode, tldSuffix: ".simplex", minCharLength: 6, smpxNft: zeroAddress, nftGateEnabled: false},
owner,
],
})
const proxy = await deploy(owner, "simplex/SimplexControllerProxy.sol/SimplexControllerProxy.json", [implementation.address, initData])
const controller = {address: proxy.address, abi: implementation.abi}
const subnameRegistrar = await deploy(owner, "simplex/SubnameRegistrar.sol/SubnameRegistrar.json", [ens.address, baseRegistrar.address])
const resolver = await deploy(owner, "simplex/SimplexResolver.sol/SimplexResolver.json", [
ens.address,
subnameRegistrar.address,
controller.address,
zeroAddress,
])
await write(owner, subnameRegistrar, "setResolver", [resolver.address])
await write(owner, baseRegistrar, "addController", [controller.address])
await write(owner, baseRegistrar, "setSubnameHook", [subnameRegistrar.address])
await write(owner, controller, "setDefaultResolver", [resolver.address])
await write(owner, controller, "setBeneficiary", [guardian])
const sponsor = await deploy(owner, "simplex/SimplexSponsor.sol/SimplexSponsor.json", [controller.address])
await write(owner, controller, "setSponsor", [sponsor.address])
return {baseRegistrar, controller, resolver, sponsor}
}
async function deploy(from: Address, artifact: string, args: unknown[]): Promise<Contract> {
const {abi, bytecode} = JSON.parse(readFileSync(join(ensContractsDir!, "artifacts/contracts", artifact), "utf8"))
const hash = await walletClient.deployContract({account: from, abi, bytecode, args})
const {contractAddress} = await publicClient.waitForTransactionReceipt({hash})
return {address: getAddress(contractAddress!), abi}
}
async function write(from: Address, contract: Contract, functionName: string, args: unknown[]): Promise<void> {
const hash = await walletClient.writeContract({account: from, ...contract, functionName, args})
expect((await publicClient.waitForTransactionReceipt({hash})).status).toBe("success")
}
function read(contract: Contract, functionName: string, args: unknown[]): Promise<unknown> {
return publicClient.readContract({...contract, functionName, args})
}
+33
View File
@@ -0,0 +1,33 @@
import {expect, test} from "@playwright/test"
import {bytesToHex, hexToBytes} from "viem"
import {parseNameCode} from "../src/code"
import {makeCommitment, registerIntentDigest, type Registration} from "../src/registration"
import {signDigest, walletFromEntropy} from "../src/wallet"
import {chainId, sponsor} from "../web/config"
test("prepares a commitment and a registration signed by the code's wallet", async ({page}) => {
await page.goto("/")
const code = await page.locator("#code").innerText()
await page.locator("#label").fill("bakery1")
await page.locator("#contact").fill("https://smp.simplex.im/a#contact")
await page.locator("#channel").fill("https://smp1.simplex.im/c#one\nhttps://smp2.simplex.im/c#two")
await page.locator("#register").click()
const {commitment} = JSON.parse(await page.locator("#commit-request").innerText())
const request = JSON.parse(await page.locator("#register-request").innerText())
const wallet = walletFromEntropy(parseNameCode(code)!)
expect(request.owner).toBe(bytesToHex(wallet.address))
expect(request.channelLinks).toEqual(["https://smp1.simplex.im/c#one", "https://smp2.simplex.im/c#two"])
const registration: Registration = {
...request,
owner: hexToBytes(request.owner),
duration: BigInt(request.duration),
secret: hexToBytes(request.secret),
resolver: hexToBytes(request.resolver),
}
expect(bytesToHex(makeCommitment(registration))).toBe(commitment)
const digest = registerIntentDigest(chainId, sponsor, registration, BigInt(request.nonce), BigInt(request.deadline))
expect(request.signature).toBe(bytesToHex(signDigest(wallet.privateKey, digest)))
})
+16
View File
@@ -0,0 +1,16 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ES2022",
"moduleResolution": "node",
"lib": ["ES2022"],
"outDir": "dist",
"rootDir": "src",
"declaration": true,
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*.ts"]
}
+6
View File
@@ -0,0 +1,6 @@
import {defineConfig} from "vite"
export default defineConfig({
root: "web",
build: {outDir: "../dist-web", emptyOutDir: true},
})
+7
View File
@@ -0,0 +1,7 @@
import {hexToBytes} from "@noble/curves/utils"
export const chainId = 31337n
export const sponsor = hexToBytes("9a676e781a523b5d0c0e43731313a708cb607508")
export const resolver = hexToBytes("2279b7a0a67db372996a5fab50d91eaa73d2ebe6")
export const tld = "simplex"
export const duration = 2n * 365n * 24n * 3600n
+22
View File
@@ -0,0 +1,22 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Security-Policy" content="default-src 'self'">
<title>SimpleX Names</title>
</head>
<body>
<h1>SimpleX Names</h1>
<p>Your redemption code: <code id="code"></code></p>
<p><label>Name <input id="label"></label></p>
<p><label>Contact links, one per line <textarea id="contact"></textarea></label></p>
<p><label>Channel links, one per line <textarea id="channel"></textarea></label></p>
<p><button id="register">Register</button></p>
<h2>Commit request</h2>
<pre id="commit-request"></pre>
<h2>Register request</h2>
<pre id="register-request"></pre>
<script type="module" src="./main.ts"></script>
</body>
</html>
+41
View File
@@ -0,0 +1,41 @@
import {bytesToHex} from "@noble/curves/utils"
import {formatNameCode} from "../src/code"
import {makeCommitment, registerIntentDigest, type Registration} from "../src/registration"
import {signDigest, walletFromEntropy} from "../src/wallet"
import {chainId, duration, resolver, sponsor, tld} from "./config"
const wallet = walletFromEntropy(crypto.getRandomValues(new Uint8Array(16)))
element("code").textContent = formatNameCode(wallet.entropy)
element("register").addEventListener("click", () => {
const registration: Registration = {
label: (element("label") as HTMLInputElement).value,
tld,
owner: wallet.address,
duration,
secret: crypto.getRandomValues(new Uint8Array(32)),
resolver,
contactLinks: lines("contact"),
channelLinks: lines("channel"),
}
const nonce = 0n
const deadline = BigInt(Math.floor(Date.now() / 1000) + 3600)
const signature = signDigest(wallet.privateKey, registerIntentDigest(chainId, sponsor, registration, nonce, deadline))
element("commit-request").textContent = json({commitment: makeCommitment(registration)})
element("register-request").textContent = json({...registration, nonce, deadline, signature})
})
function element(id: string): HTMLElement {
return document.getElementById(id)!
}
function lines(id: string): string[] {
return (element(id) as HTMLTextAreaElement).value
.split("\n")
.map(line => line.trim())
.filter(line => line !== "")
}
function json(request: object): string {
return JSON.stringify(request, (_, v) => (v instanceof Uint8Array ? "0x" + bytesToHex(v) : typeof v === "bigint" ? v.toString() : v), 2)
}
+1
View File
@@ -595,6 +595,7 @@ test-suite simplexmq-test
XFTPServerTests
WebTests
XFTPWebTests
NamesWebTests
SMPWeb
XFTPWeb
Web.Embedded
+137
View File
@@ -0,0 +1,137 @@
{-# LANGUAGE OverloadedStrings #-}
-- | Tests for the names-web TypeScript code: each test runs it via node and compares its output with the Haskell functions it must match.
--
-- Prerequisites: cd names-web && npm install && npm run build
module NamesWebTests (namesWebTests) where
import Control.Concurrent.STM (TVar, atomically)
import Control.Monad (forM_, replicateM, replicateM_)
import Crypto.Random (ChaChaDRG)
import qualified Data.ByteArray as BA
import qualified Data.ByteArray.Encoding as BAE
import Data.Bifunctor (first)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as BC
import Data.Char (toLower)
import Data.List (intercalate)
import Data.Word (Word64)
import qualified Simplex.Messaging.Crypto as C
import Simplex.Messaging.Crypto.BIP32 (masterKey, xkKey)
import Simplex.Messaging.Crypto.BIP39 (EntropyStrength (..), WalletEntropy, entropySeed, randomEntropy, unEntropy)
import Simplex.Messaging.Crypto.BIP44 (CoinType (..), bip44Path, mkAccountIndex)
import qualified Simplex.Messaging.Crypto.Secp256k1 as S
import Simplex.Messaging.Encoding.String (strDecode)
import Simplex.Messaging.Eth.Address (Address, deriveAddress, unAddress)
import Simplex.Messaging.Eth.EIP712
import System.Directory (doesDirectoryExist)
import System.Random (randomIO)
import System.Process (CreateProcess (..), proc, readCreateProcess)
import Test.Hspec hiding (fit, it)
import Util
namesWebDir :: FilePath
namesWebDir = "names-web"
namesWebTests :: Spec
namesWebTests = do
distExists <- runIO $ doesDirectoryExist (namesWebDir <> "/dist")
if distExists
then do
g <- runIO C.newRandom
it "derives the wallet address from the entropy as Haskell does" $ testWalletAddress g
it "signs a digest as Haskell does" $ testSignature g
it "hashes the RegisterName intent as Haskell does" testIntentDigest
it "formats and parses the simplex-chat name codes" testNameCodes
it "encodes the simplex-chat registration vectors" testChatVectors
else
it "skipped (run 'cd names-web && npm install && npm run build' first)" $
pendingWith "TS project not compiled"
testWalletAddress :: TVar ChaChaDRG -> IO ()
testWalletAddress g =
replicateM_ 5 $ do
entropy <- atomically $ randomEntropy ES128 g
(_, addr) <- wallet g entropy
callNode ("walletFromEntropy(" <> jsUint8 (BA.convert $ unEntropy entropy) <> ").address") `shouldReturn` hex (unAddress addr)
testSignature :: TVar ChaChaDRG -> IO ()
testSignature g =
replicateM_ 5 $ do
entropy <- atomically $ randomEntropy ES128 g
(key, _) <- wallet g entropy
digest <- atomically $ C.randomBytes 32 g
signature <- either error id <$> S.signRecoverable g key digest
callNode ("signDigest(walletFromEntropy(" <> jsUint8 (BA.convert $ unEntropy entropy) <> ").privateKey, " <> jsUint8 digest <> ")")
`shouldReturn` hex (serializeSignature signature)
testIntentDigest :: IO ()
testIntentDigest =
replicateM_ 5 $ do
[owner, resolver, sponsor] <- replicateM 3 $ B.pack <$> replicateM 20 randomIO
chainId <- randomIO :: IO Word64
nonce <- randomIO :: IO Word64
deadline <- randomIO :: IO Word64
let domain = Eip712Domain {edName = "SimplexSponsor", edVersion = "1", edChainId = chainId, edVerifyingContract = address sponsor}
registration =
"{label: 'bakery1', tld: 'simplex', owner: " <> jsUint8 owner <> ", duration: 0n, secret: new Uint8Array(32), resolver: "
<> jsUint8 resolver <> ", contactLinks: [], channelLinks: []}"
callNode ("registerIntentDigest(" <> show chainId <> "n, " <> jsUint8 sponsor <> ", " <> registration <> ", " <> show nonce <> "n, " <> show deadline <> "n)")
`shouldReturn` hex
( hashTypedData
domain
"RegisterName(string label,address owner,address resolver,bytes[] data,uint256 nonce,uint256 deadline)"
[VBytes "bakery1", VAddress $ address owner, VAddress $ address resolver, VArray [], VUint $ fromIntegral nonce, VUint $ fromIntegral deadline]
)
testNameCodes :: IO ()
testNameCodes =
forM_
[ ("00000000000000000000000000000000", "SN-00000-00000-00000-00000-00000-0VME2"),
("ffffffffffffffffffffffffffffffff", "SN-ZZZZZ-ZZZZZ-ZZZZZ-ZZZZZ-ZZZZZ-XDCD9"),
("9e885d952ad362caeb4efe34a8e91bd2", "SN-KT45V-59ATD-HCNTT-EZRTA-HT8VT-8A0BT")
]
$ \(entropy, code) -> do
callNode ("formatNameCode(" <> jsHex entropy <> ")") `shouldReturn` BC.pack code
callNode ("parseNameCode('" <> map toLower code <> "')") `shouldReturn` BC.pack entropy
testChatVectors :: IO ()
testChatVectors = do
callNode ("makeCommitment(" <> knownRegistration <> ")") `shouldReturn` "43aeb4617085160f4dc7ad495d1119f39bca441276b1990123fd3ecb8a40a360"
callNode ("signDigest(walletFromEntropy(new Uint8Array(16)).privateKey, registerIntentDigest(31337n, " <> jsHex "9a676e781a523b5d0c0e43731313a708cb607508" <> ", " <> knownRegistration <> ", 0n, 4102444800n))")
`shouldReturn` "74af637cf246cd336c3713f95fd9ed19862971598fcab5f4fb5d044ed033a3854c2ce30ffd36c25ed5f9a8ef691d004b3662f3553113403416f658d9c604732b1b"
where
knownRegistration =
"{label: 'bakery1', tld: 'simplex', owner: walletFromEntropy(new Uint8Array(16)).address, duration: 63072000n, secret: new Uint8Array(32).fill(0x11), resolver: "
<> jsHex "2279b7a0a67db372996a5fab50d91eaa73d2ebe6"
<> ", contactLinks: ['https://smp.simplex.im/a#contact'], channelLinks: ['https://smp1.simplex.im/c#one', 'https://smp2.simplex.im/c#two']}"
wallet :: TVar ChaChaDRG -> WalletEntropy -> IO (S.Secp256k1PrivateKey, Address)
wallet g entropy = first xkKey . either error id <$> deriveAddress g master (bip44Path Ethereum $ either error id $ mkAccountIndex 0)
where
master = either error id $ masterKey $ entropySeed entropy ""
callNode :: String -> IO ByteString
callNode expr =
BC.pack
<$> readCreateProcess
(proc "node" ["--input-type=module", "-e", imports <> "const v = " <> expr <> "; process.stdout.write(typeof v === 'string' ? v : Buffer.from(v).toString('hex'));"]) {cwd = Just namesWebDir}
""
where
imports =
"import {formatNameCode, parseNameCode} from './dist/code.js';"
<> "import {makeCommitment, registerIntentDigest} from './dist/registration.js';"
<> "import {signDigest, walletFromEntropy} from './dist/wallet.js';"
jsUint8 :: ByteString -> String
jsUint8 bs = "new Uint8Array([" <> intercalate "," (map show $ B.unpack bs) <> "])"
jsHex :: String -> String
jsHex = jsUint8 . either error id . BAE.convertFromBase BAE.Base16 . BC.pack
address :: ByteString -> Address
address = either error id . strDecode . hex
hex :: ByteString -> ByteString
hex = BAE.convertToBase BAE.Base16
+2
View File
@@ -42,6 +42,7 @@ import Simplex.FileTransfer.Server.Store (SFSType (..))
import XFTPServerTests (xftpServerTests)
import WebTests (webTests)
import XFTPWebTests (xftpWebTests)
import NamesWebTests (namesWebTests)
#if defined(dbPostgres)
import Fixtures
@@ -182,6 +183,7 @@ main = do
#else
describe "XFTP Web Client" $ xftpWebTests (pure ())
#endif
describe "Names Web" namesWebTests
describe "XRCP" remoteControlTests
describe "Web" webTests
describe "Server CLIs" cliTests