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 { 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..85d49c7a --- /dev/null +++ b/e2e/tests/shared/mocked/zcash-search.spec.ts @@ -0,0 +1,116 @@ +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, + 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, + * 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"); +} + +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 }) => { + calls = 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 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/${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 }) => { + 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}$`)); + }); +}); 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 1ddc926c..609c3ecb 100644 --- a/src/components/pages/zcash/ZcashTransactionPage.tsx +++ b/src/components/pages/zcash/ZcashTransactionPage.tsx @@ -1,11 +1,13 @@ 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"; 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"; @@ -15,6 +17,7 @@ import ZcashTransactionDisplay, { type InputResolution } from "./ZcashTransactio 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,26 @@ 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; + // 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 (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)); } finally { if (!signal.aborted) setLoading(false); } @@ -80,7 +102,17 @@ export default function ZcashTransactionPage() { controller.abort(); resolveControllerRef.current?.abort(); }; - }, [dataService, txid, getCached, cacheNetworkId, cacheIfFinal, attempt]); + }, [ + dataService, + txid, + getCached, + cacheNetworkId, + cacheIfFinal, + attempt, + navigate, + networkSlug, + setCached, + ]); // 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..2eb37107 100644 --- a/src/hooks/useSearch.ts +++ b/src/hooks/useSearch.ts @@ -2,7 +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 { 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; @@ -93,12 +96,20 @@ 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 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 isAddress = isEvmAddress || isBitcoinAddress; + const isTransactionHash = isEvmTransactionHash || isUtxoHash; + const isAddress = isEvmAddress || isBitcoinAddress || isZcashAddressTerm; // If pattern doesn't match any valid type, show error immediately if (!isTransactionHash && !isAddress && !isBlockNumber) { @@ -117,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";