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
12 changes: 12 additions & 0 deletions e2e/tests/shared/mocked/zcash-address.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,4 +140,16 @@ test.describe("Zcash address", () => {
await expect(items).toHaveCount(10);
await expect(items.last()).toContainText(history[0] ?? "");
});

test("offers AI analysis only when the address has public data", async ({ page }) => {
await mockZcashRpc(page);

await page.goto(addressUrl(T_ADDRESS));
await expect(page.locator(".ai-analysis-panel")).toHaveCount(1);

// A Sapling address has nothing public to analyze, so it isn't sent to the AI provider
await page.goto(addressUrl(SAPLING_ADDRESS));
await expect(page.getByText("Shielded addresses don't reveal balances")).toBeVisible();
await expect(page.locator(".ai-analysis-panel")).toHaveCount(0);
});
});
481 changes: 251 additions & 230 deletions src/components/pages/zcash/ZcashAddressDisplay.tsx

Large diffs are not rendered by default.

521 changes: 271 additions & 250 deletions src/components/pages/zcash/ZcashBlockDisplay.tsx

Large diffs are not rendered by default.

532 changes: 277 additions & 255 deletions src/components/pages/zcash/ZcashTransactionDisplay.tsx

Large diffs are not rendered by default.

175 changes: 175 additions & 0 deletions src/components/pages/zcash/aiContext.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
import { describe, expect, it } from "vitest";
import type { ZcashAddress, ZcashBlock, ZcashTransaction } from "../../../types";
import {
buildAddressAnalysisContext,
buildBlockAnalysisContext,
buildTransactionAnalysisContext,
} from "./aiContext";

const T_ADDRESS = "t1KAuVfS2r2hc7RwSh6GTuyfqCGMFEpwkZ2";

// Mainnet tx 36a167f6…ce2e3, block 3,483,400
const ironwoodOnly: ZcashTransaction = {
txid: "36a167f602a15015593130974e0942179e7e394e0e0e6e239752533e2b5ce2e3",
version: 6,
size: 9_170,
locktime: 0,
expiryHeight: 3483438,
vin: [],
vout: [],
shielded: { ironwood: { actions: 2, valueBalanceZat: 10_000 } },
blockhash: "0".repeat(64),
blockheight: 3483400,
confirmations: 66,
};

describe("buildTransactionAnalysisContext", () => {
it("describes a fully shielded transaction with its fee in ZEC", () => {
const context = buildTransactionAnalysisContext(ironwoodOnly);

expect(context).toMatchObject({
status: "confirmed",
kind: "shielded",
pools: ["ironwood"],
transparentInputCount: 0,
transparentOutputCount: 0,
feeZEC: 0.0001,
shieldedBundles: { ironwood: { actions: 2, valueBalanceZEC: 0.0001 } },
});
expect(context.transparentInputsZEC).toBeUndefined();
});

it("leaves the fee out while transparent input values are unknown", () => {
const context = buildTransactionAnalysisContext({
...ironwoodOnly,
vin: [{ txid: "a".repeat(64), vout: 0, sequence: 0 }],
shielded: { sapling: { spends: 0, outputs: 2, valueBalanceZat: -500_000 } },
blockhash: undefined,
confirmations: undefined,
});

expect(context).toMatchObject({ status: "unconfirmed (in mempool)", kind: "shielding" });
expect(context.feeZEC).toBeUndefined();
});
});

describe("buildTransactionAnalysisContext for Sprout", () => {
it("reports JoinSplit public values and the fee once inputs are known", () => {
const sprout: ZcashTransaction = {
txid: "5".repeat(64),
version: 2,
size: 1_802,
locktime: 0,
vin: [{ txid: "a".repeat(64), vout: 0, sequence: 0, valueZat: 30_000 }],
vout: [],
shielded: { sprout: { joinSplits: 1, vpubOldZat: 20_000, vpubNewZat: 0 } },
};

expect(buildTransactionAnalysisContext(sprout)).toMatchObject({
kind: "shielding",
pools: ["transparent", "sprout"],
isCoinbase: false,
feeZEC: 0.0001,
shieldedBundles: { sprout: { joinSplits: 1, enteredSproutZEC: 0.0002, leftSproutZEC: 0 } },
});
});
});

describe("buildBlockAnalysisContext", () => {
it("converts the coinbase outputs and value pools to ZEC", () => {
const block: ZcashBlock = {
hash: "0".repeat(64),
height: 3483400,
time: 1789411472,
nTx: 18,
size: 84_186,
version: 4,
merkleRoot: "0".repeat(64),
bits: "1c008816",
nonce: "a9a1",
difficulty: 252_490_000,
coinbaseOutputs: [
{ address: "t1SqwRAAdSig6dE4EBPLonAait219VmkUjP", valueZat: 125_490_751 },
{ address: "t3cFfPt1Bcvgez9ZbMBFWeZsskxTkPzGCow", valueZat: 12_500_000 },
],
shieldedTxCounts: { sapling: 2, ironwood: 2 },
valuePools: [{ id: "sapling", valueZat: 51_144_292_792_244 }],
};

expect(buildBlockAnalysisContext(block)).toMatchObject({
transactionCount: 18,
coinbaseTotalZEC: 1.37990751,
coinbaseShieldedZEC: undefined,
shieldedTransactionCounts: { sapling: 2, ironwood: 2 },
valuePoolsZEC: { sapling: 511442.92792244 },
});
});
});

describe("buildBlockAnalysisContext for a shielded coinbase", () => {
it("includes the reward paid into the shielded pools", () => {
const block: ZcashBlock = {
hash: "0".repeat(64),
height: 3483401,
time: 1789411547,
nTx: 1,
size: 2_000,
version: 4,
merkleRoot: "0".repeat(64),
bits: "1c008816",
nonce: "a9a1",
difficulty: 252_490_000,
coinbaseOutputs: [{ address: "t3cFfPt1Bcvgez9ZbMBFWeZsskxTkPzGCow", valueZat: 12_500_000 }],
coinbaseShieldedZat: 125_490_751,
};

expect(buildBlockAnalysisContext(block)).toMatchObject({
coinbaseTotalZEC: 1.37990751,
coinbaseShieldedZEC: 1.25490751,
});
});
});

describe("buildAddressAnalysisContext", () => {
it("reports a blocked address index instead of a zero balance", () => {
const address: ZcashAddress = {
address: T_ADDRESS,
type: "p2pkh",
transparentAddress: T_ADDRESS,
balance: { availability: "unsupported" },
utxos: { availability: "unsupported" },
txids: { availability: "unsupported" },
};

const context = buildAddressAnalysisContext(address);

expect(context).toMatchObject({
addressType: "p2pkh",
addressIndex: {
balance: "unsupported",
unspentOutputs: "unsupported",
history: "unsupported",
},
});
expect(context.transparentBalanceZEC).toBeUndefined();
expect(context.transparentReceiver).toBeUndefined();
});

it("describes a unified address through its transparent receiver, newest transactions first", () => {
const context = buildAddressAnalysisContext({
address: `u1${"q".repeat(100)}`,
type: "unified",
transparentAddress: T_ADDRESS,
receivers: { availability: "ok", data: { orchard: `u1${"p".repeat(60)}`, p2pkh: T_ADDRESS } },
balance: { availability: "ok", data: { balanceZat: 9_514_810 } },
txids: { availability: "ok", data: ["older", "newer"] },
});

expect(context).toMatchObject({
transparentReceiver: T_ADDRESS,
receiverTypes: ["orchard", "p2pkh"],
transparentBalanceZEC: 0.0951481,
recentTxids: ["newer", "older"],
});
});
});
136 changes: 136 additions & 0 deletions src/components/pages/zcash/aiContext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
/**
* Compact contexts for the AI analysis panel. Amounts are converted to ZEC and field names carry
* the unit, so the model never has to infer one.
*/

import type {
ZcashAddress,
ZcashBlock,
ZcashShieldedBundles,
ZcashTransaction,
} from "../../../types";
import {
classifyTransaction,
computeFee,
getTransactionPools,
getTransparentOutputZat,
zatToZec,
} from "../../../utils/zcashUtils";

function summarizeShieldedBundles({ sprout, sapling, orchard, ironwood }: ZcashShieldedBundles) {
return {
sprout: sprout && {
joinSplits: sprout.joinSplits,
enteredSproutZEC: zatToZec(sprout.vpubOldZat),
leftSproutZEC: zatToZec(sprout.vpubNewZat),
},
sapling: sapling && {
spends: sapling.spends,
outputs: sapling.outputs,
valueBalanceZEC: zatToZec(sapling.valueBalanceZat),
},
orchard: orchard && {
actions: orchard.actions,
valueBalanceZEC: zatToZec(orchard.valueBalanceZat),
},
ironwood: ironwood && {
actions: ironwood.actions,
valueBalanceZEC: zatToZec(ironwood.valueBalanceZat),
},
};
}

export function buildTransactionAnalysisContext(tx: ZcashTransaction): Record<string, unknown> {
const fee = computeFee(tx);
const feeZat = fee.kind === "known" ? fee.zat : undefined;
const inputValuesKnown =
tx.vin.length > 0 && tx.vin.every((input) => input.valueZat !== undefined);

return {
txid: tx.txid,
status: tx.blockhash && tx.confirmations ? "confirmed" : "unconfirmed (in mempool)",
confirmations: tx.confirmations,
blockHeight: tx.blockheight,
kind: classifyTransaction(tx),
pools: getTransactionPools(tx),
isCoinbase: fee.kind === "coinbase",
version: tx.version,
expiryHeight: tx.expiryHeight,
sizeBytes: tx.size,
transparentInputCount: tx.vin.length,
transparentOutputCount: tx.vout.length,
transparentInputsZEC: inputValuesKnown
? zatToZec(tx.vin.reduce((sum, input) => sum + (input.valueZat ?? 0), 0))
: undefined,
transparentOutputsZEC: zatToZec(getTransparentOutputZat(tx)),
feeZEC: feeZat === undefined ? undefined : zatToZec(feeZat),
feeRateZatPerByte:
feeZat !== undefined && tx.size > 0 ? Number((feeZat / tx.size).toFixed(2)) : undefined,
shieldedBundles: summarizeShieldedBundles(tx.shielded),
transparentOutputs: tx.vout.map((output) => ({
address: output.address,
amountZEC: zatToZec(output.valueZat),
scriptType: output.scriptType,
})),
};
}

export function buildBlockAnalysisContext(block: ZcashBlock): Record<string, unknown> {
const coinbaseOutputs = block.coinbaseOutputs ?? [];
const coinbaseShieldedZat = block.coinbaseShieldedZat ?? 0;
const coinbaseTotalZat =
coinbaseOutputs.reduce((sum, output) => sum + output.valueZat, 0) + coinbaseShieldedZat;

return {
height: block.height,
hash: block.hash,
time: block.time,
confirmations: block.confirmations,
transactionCount: block.nTx,
sizeBytes: block.size,
difficulty: block.difficulty,
coinbaseTotalZEC: coinbaseTotalZat > 0 ? zatToZec(coinbaseTotalZat) : undefined,
// Reward paid into Sapling or Orchard by a shielded coinbase (not in coinbaseOutputs)
coinbaseShieldedZEC: coinbaseShieldedZat > 0 ? zatToZec(coinbaseShieldedZat) : undefined,
coinbaseOutputs: coinbaseOutputs.map((output) => ({
address: output.address,
amountZEC: zatToZec(output.valueZat),
})),
transparentOutputZEC:
block.transparentOutputZat === undefined ? undefined : zatToZec(block.transparentOutputZat),
shieldedTransactionCounts: block.shieldedTxCounts,
noteCommitmentTreeSizes: block.trees,
valuePoolsZEC:
block.valuePools &&
Object.fromEntries(block.valuePools.map((pool) => [pool.id, zatToZec(pool.valueZat)])),
chainSupplyZEC: block.chainSupplyZat === undefined ? undefined : zatToZec(block.chainSupplyZat),
};
}

export function buildAddressAnalysisContext(address: ZcashAddress): Record<string, unknown> {
const { balance, utxos, txids, receivers } = address;

return {
address: address.address,
addressType: address.type,
transparentReceiver:
address.transparentAddress !== address.address ? address.transparentAddress : undefined,
receiverTypes: receivers?.data && Object.keys(receivers.data),
receiversLookup: receivers?.availability,
// Availability per address-index section, so a blocked index isn't read as a zero balance
addressIndex: balance && {
balance: balance.availability,
unspentOutputs: utxos?.availability,
history: txids?.availability,
},
// Only the transparent receiver's: a unified address's other receivers are shielded
transparentBalanceZEC:
balance?.data === undefined ? undefined : zatToZec(balance.data.balanceZat),
transparentReceivedZEC:
balance?.data?.receivedZat === undefined ? undefined : zatToZec(balance.data.receivedZat),
unspentOutputCount: utxos?.data?.length,
transactionCount: txids?.data?.length,
// getaddresstxids returns chain order, oldest first
recentTxids: txids?.data && [...txids.data].reverse().slice(0, 10),
};
}
Loading