Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion e2e/fixtures/rpcMock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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 {
Expand Down
41 changes: 38 additions & 3 deletions e2e/fixtures/zcash.ts
Original file line number Diff line number Diff line change
@@ -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/;
Expand Down Expand Up @@ -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<string>(
TIP_BLOCK.tx.flatMap((tx) => tx.vin.flatMap((input) => (input.txid ? [input.txid] : []))),
);

export const ZCASH = {
networkSlug: "zec",
tipHeight: BLOCK_3483400.height,
Expand Down Expand Up @@ -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,
Expand All @@ -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<RecordedRpcCall[]> {
const calls: RecordedRpcCall[] = [];
Expand Down Expand Up @@ -170,12 +200,17 @@ export async function mockZcashRpc(page: Page): Promise<RecordedRpcCall[]> {
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];
Expand Down
116 changes: 116 additions & 0 deletions e2e/tests/shared/mocked/zcash-search.spec.ts
Original file line number Diff line number Diff line change
@@ -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}$`));
});
});
11 changes: 9 additions & 2 deletions src/components/pages/zcash/ZcashBlockPage.tsx
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -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,
Expand Down Expand Up @@ -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 });
Expand Down Expand Up @@ -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 (
Expand Down
38 changes: 35 additions & 3 deletions src/components/pages/zcash/ZcashTransactionPage.tsx
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -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,
Expand Down Expand Up @@ -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/<block hash> 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);
}
Expand All @@ -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.
Expand Down
22 changes: 17 additions & 5 deletions src/hooks/useSearch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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) {
Expand All @@ -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}`);
Expand Down
Loading