From adb58d1359861c12403f7ec7ccb500c0d0e86860 Mon Sep 17 00:00:00 2001 From: Mati OS Date: Mon, 14 Sep 2026 20:39:03 -0300 Subject: [PATCH 1/4] test(e2e): let mocked RPC handlers return JSON-RPC errors --- e2e/fixtures/rpcMock.ts | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/e2e/fixtures/rpcMock.ts b/e2e/fixtures/rpcMock.ts index b4700f25..9e7f21de 100644 --- a/e2e/fixtures/rpcMock.ts +++ b/e2e/fixtures/rpcMock.ts @@ -21,6 +21,26 @@ type RpcMethodHandler = | { result: unknown } | { error: { code: number; message: string } }; +const RPC_ERROR = Symbol("rpcError"); + +interface RpcErrorResponse { + [RPC_ERROR]: true; + code: number; + message: string; +} + +/** + * Return this from a function handler to answer with a JSON-RPC error instead of a result, + * e.g. `getblock: ([hash]) => (known(hash) ? block : rpcError(-8, "Block not found"))`. + */ +export function rpcError(code: number, message: string): RpcErrorResponse { + return { [RPC_ERROR]: true, code, message }; +} + +function isRpcError(value: unknown): value is RpcErrorResponse { + return typeof value === "object" && value !== null && RPC_ERROR in value; +} + export interface MockOptions { /** Return HTTP status instead of a JSON-RPC response. Overrides handlers. */ httpStatus?: number; @@ -77,7 +97,10 @@ export async function mockJsonRpc( error: { code: -32601, message: `method ${method} not mocked` }, }; } else if (typeof handler === "function") { - body = { jsonrpc: "2.0", id, result: handler(params) }; + const value = handler(params); + body = isRpcError(value) + ? { jsonrpc: "2.0", id, error: { code: value.code, message: value.message } } + : { jsonrpc: "2.0", id, result: value }; } else if ("result" in handler) { body = { jsonrpc: "2.0", id, result: handler.result }; } else { From fd9aeb7addd6dc0c9fb9d11c0eb394ed09e73625 Mon Sep 17 00:00:00 2001 From: Mati OS Date: Mon, 14 Sep 2026 20:39:04 -0300 Subject: [PATCH 2/4] feat(search): route Zcash addresses and block hashes Zcash block hashes and txids are both 64 hex characters, so search keeps sending hashes to the transaction page, which now looks the hash up as a block and redirects when no transaction matches. --- .../pages/zcash/ZcashTransactionPage.tsx | 29 +++++++++++++++++-- src/hooks/useSearch.ts | 6 +++- 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/src/components/pages/zcash/ZcashTransactionPage.tsx b/src/components/pages/zcash/ZcashTransactionPage.tsx index 1ddc926c..101e0bc3 100644 --- a/src/components/pages/zcash/ZcashTransactionPage.tsx +++ b/src/components/pages/zcash/ZcashTransactionPage.tsx @@ -1,6 +1,6 @@ import { useCallback, useEffect, useRef, useState } from "react"; import { useTranslation } from "react-i18next"; -import { useParams } from "react-router-dom"; +import { useNavigate, useParams } from "react-router-dom"; import { CACHE_MIN_CONFIRMATIONS, LOADER_TIMEOUT_MS } from "../../../config/zcashConstants"; import { useDataService } from "../../../hooks/useDataService"; import { usePersistentCache } from "../../../hooks/usePersistentCache"; @@ -12,9 +12,12 @@ import Breadcrumb from "../../common/Breadcrumb"; import LoaderWithTimeout from "../../common/LoaderWithTimeout"; import ZcashTransactionDisplay, { type InputResolution } from "./ZcashTransactionDisplay"; +const HASH_PATTERN = /^[0-9a-f]{64}$/i; + export default function ZcashTransactionPage() { const { t } = useTranslation("zcash"); const { filter: txid } = useParams<{ filter?: string }>(); + const navigate = useNavigate(); const { slug: networkSlug, label: networkLabel, @@ -69,7 +72,18 @@ export default function ZcashTransactionPage() { setTransaction(data); cacheIfFinal(data); } catch (err) { - if (!signal.aborted) setError(err instanceof Error ? err.message : String(err)); + if (signal.aborted) return; + // Search sends every 64-character hash here, and Zcash block hashes look like txids, + // so a hash that matches no transaction may still be a block + const block = HASH_PATTERN.test(txid) + ? await adapter.getBlock(txid, { signal }).catch(() => null) + : null; + if (signal.aborted) return; + if (block) { + navigate(`/${networkSlug}/block/${block.data.block.hash}`, { replace: true }); + return; + } + setError(err instanceof Error ? err.message : String(err)); } finally { if (!signal.aborted) setLoading(false); } @@ -80,7 +94,16 @@ export default function ZcashTransactionPage() { controller.abort(); resolveControllerRef.current?.abort(); }; - }, [dataService, txid, getCached, cacheNetworkId, cacheIfFinal, attempt]); + }, [ + dataService, + txid, + getCached, + cacheNetworkId, + cacheIfFinal, + attempt, + navigate, + networkSlug, + ]); // Zebra omits transparent input values, so the fee is only resolved when the user asks. // A failed run keeps what it resolved, so asking again resumes from there. diff --git a/src/hooks/useSearch.ts b/src/hooks/useSearch.ts index 490e7630..c220a84d 100644 --- a/src/hooks/useSearch.ts +++ b/src/hooks/useSearch.ts @@ -3,6 +3,7 @@ import { useLocation, useNavigate } from "react-router-dom"; import { AppContext, useNetworks } from "../context"; import { ENSService } from "../services/ENS/ENSService"; import { isEVMNetwork, resolveNetwork } from "../utils/networkResolver"; +import { isZcashAddress } from "../utils/zcashUtils"; interface UseSearchResult { searchTerm: string; @@ -95,10 +96,13 @@ export function useSearch(): UseSearchResult { const isEvmAddress = /^0x[a-fA-F0-9]{40}$/.test(term); const isBitcoinTxid = /^[a-fA-F0-9]{64}$/.test(term); const isBitcoinAddress = /^(1|3|bc1)[a-zA-Z0-9]{25,62}$/.test(term); + // Transparent, Sapling, unified, Sprout and TEX addresses. Zcash block hashes are also 64 + // hex characters: they go to the transaction page, which redirects to the matching block. + const isZcashAddressTerm = resolvedNetwork?.type === "zcash" && isZcashAddress(term); const isBlockNumber = /^\d+$/.test(term); const isTransactionHash = isEvmTransactionHash || isBitcoinTxid; - const isAddress = isEvmAddress || isBitcoinAddress; + const isAddress = isEvmAddress || isBitcoinAddress || isZcashAddressTerm; // If pattern doesn't match any valid type, show error immediately if (!isTransactionHash && !isAddress && !isBlockNumber) { From e3ed330a9640cbc7c4f985a2af439e7b90c1dba5 Mon Sep 17 00:00:00 2001 From: Mati OS Date: Mon, 14 Sep 2026 20:39:05 -0300 Subject: [PATCH 3/4] test(e2e): add hermetic Zcash search spec --- e2e/fixtures/zcash.ts | 41 ++++++++++++- e2e/tests/shared/mocked/zcash-search.spec.ts | 62 ++++++++++++++++++++ 2 files changed, 100 insertions(+), 3 deletions(-) create mode 100644 e2e/tests/shared/mocked/zcash-search.spec.ts diff --git a/e2e/fixtures/zcash.ts b/e2e/fixtures/zcash.ts index 5e88bad2..5fa8e4bb 100644 --- a/e2e/fixtures/zcash.ts +++ b/e2e/fixtures/zcash.ts @@ -1,6 +1,6 @@ import type { Page } from "@playwright/test"; import { BLOCK_3483400 } from "../../src/services/adapters/ZcashAdapter/fixtures"; -import { mockJsonRpc } from "./rpcMock"; +import { mockJsonRpc, rpcError } from "./rpcMock"; /** The built-in Zcash RPC defaults are Tatum's gateways, so every Zcash request matches this */ export const ZCASH_RPC_PATTERN = /zcash-(mainnet|testnet)(-zebrad)?\.gateway\.tatum\.io/; @@ -44,6 +44,11 @@ const TRANSPARENT_TX = { const TIP_BLOCK = { ...BLOCK_3483400, tx: [...BLOCK_3483400.tx, TRANSPARENT_TX] }; const KNOWN_TRANSACTIONS = new Map(TIP_BLOCK.tx.map((tx) => [tx.txid, tx])); +// Transactions spent by the known transactions' transparent inputs, served for input lookups +const PREVIOUS_TXIDS = new Set( + TIP_BLOCK.tx.flatMap((tx) => tx.vin.flatMap((input) => (input.txid ? [input.txid] : []))), +); + export const ZCASH = { networkSlug: "zec", tipHeight: BLOCK_3483400.height, @@ -99,7 +104,7 @@ function blockSummary(height: number) { }; } -/** Any unknown txid is served as a previous transaction with 20 outputs of 0.0003 ZEC */ +/** A previous transaction with 20 outputs of 0.0003 ZEC */ function previousTransaction(txid: string) { return { txid, @@ -122,9 +127,34 @@ function previousTransaction(txid: string) { }; } +/** An unconfirmed transparent transaction, served for mempool txids */ +function pendingTransaction(txid: string) { + return { + txid, + version: 5, + size: 372, + locktime: 0, + expiryheight: ZCASH.tipHeight + 40, + time: Math.floor(Date.now() / 1000), + vin: [{ txid: "a1".repeat(32), vout: 2, sequence: 4294967295 }], + vout: [ + { + value: 0.0002, + valueZat: 20_000, + n: 0, + scriptPubKey: { type: "pubkeyhash", addresses: [T_ADDRESS] }, + }, + ], + vShieldedSpend: [], + vShieldedOutput: [], + vjoinsplit: [], + }; +} + /** * Serve a Zcash chain whose tip is mainnet block 3,483,400 (plus one synthetic transparent * transaction) and record every Zcash RPC call the page makes, including unmocked methods. + * Unknown transactions and block hashes fail the way Zebra does. */ export async function mockZcashRpc(page: Page): Promise { const calls: RecordedRpcCall[] = []; @@ -170,12 +200,17 @@ export async function mockZcashRpc(page: Page): Promise { if (isTip) { return verbosity === 2 ? TIP_BLOCK : { ...TIP_BLOCK, tx: TIP_BLOCK.tx.map((tx) => tx.txid) }; } + if (!/^\d+$/.test(hashOrHeight)) return rpcError(-8, "Block not found"); const summary = blockSummary(Number(hashOrHeight)); return verbosity === 2 ? { ...summary, tx: [] } : summary; }, getrawtransaction: (params) => { const [txid] = params as [string]; - return KNOWN_TRANSACTIONS.get(txid) ?? previousTransaction(txid); + const known = KNOWN_TRANSACTIONS.get(txid); + if (known) return known; + if (PREVIOUS_TXIDS.has(txid)) return previousTransaction(txid); + if (txid in MEMPOOL) return pendingTransaction(txid); + return rpcError(-5, "No such mempool or main chain transaction"); }, getrawmempool: (params) => { const [verbose] = params as [boolean | undefined]; diff --git a/e2e/tests/shared/mocked/zcash-search.spec.ts b/e2e/tests/shared/mocked/zcash-search.spec.ts new file mode 100644 index 00000000..47bd65ca --- /dev/null +++ b/e2e/tests/shared/mocked/zcash-search.spec.ts @@ -0,0 +1,62 @@ +import type { Page } from "@playwright/test"; +import { + BLOCK_3483400, + IRONWOOD_ONLY_TX, +} from "../../../../src/services/adapters/ZcashAdapter/fixtures"; +import { expect, test } from "../../../fixtures/test"; +import { mockZcashRpc, ZCASH } from "../../../fixtures/zcash"; + +/** + * Hermetic search on a Zcash network. Zcash block hashes and txids are both 64 hex characters, + * so hashes go to the transaction page, which redirects to the block when no transaction matches. + */ +async function search(page: Page, term: string) { + const input = page.locator("input.home-search-input").first(); + await input.fill(term); + await input.press("Enter"); +} + +test.describe("Zcash search", () => { + test.beforeEach(async ({ page }) => { + await mockZcashRpc(page); + await page.goto(`/#/${ZCASH.networkSlug}`); + await expect(page.locator(".network-title-name")).toHaveText("ZCASH MAINNET"); + }); + + test("goes to a block by height", async ({ page }) => { + await search(page, String(ZCASH.tipHeight)); + + await expect(page).toHaveURL(new RegExp(`/${ZCASH.networkSlug}/block/${ZCASH.tipHeight}$`)); + await expect(page.locator(".block-number")).toHaveText("#3,483,400"); + }); + + test("goes to a transaction by txid", async ({ page }) => { + await search(page, IRONWOOD_ONLY_TX.txid ?? ""); + + await expect(page).toHaveURL(new RegExp(`/${ZCASH.networkSlug}/tx/${IRONWOOD_ONLY_TX.txid}$`)); + await expect(page.getByText("Fully shielded transaction")).toBeVisible(); + }); + + test("redirects a block hash to its block page", async ({ page }) => { + await search(page, BLOCK_3483400.hash); + + await expect(page).toHaveURL(new RegExp(`/${ZCASH.networkSlug}/block/${BLOCK_3483400.hash}$`)); + await expect(page.locator(".block-number")).toHaveText("#3,483,400"); + }); + + test("reports a hash that matches no transaction or block", async ({ page }) => { + const unknownHash = "ab".repeat(32); + + await search(page, unknownHash); + + await expect(page.getByText("Couldn't load this transaction")).toBeVisible(); + await expect(page).toHaveURL(new RegExp(`/${ZCASH.networkSlug}/tx/${unknownHash}$`)); + }); + + test("rejects a term that is not a height, hash or address", async ({ page }) => { + await search(page, "not-a-zcash-term"); + + await expect(page.locator(".home-search-error").first()).toBeVisible(); + await expect(page).toHaveURL(new RegExp(`/#/${ZCASH.networkSlug}$`)); + }); +}); From d72ca162c9f0edbef7f37add46955d0b418912c6 Mon Sep 17 00:00:00 2001 From: Mati OS Date: Fri, 20 Nov 2026 20:27:43 -0300 Subject: [PATCH 4/4] fix(search): resolve zcash block hashes in one call, not on rate limits - The transaction page only tries a hash as a block when the node answered that no such transaction exists. A rate-limited or unreachable endpoint said nothing about the hash, so it no longer triggers a second round of retries (~90s and up to six requests). - A hash that is a block redirects to /block/ and hands the block it already fetched to the block page, which doesn't refetch it (and caches it when it already has a successor). - ZcashRpcError.answered tells definitive JSON-RPC answers apart from HTTP and network failures. - Search: isBitcoinTxid becomes isHex64Hash (shared in hashUtils with the transaction page), Zcash networks are matched with isZcashNetwork, addresses are checked against the selected network, and all-uppercase Bech32m addresses are lowercased. - E2E: one getblock per block-hash search, no block lookup for a rate-limited hash, and uppercase unified addresses. --- e2e/tests/shared/mocked/zcash-search.spec.ts | 62 +++++++++++++++++-- src/components/pages/zcash/ZcashBlockPage.tsx | 11 +++- .../pages/zcash/ZcashTransactionPage.tsx | 27 +++++--- src/hooks/useSearch.ts | 24 ++++--- .../adapters/ZcashAdapter/ZcashAdapter.ts | 9 +++ src/utils/hashUtils.ts | 9 +++ src/utils/zcashUtils.ts | 10 ++- 7 files changed, 128 insertions(+), 24 deletions(-) create mode 100644 src/utils/hashUtils.ts diff --git a/e2e/tests/shared/mocked/zcash-search.spec.ts b/e2e/tests/shared/mocked/zcash-search.spec.ts index 47bd65ca..85d49c7a 100644 --- a/e2e/tests/shared/mocked/zcash-search.spec.ts +++ b/e2e/tests/shared/mocked/zcash-search.spec.ts @@ -4,7 +4,12 @@ import { IRONWOOD_ONLY_TX, } from "../../../../src/services/adapters/ZcashAdapter/fixtures"; import { expect, test } from "../../../fixtures/test"; -import { mockZcashRpc, ZCASH } from "../../../fixtures/zcash"; +import { + mockZcashRpc, + type RecordedRpcCall, + ZCASH, + ZCASH_RPC_PATTERN, +} from "../../../fixtures/zcash"; /** * Hermetic search on a Zcash network. Zcash block hashes and txids are both 64 hex characters, @@ -16,9 +21,14 @@ async function search(page: Page, term: string) { await input.press("Enter"); } +let calls: RecordedRpcCall[] = []; + +const getblockCalls = (hashOrHeight: string) => + calls.filter((call) => call.method === "getblock" && call.params[0] === hashOrHeight); + test.describe("Zcash search", () => { test.beforeEach(async ({ page }) => { - await mockZcashRpc(page); + calls = await mockZcashRpc(page); await page.goto(`/#/${ZCASH.networkSlug}`); await expect(page.locator(".network-title-name")).toHaveText("ZCASH MAINNET"); }); @@ -37,11 +47,55 @@ test.describe("Zcash search", () => { await expect(page.getByText("Fully shielded transaction")).toBeVisible(); }); - test("redirects a block hash to its block page", async ({ page }) => { + test("redirects a block hash to its block page by height, fetching the block once", async ({ + page, + }) => { + // The dashboard fetches the tip by height too; count only what the search adds + await expect(page.getByTestId("zcash-blocks-table")).toContainText("#3,483,400"); + const tipFetchesBefore = getblockCalls(String(ZCASH.tipHeight)).length; + await search(page, BLOCK_3483400.hash); - await expect(page).toHaveURL(new RegExp(`/${ZCASH.networkSlug}/block/${BLOCK_3483400.hash}$`)); + await expect(page).toHaveURL(new RegExp(`/${ZCASH.networkSlug}/block/${ZCASH.tipHeight}$`)); await expect(page.locator(".block-number")).toHaveText("#3,483,400"); + // The transaction page's lookup is handed to the block page, which doesn't refetch it + expect(getblockCalls(BLOCK_3483400.hash)).toHaveLength(1); + expect(getblockCalls(String(ZCASH.tipHeight))).toHaveLength(tipFetchesBefore); + }); + + test("doesn't look up a rate-limited hash as a block", async ({ page }) => { + const hash = "cd".repeat(32); + await page.route(ZCASH_RPC_PATTERN, async (route) => { + const body = JSON.parse(route.request().postData() ?? "{}"); + if (body.method === "getrawtransaction" && body.params?.[0] === hash) { + await route.fulfill({ status: 429, body: "" }); + return; + } + await route.fallback(); + }); + // Skip through the 15s and 30s rate-limit backoffs + await page.clock.install(); + await page.reload(); + + await search(page, hash); + await expect(page).toHaveURL(new RegExp(`/tx/${hash}$`)); + // Each backoff is scheduled after the previous attempt answers, so step through them + await expect(async () => { + await page.clock.fastForward(16_000); + await expect(page.getByText("Couldn't load this transaction")).toBeVisible({ + timeout: 500, + }); + }).toPass({ timeout: 20_000 }); + + expect(getblockCalls(hash)).toHaveLength(0); + }); + + test("normalizes an all-uppercase unified address", async ({ page }) => { + const unified = `u1${"q".repeat(100)}`; + + await search(page, unified.toUpperCase()); + + await expect(page).toHaveURL(new RegExp(`/${ZCASH.networkSlug}/address/${unified}$`)); }); test("reports a hash that matches no transaction or block", async ({ page }) => { diff --git a/src/components/pages/zcash/ZcashBlockPage.tsx b/src/components/pages/zcash/ZcashBlockPage.tsx index 963f109a..cd4d406c 100644 --- a/src/components/pages/zcash/ZcashBlockPage.tsx +++ b/src/components/pages/zcash/ZcashBlockPage.tsx @@ -1,6 +1,6 @@ import { useEffect, useState } from "react"; import { useTranslation } from "react-i18next"; -import { useParams } from "react-router-dom"; +import { useLocation, useParams } from "react-router-dom"; import { LOADER_TIMEOUT_MS } from "../../../config/zcashConstants"; import { useDataService } from "../../../hooks/useDataService"; import { usePersistentCache } from "../../../hooks/usePersistentCache"; @@ -13,6 +13,8 @@ import ZcashBlockDisplay from "./ZcashBlockDisplay"; export default function ZcashBlockPage() { const { t } = useTranslation("zcash"); const { filter } = useParams<{ filter?: string }>(); + // The transaction page hands over a block it already fetched while resolving a hash + const handedOver = (useLocation().state as { block?: ZcashBlock } | null)?.block; const { slug: networkSlug, label: networkLabel, @@ -42,6 +44,11 @@ export default function ZcashBlockPage() { setFromCache(false); try { + if (handedOver && String(handedOver.height) === filter) { + setBlock(handedOver); + return; + } + let blockId: string | number = filter; if (filter === "latest") { blockId = await adapter.getLatestBlockNumber({ signal }); @@ -72,7 +79,7 @@ export default function ZcashBlockPage() { fetchBlock(); return () => controller.abort(); - }, [dataService, filter, getCached, setCached, cacheNetworkId, attempt]); + }, [dataService, filter, getCached, setCached, cacheNetworkId, attempt, handedOver]); if (loading) { return ( diff --git a/src/components/pages/zcash/ZcashTransactionPage.tsx b/src/components/pages/zcash/ZcashTransactionPage.tsx index 101e0bc3..609c3ecb 100644 --- a/src/components/pages/zcash/ZcashTransactionPage.tsx +++ b/src/components/pages/zcash/ZcashTransactionPage.tsx @@ -5,15 +5,15 @@ import { CACHE_MIN_CONFIRMATIONS, LOADER_TIMEOUT_MS } from "../../../config/zcas import { useDataService } from "../../../hooks/useDataService"; import { usePersistentCache } from "../../../hooks/usePersistentCache"; import { useZcashNetworkFromPath } from "../../../hooks/useZcashNetworkFromPath"; +import { ZcashRpcError } from "../../../services/adapters/ZcashAdapter"; import type { ZcashTransaction } from "../../../types"; +import { isHex64Hash } from "../../../utils/hashUtils"; import { truncateHash } from "../../../utils/zcashFormatters"; import { countPreviousTransactions } from "../../../utils/zcashUtils"; import Breadcrumb from "../../common/Breadcrumb"; import LoaderWithTimeout from "../../common/LoaderWithTimeout"; import ZcashTransactionDisplay, { type InputResolution } from "./ZcashTransactionDisplay"; -const HASH_PATTERN = /^[0-9a-f]{64}$/i; - export default function ZcashTransactionPage() { const { t } = useTranslation("zcash"); const { filter: txid } = useParams<{ filter?: string }>(); @@ -73,14 +73,22 @@ export default function ZcashTransactionPage() { cacheIfFinal(data); } catch (err) { if (signal.aborted) return; - // Search sends every 64-character hash here, and Zcash block hashes look like txids, - // so a hash that matches no transaction may still be a block - const block = HASH_PATTERN.test(txid) - ? await adapter.getBlock(txid, { signal }).catch(() => null) - : null; + // Zcash block hashes look like txids, so a hash the node says matches no transaction + // may be a block (from search, or a pasted /tx/ URL). Rate-limited or + // unreachable endpoints said nothing about the hash, so don't spend a call on those. + const notATransaction = err instanceof ZcashRpcError && err.answered; + const result = + notATransaction && isHex64Hash(txid) + ? await adapter.getBlock(txid, { signal }).catch(() => null) + : null; if (signal.aborted) return; - if (block) { - navigate(`/${networkSlug}/block/${block.data.block.hash}`, { replace: true }); + if (result) { + const { block } = result.data; + if (block.nextBlockHash) { + setCached(cacheNetworkId, "block", String(block.height), block); + } + // Hand the block over so its page doesn't fetch it again + navigate(`/${networkSlug}/block/${block.height}`, { replace: true, state: { block } }); return; } setError(err instanceof Error ? err.message : String(err)); @@ -103,6 +111,7 @@ export default function ZcashTransactionPage() { attempt, navigate, networkSlug, + setCached, ]); // Zebra omits transparent input values, so the fee is only resolved when the user asks. diff --git a/src/hooks/useSearch.ts b/src/hooks/useSearch.ts index c220a84d..2eb37107 100644 --- a/src/hooks/useSearch.ts +++ b/src/hooks/useSearch.ts @@ -2,8 +2,10 @@ import { useCallback, useContext, useMemo, useState } from "react"; import { useLocation, useNavigate } from "react-router-dom"; import { AppContext, useNetworks } from "../context"; import { ENSService } from "../services/ENS/ENSService"; -import { isEVMNetwork, resolveNetwork } from "../utils/networkResolver"; -import { isZcashAddress } from "../utils/zcashUtils"; +import { getZcashNetworkKind } from "../config/zcashConstants"; +import { isHex64Hash } from "../utils/hashUtils"; +import { isEVMNetwork, isZcashNetwork, resolveNetwork } from "../utils/networkResolver"; +import { isZcashAddress, normalizeZcashAddress } from "../utils/zcashUtils"; interface UseSearchResult { searchTerm: string; @@ -94,14 +96,19 @@ export function useSearch(): UseSearchResult { // Determine what type of search this is const isEvmTransactionHash = /^0x[a-fA-F0-9]{64}$/.test(term); const isEvmAddress = /^0x[a-fA-F0-9]{40}$/.test(term); - const isBitcoinTxid = /^[a-fA-F0-9]{64}$/.test(term); + // A Bitcoin or Zcash txid. Zcash block hashes look the same: they go to the transaction + // page, which redirects to the block when the node finds no such transaction. + const isUtxoHash = isHex64Hash(term); const isBitcoinAddress = /^(1|3|bc1)[a-zA-Z0-9]{25,62}$/.test(term); - // Transparent, Sapling, unified, Sprout and TEX addresses. Zcash block hashes are also 64 - // hex characters: they go to the transaction page, which redirects to the matching block. - const isZcashAddressTerm = resolvedNetwork?.type === "zcash" && isZcashAddress(term); + // Transparent, Sapling, unified, Sprout and TEX addresses of the selected Zcash network. + // With no network selected any Zcash address counts, so the "select a network" hint shows. + const isZcashAddressTerm = resolvedNetwork + ? isZcashNetwork(resolvedNetwork) && + isZcashAddress(term, getZcashNetworkKind(resolvedNetwork.networkId)) + : isZcashAddress(term); const isBlockNumber = /^\d+$/.test(term); - const isTransactionHash = isEvmTransactionHash || isBitcoinTxid; + const isTransactionHash = isEvmTransactionHash || isUtxoHash; const isAddress = isEvmAddress || isBitcoinAddress || isZcashAddressTerm; // If pattern doesn't match any valid type, show error immediately @@ -121,7 +128,8 @@ export function useSearch(): UseSearchResult { navigate(`/${networkId}/tx/${term}`); setSearchTerm(""); } else if (isAddress) { - navigate(`/${networkId}/address/${term}`); + const address = isZcashAddressTerm ? normalizeZcashAddress(term) : term; + navigate(`/${networkId}/address/${address}`); setSearchTerm(""); } else if (isBlockNumber) { navigate(`/${networkId}/block/${term}`); diff --git a/src/services/adapters/ZcashAdapter/ZcashAdapter.ts b/src/services/adapters/ZcashAdapter/ZcashAdapter.ts index 39fba262..5ba824d7 100644 --- a/src/services/adapters/ZcashAdapter/ZcashAdapter.ts +++ b/src/services/adapters/ZcashAdapter/ZcashAdapter.ts @@ -18,6 +18,7 @@ import { logger } from "../../../utils/logger"; import { classifyRpcErrors, detectZcashAddressType, + isRpcErrorAnswer, normalizeZcashAddress, type ZcashRpcErrorKind, } from "../../../utils/zcashUtils"; @@ -59,6 +60,14 @@ export class ZcashRpcError extends Error { this.kind = kind; this.messages = messages; } + + /** + * An endpoint gave a definitive JSON-RPC answer (e.g. "not found"), rather than being rate + * limited or unreachable + */ + get answered(): boolean { + return this.kind === "failed" && this.messages.some(isRpcErrorAnswer); + } } /** diff --git a/src/utils/hashUtils.ts b/src/utils/hashUtils.ts new file mode 100644 index 00000000..f460d8ff --- /dev/null +++ b/src/utils/hashUtils.ts @@ -0,0 +1,9 @@ +/** + * 64 hex characters without a 0x prefix: a Bitcoin or Zcash txid or block hash (the two look + * alike, so only a lookup can tell them apart) + */ +const HEX64_PATTERN = /^[0-9a-fA-F]{64}$/; + +export function isHex64Hash(term: string): boolean { + return HEX64_PATTERN.test(term); +} diff --git a/src/utils/zcashUtils.ts b/src/utils/zcashUtils.ts index 404accd2..2d139cb0 100644 --- a/src/utils/zcashUtils.ts +++ b/src/utils/zcashUtils.ts @@ -193,6 +193,14 @@ const RATE_LIMITED_PATTERN = /status: 429/; const UNSUPPORTED_PATTERN = /method not found/i; const RPC_ERROR_PATTERN = /^RPC error:/; +/** + * Whether an endpoint answered with a JSON-RPC error (e.g. "No such transaction"), as opposed + * to an HTTP or network failure + */ +export function isRpcErrorAnswer(message: string): boolean { + return RPC_ERROR_PATTERN.test(message); +} + /** * Classify the per-endpoint error messages of a failed RPC call: * 1. Any endpoint answered with a JSON-RPC error other than "method not found": that answer is @@ -202,7 +210,7 @@ const RPC_ERROR_PATTERN = /^RPC error:/; */ export function classifyRpcErrors(messages: string[]): ZcashRpcErrorKind { const definitive = messages.some( - (message) => RPC_ERROR_PATTERN.test(message) && !UNSUPPORTED_PATTERN.test(message), + (message) => isRpcErrorAnswer(message) && !UNSUPPORTED_PATTERN.test(message), ); if (definitive) return "failed"; if (messages.some((message) => RATE_LIMITED_PATTERN.test(message))) return "rateLimited";