From 8d1847ac13a7f41f573a12bf4b70367696e2e2ff Mon Sep 17 00:00:00 2001 From: "CC (Claude Code)" Date: Mon, 16 Nov 2026 12:33:33 -0800 Subject: [PATCH 1/3] wip(payment-anchor): shadow verifier, replay table draft, tests Co-Authored-By: Claude Opus 5.5 --- src/services/payment-anchor-db.ts | 98 +++++ src/services/payment-anchor-verify.ts | 389 ++++++++++++++++++ src/services/settled-interaction-scorer.ts | 79 +++- src/services/x402-settlement-verifier.ts | 108 ++++- ...6130000_payment_anchor_claims.rollback.sql | 4 + .../20261116130000_payment_anchor_claims.sql | 48 +++ .../base-sepolia-x402-settlement.json | 40 ++ tests/payment-anchor-through-scorer.test.ts | 243 +++++++++++ tests/payment-anchor-verify.test.ts | 388 +++++++++++++++++ 9 files changed, 1382 insertions(+), 15 deletions(-) create mode 100644 src/services/payment-anchor-db.ts create mode 100644 src/services/payment-anchor-verify.ts create mode 100644 supabase/migrations/20261116130000_payment_anchor_claims.rollback.sql create mode 100644 supabase/migrations/20261116130000_payment_anchor_claims.sql create mode 100644 tests/fixtures/payment-anchor/base-sepolia-x402-settlement.json create mode 100644 tests/payment-anchor-through-scorer.test.ts create mode 100644 tests/payment-anchor-verify.test.ts diff --git a/src/services/payment-anchor-db.ts b/src/services/payment-anchor-db.ts new file mode 100644 index 000000000..b469aaa4f --- /dev/null +++ b/src/services/payment-anchor-db.ts @@ -0,0 +1,98 @@ +/** + * payment-anchor-db.ts — the Supabase side of `payment-anchor-verify.ts`. + * + * TERMS come from three tables, all written by the engine, none by the caller: + * service_contracts provider, buyer, agreed_price_usdc_raw (the price, in USDC's smallest unit) + * repid_agents the provider's `wallet_address` = the payee + * x402_settlements the settlement recorded for the contract (`idempotency_key` = contract id): + * its `tx_hash` and the facilitator-verified `payer_address` + * + * Why `wallet_address` and not `erc8004_address`: MEASURED 2026-11-16 on the five most recent real + * settlements, every payee was the provider's `wallet_address`, while `erc8004_address` held values + * such as `pending-mint:…`, a registry contract's address, and free text. A payee read from that + * column would refuse real payments or accept payments to the wrong address. + * + * Why the payer is NOT the buyer's wallet: the same five settlements were all paid by the custodian + * wallet, not by the buyer agent's own `wallet_address`. The payer is what the facilitator verified + * from the signed authorization, which `x402_settlements.payer_address` records. + * + * REPLAY TABLE: `payment_anchor_claims`, created by the DRAFT migration + * `supabase/migrations/20261116130000_payment_anchor_claims.sql`. Until Sean applies it, an anchor + * the chain refuses is still REFUSED, and one the chain accepts reports NOT_CHECKED + * `replay_store_unreachable` with `chain_verified: true`: it says exactly what is missing instead of + * passing. + */ +import { db } from '../db'; +import type { AnchorBindingRow, AnchorReplayStore, AnchorTerms } from './payment-anchor-verify'; + +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +const HEX32 = /^0x[0-9a-fA-F]{64}$/; + +/** Load a contract's payment terms. null = no such contract. Throws when the read fails. */ +export async function dbAnchorTerms(contractId: string): Promise { + if (!UUID.test(contractId)) return null; // service_contracts.id is a uuid; anything else is not a contract + + const { data: c, error: cErr } = await db + .from('service_contracts') + .select('id, provider_agent_id, agreed_price_usdc_raw') + .eq('id', contractId) + .maybeSingle(); + if (cErr) throw new Error('service_contracts read failed'); + if (!c) return null; + + const { data: p, error: pErr } = await db + .from('repid_agents') + .select('wallet_address') + .eq('id', (c as any).provider_agent_id) + .maybeSingle(); + if (pErr) throw new Error('repid_agents read failed'); + + // More than one settlement row for a contract is itself an anomaly: maybeSingle errors, which + // surfaces as NOT_CHECKED rather than picking one. + const { data: s, error: sErr } = await db + .from('x402_settlements') + .select('tx_hash, payer_address, is_simulated') + .eq('idempotency_key', contractId) + .maybeSingle(); + if (sErr) throw new Error('x402_settlements read failed'); + + const recordedTx = + s && (s as any).is_simulated === false && HEX32.test(String((s as any).tx_hash ?? '')) ? String((s as any).tx_hash) : null; + + let units: bigint; + try { + units = BigInt((c as any).agreed_price_usdc_raw ?? 0); + } catch { + units = 0n; + } + + return { + contractId, + payeeAddress: (p as any)?.wallet_address ?? null, + claimedUnits: units, + payerAddress: recordedTx ? ((s as any).payer_address ?? null) : null, + recordedTxHash: recordedTx, + }; +} + +/** The replay table. Any read or write error throws, which the verifier reports as NOT_CHECKED. */ +export function dbAnchorReplayStore(): AnchorReplayStore { + return { + async find(chainId, txHash) { + const { data, error } = await db + .from('payment_anchor_claims') + .select('contract_id') + .eq('chain_id', chainId) + .eq('tx_hash', txHash.toLowerCase()) + .maybeSingle(); + if (error) throw new Error('payment_anchor_claims read failed'); + return data ? { contract_id: String((data as any).contract_id) } : null; + }, + async bind(row: AnchorBindingRow) { + const { error } = await db.from('payment_anchor_claims').insert(row); + if (!error) return 'ok'; + if (String(error.code) === '23505') return 'duplicate'; + throw new Error('payment_anchor_claims write failed'); + }, + }; +} diff --git a/src/services/payment-anchor-verify.ts b/src/services/payment-anchor-verify.ts new file mode 100644 index 000000000..201076137 --- /dev/null +++ b/src/services/payment-anchor-verify.ts @@ -0,0 +1,389 @@ +/** + * payment-anchor-verify.ts — is this payment anchor real, paid, bound to its contract, and new? + * + * THE GAP (E2E eval 2026-11-16, §3a and gap 4). An x402 payment anchor was accepted on SHAPE: + * `linkPaymentProof` checks a 0x-prefixed 32-byte hash and a chain id, and nothing else unless a + * caller opts into `requireVerified`. The eval passed a made-up hash through the repo's own trust + * harness and turned an UNCERTAIN outcome into SUCCESS_AUDITED, delta +25. A reputation that can + * be earned by typing 64 hex characters costs nothing to farm. + * + * WHAT THIS CHECKS, in this order, each from something the caller cannot write: + * 1. shape and chain (Base Sepolia only); + * 2. the anchor names a contract, and the contract exists in OUR records. The payee, the payer + * and the price come from that record, never from the caller: the caller supplies only + * a contract id and a tx hash; + * 3. when the contract already has a recorded settlement tx, the anchor is that tx; + * 4. the tx has not anchored anything before (the replay table); + * 5. on chain: a canonical-USDC `Transfer` to the payee of at least the contract price, + * from the recorded payer when one is recorded, net of anything the payee sent back + * in the same tx. An EIP-3009 `AuthorizationUsed` beside it marks it as an x402 settlement; + * 6. the tx is then bound to this contract, so it cannot anchor a second one. + * + * THREE ANSWERS, NOT TWO. VERIFIED, REFUSED (we looked, and the answer is no), or NOT_CHECKED + * (we could not look). An RPC that fails, times out or refuses is NOT_CHECKED: never a pass, and + * never a refusal, because reporting an outage as a bad payment turns an infrastructure problem + * into an accusation. NOT_CHECKED still does not earn: an unverified anchor is a claim. + * + * The RPC error TEXT never reaches an answer. ethers v6 puts the request URL, key and all, in the + * message of a server error; `x402-settlement-verifier.ts` withholds it, and this module only ever + * reports fixed codes. + * + * MODE (`PAYMENT_ANCHOR_VERIFY_MODE`): + * unset / 'off' nothing is read, nothing is logged, nothing changes. The default. + * 'shadow' check every anchor, log what would be refused, record the binding. Changes + * no delta and no score. + * 'enforce' REFUSED IN THIS BUILD. Behaves exactly as 'shadow' and says so loudly. + * Turning it on strips a non-VERIFIED anchor before scoring, which moves money- + * backed reputation: that is Sean's call, in its own MAJOR PR (CLAUDE_RULES r31). + * anything else a typo: said loudly, behaves as 'shadow' (records, moves nothing). + * + * This module does no I/O of its own. The chain read is `verifySettlement`; the contract terms and + * the replay table come in as dependencies (`payment-anchor-db.ts` holds the Supabase versions), so + * every property here is tested offline. + */ +import { DEFAULT_CHAIN_ID } from './x402-outcome-link'; +import { verifySettlement, type VerifySettlementResult } from './x402-settlement-verifier'; + +/** Canonical Base Sepolia USDC. Pinned here, not read from env or from the caller. */ +export const ANCHOR_USDC = '0x036CbD53842c5426634e7929541eC2318f3dCF7e'; + +/** How long one chain read may take before the answer is NOT_CHECKED. */ +export const DEFAULT_ANCHOR_RPC_TIMEOUT_MS = 10_000; + +export type PaymentAnchorVerifyMode = 'off' | 'shadow' | 'enforce'; + +export interface PaymentAnchorModeReading { + /** What the environment asked for. 'invalid' = an unrecognised value. */ + requested: PaymentAnchorVerifyMode | 'invalid'; + /** What actually runs. Never 'enforce' in this build. */ + effective: 'off' | 'shadow'; + /** Set when the requested mode was not honoured, and why. */ + note?: string; +} + +/** + * Read `PAYMENT_ANCHOR_VERIFY_MODE`. 'enforce' and typos both run as 'shadow' and log once per + * process, so a misconfiguration is visible without flooding the log on every anchor. + */ +const warned = new Set(); +export function paymentAnchorVerifyMode( + raw: string | undefined = process.env.PAYMENT_ANCHOR_VERIFY_MODE, +): PaymentAnchorModeReading { + const v = (raw ?? '').trim().toLowerCase(); + if (v === '' || v === 'off') return { requested: 'off', effective: 'off' }; + if (v === 'shadow') return { requested: 'shadow', effective: 'shadow' }; + const reading: PaymentAnchorModeReading = + v === 'enforce' + ? { + requested: 'enforce', + effective: 'shadow', + note: 'enforce is refused in this build (Sean decides, in its own PR); running as shadow: checks and records, moves nothing', + } + : { + requested: 'invalid', + effective: 'shadow', + note: `PAYMENT_ANCHOR_VERIFY_MODE=${JSON.stringify(raw)} is not off|shadow|enforce; running as shadow: checks and records, moves nothing`, + }; + if (!warned.has(v)) { + warned.add(v); + console.error(`[payment-anchor] ${reading.note}`); + } + return reading; +} + +/** What our own records say this contract's payment must look like. */ +export interface AnchorTerms { + contractId: string; + /** The provider's wallet: who must have RECEIVED the money. Null when we do not know it. */ + payeeAddress: string | null; + /** The agreed price, in USDC's smallest unit (6 decimals). */ + claimedUnits: bigint; + /** Who paid, when a settlement for this contract was recorded. Null otherwise. */ + payerAddress: string | null; + /** The settlement tx recorded for this contract, when there is one. */ + recordedTxHash: string | null; +} + +export interface AnchorBindingRow { + chain_id: number; + /** Lowercase. */ + tx_hash: string; + contract_id: string; + payee_address: string; + payer_address: string | null; + amount_units: string; + settlement_kind: AnchorSettlementKind; + verified_at: string; +} + +/** One tx anchors at most one contract, once. Backed by `payment_anchor_claims` in production. */ +export interface AnchorReplayStore { + find(chainId: number, txHash: string): Promise<{ contract_id: string } | null>; + /** 'duplicate' when the tx is already bound (a unique violation): the race was lost. */ + bind(row: AnchorBindingRow): Promise<'ok' | 'duplicate'>; +} + +export interface AnchorDeps { + loadTerms(contractId: string): Promise; + replay: AnchorReplayStore; + timeoutMs?: number; + minConfirmations?: number; + now?: () => Date; +} + +export interface AnchorClaim { + txHash: string; + chainId: number; + /** The contract this payment is said to settle. Required: an unbound anchor is refused. */ + contractId: string | null | undefined; +} + +export type AnchorVerdict = 'VERIFIED' | 'REFUSED' | 'NOT_CHECKED'; +export type AnchorSettlementKind = 'eip3009' | 'transfer'; + +export type AnchorReason = + | 'verified' + // REFUSED: we looked, and the answer is no. + | 'malformed_tx_hash' + | 'wrong_chain' + | 'contract_unbound' + | 'contract_unknown' + | 'no_claimed_value' + | 'contract_tx_mismatch' + | 'replay_same_contract' + | 'replay_other_contract' + | 'tx_not_found' + | 'tx_reverted' + | 'wrong_token' + | 'transfer_elsewhere' + | 'no_transfer_to_payee' + | 'below_claimed_value' + | 'payer_mismatch' + | 'self_payment' + | 'refunded_in_tx' + // NOT_CHECKED: we could not look. + | 'terms_unreadable' + | 'payee_unknown' + | 'rpc_unreachable' + | 'rpc_timeout' + | 'insufficient_confirmations' + | 'replay_store_unreachable'; + +export interface AnchorCheck { + verdict: AnchorVerdict; + reason: AnchorReason; + contract_id: string | null; + tx_hash: string; + chain_id: number; + /** Set once the chain was read and the transfer was found. */ + settlement_kind?: AnchorSettlementKind; + /** Units the payee netted from the payer in this tx, as a decimal string. */ + net_units?: string; + /** For a replay: the contract the tx is already bound to. */ + bound_contract_id?: string; + /** True when the chain alone would have verified it (the replay store was not reachable). */ + chain_verified?: boolean; +} + +const HEX32 = /^0x[0-9a-fA-F]{64}$/; +const ADDR = /^0x[0-9a-fA-F]{40}$/; + +function lc(s: string | null | undefined): string { + return (s ?? '').trim().toLowerCase(); +} + +class AnchorTimeout extends Error {} + +function withTimeout(p: Promise, ms: number): Promise { + let timer: ReturnType | undefined; + const t = new Promise((_, reject) => { + timer = setTimeout(() => reject(new AnchorTimeout()), ms); + }); + return Promise.race([p, t]).finally(() => { + if (timer) clearTimeout(timer); + }); +} + +/** Map the settlement verifier's fixed code to this module's answer. Unknown codes do not pass. */ +function fromSettlement(r: VerifySettlementResult): { verdict: AnchorVerdict; reason: AnchorReason } { + switch (r.code) { + case 'verified': + return { verdict: 'VERIFIED', reason: 'verified' }; + case 'tx_not_found': + case 'tx_reverted': + case 'wrong_token': + case 'transfer_elsewhere': + case 'no_transfer_to_payee': + case 'below_claimed_value': + case 'malformed_tx_hash': + return { verdict: 'REFUSED', reason: r.code }; + case 'insufficient_confirmations': + // Too early is not wrong: ask again later. + return { verdict: 'NOT_CHECKED', reason: 'insufficient_confirmations' }; + case 'no_payee': + return { verdict: 'NOT_CHECKED', reason: 'payee_unknown' }; + default: + // rpc_unreachable, unsupported_chain, token_not_configured, and any code added later. + return { verdict: 'NOT_CHECKED', reason: 'rpc_unreachable' }; + } +} + +/** + * Verify one payment anchor. Never throws: every failure is an answer. + */ +export async function verifyPaymentAnchor(claim: AnchorClaim, deps: AnchorDeps): Promise { + const txHash = lc(claim.txHash); + const contractId = typeof claim.contractId === 'string' && claim.contractId.trim() ? claim.contractId.trim() : null; + const base = { contract_id: contractId, tx_hash: txHash, chain_id: claim.chainId }; + const refuse = (reason: AnchorReason, extra: Partial = {}): AnchorCheck => ({ + verdict: 'REFUSED', + reason, + ...base, + ...extra, + }); + const notChecked = (reason: AnchorReason, extra: Partial = {}): AnchorCheck => ({ + verdict: 'NOT_CHECKED', + reason, + ...base, + ...extra, + }); + + // 1. Shape and chain. + if (!HEX32.test(txHash)) return refuse('malformed_tx_hash'); + if (claim.chainId !== DEFAULT_CHAIN_ID) return refuse('wrong_chain'); + + // 2. The anchor must name a contract we know. Its terms come from our records, not the caller. + if (!contractId) return refuse('contract_unbound'); + let terms: AnchorTerms | null; + try { + terms = await deps.loadTerms(contractId); + } catch { + return notChecked('terms_unreadable'); + } + if (!terms) return refuse('contract_unknown'); + if (typeof terms.claimedUnits !== 'bigint' || terms.claimedUnits <= 0n) return refuse('no_claimed_value'); + const payee = lc(terms.payeeAddress); + if (!ADDR.test(payee)) return notChecked('payee_unknown'); + const payer = ADDR.test(lc(terms.payerAddress)) ? lc(terms.payerAddress) : null; + + // 3. A contract with a recorded settlement is bound to THAT tx. + const recorded = lc(terms.recordedTxHash); + if (HEX32.test(recorded) && recorded !== txHash) return refuse('contract_tx_mismatch'); + + // 4. Replay, from our own table. Checked before the chain so a known replay is refused even + // while the RPC is down. A store we cannot read does not stop the chain check: the chain's + // answer is still worth recording, but the anchor cannot be VERIFIED without it. + let replayStoreDown = false; + try { + const prior = await deps.replay.find(claim.chainId, txHash); + if (prior) { + return refuse(prior.contract_id === contractId ? 'replay_same_contract' : 'replay_other_contract', { + bound_contract_id: prior.contract_id, + }); + } + } catch { + replayStoreDown = true; + } + + // 5. The chain. Canonical USDC only, at least the contract price, to the payee. + let settlement: VerifySettlementResult; + try { + settlement = await withTimeout( + verifySettlement({ + txHash, + payeeAddress: payee, + claimedValueUsdc: 0, + claimedUnits: terms.claimedUnits, + tokenAddress: ANCHOR_USDC, + chainId: claim.chainId, + ...(deps.minConfirmations !== undefined ? { minConfirmations: deps.minConfirmations } : {}), + }), + deps.timeoutMs ?? DEFAULT_ANCHOR_RPC_TIMEOUT_MS, + ); + } catch (e) { + return notChecked(e instanceof AnchorTimeout ? 'rpc_timeout' : 'rpc_unreachable'); + } + const chain = fromSettlement(settlement); + if (chain.verdict !== 'VERIFIED') { + return chain.verdict === 'REFUSED' ? refuse(chain.reason) : notChecked(chain.reason); + } + + // The total reached the payee. Now WHO paid, and whether it stayed there. + const a = settlement.analysis; + if (!a) return notChecked('rpc_unreachable'); // a verified result always carries its analysis + if (a.inflowBySender[payee] !== undefined) return refuse('self_payment'); + const credited = payer + ? a.inflowBySender[payer] ?? 0n + : Object.values(a.inflowBySender).reduce((s, v) => s + v, 0n); + if (payer && credited === 0n) return refuse('payer_mismatch'); + const net = credited - a.outflowFromPayee; + if (net < terms.claimedUnits) { + return refuse(a.outflowFromPayee > 0n ? 'refunded_in_tx' : 'below_claimed_value', { net_units: net.toString() }); + } + const senders = payer ? [payer] : Object.keys(a.inflowBySender); + const kind: AnchorSettlementKind = a.authorizationUsedBy.some((x) => senders.includes(x)) ? 'eip3009' : 'transfer'; + const paid = { settlement_kind: kind, net_units: net.toString() }; + + // 6. Bind the tx to this contract. The unique key is the authority; the pre-check above only + // saves an RPC call. Losing the race is a replay. + if (replayStoreDown) return notChecked('replay_store_unreachable', { ...paid, chain_verified: true }); + let bound: 'ok' | 'duplicate'; + try { + bound = await deps.replay.bind({ + chain_id: claim.chainId, + tx_hash: txHash, + contract_id: contractId, + payee_address: payee, + payer_address: payer, + amount_units: net.toString(), + settlement_kind: kind, + verified_at: (deps.now?.() ?? new Date()).toISOString(), + }); + } catch { + return notChecked('replay_store_unreachable', { ...paid, chain_verified: true }); + } + if (bound === 'duplicate') { + let other: string | undefined; + try { + other = (await deps.replay.find(claim.chainId, txHash))?.contract_id; + } catch { + other = undefined; + } + return refuse(other === contractId ? 'replay_same_contract' : 'replay_other_contract', { + ...paid, + ...(other ? { bound_contract_id: other } : {}), + }); + } + + return { verdict: 'VERIFIED', reason: 'verified', ...base, ...paid }; +} + +export interface ShadowAnchorResult extends AnchorCheck { + mode: PaymentAnchorModeReading; + /** Under enforce, this anchor would be stripped before scoring. */ + would_refuse: boolean; +} + +/** + * The flag-gated entry point. 'off' returns null WITHOUT reading anything. Otherwise the anchor is + * checked and the answer logged; the caller records it and changes nothing else. + */ +export async function shadowCheckPaymentAnchor( + claim: AnchorClaim, + deps: AnchorDeps, + mode: PaymentAnchorModeReading = paymentAnchorVerifyMode(), +): Promise { + if (mode.effective === 'off') return null; + const check = await verifyPaymentAnchor(claim, deps); + const wouldRefuse = check.verdict !== 'VERIFIED'; + if (check.verdict === 'REFUSED') { + console.warn( + `[payment-anchor] shadow: would REFUSE anchor reason=${check.reason} contract=${check.contract_id ?? 'none'} tx=${check.tx_hash}`, + ); + } else if (check.verdict === 'NOT_CHECKED') { + console.warn( + `[payment-anchor] shadow: NOT_CHECKED reason=${check.reason} contract=${check.contract_id ?? 'none'} tx=${check.tx_hash} (would not earn under enforce)`, + ); + } + return { ...check, mode, would_refuse: wouldRefuse }; +} diff --git a/src/services/settled-interaction-scorer.ts b/src/services/settled-interaction-scorer.ts index 129f34f7a..3698574c0 100644 --- a/src/services/settled-interaction-scorer.ts +++ b/src/services/settled-interaction-scorer.ts @@ -22,6 +22,12 @@ */ import { buildShadowScoreEvent, type SettledInteraction, type ShadowScoreResult } from './shadow-scoring'; import { resolvePaymentProof, type VerifySettlementResult } from './x402-settlement-verifier'; +import { + paymentAnchorVerifyMode, + shadowCheckPaymentAnchor, + type AnchorDeps, + type ShadowAnchorResult, +} from './payment-anchor-verify'; export interface ScoreSettledInteractionOptions { /** @@ -34,11 +40,77 @@ export interface ScoreSettledInteractionOptions { tokenAddress?: string | null; policyVersion?: string; mode?: 'shadow' | 'applied'; + /** Test seam for the payment-anchor check (see `anchorShadow`). Production reads service_contracts / x402_settlements / payment_anchor_claims. */ + anchorDeps?: AnchorDeps; } export interface ScoredSettlement extends ShadowScoreResult { /** What the chain actually said. Absent only when no proof was supplied at all. */ settlement?: VerifySettlementResult; + /** The payment-anchor check. Absent when PAYMENT_ANCHOR_VERIFY_MODE is off or no proof was supplied. */ + anchorCheck?: ShadowAnchorResult; +} + +/** + * Run the flag-gated payment-anchor check (payment-anchor-verify.ts). It takes the payee, payer and + * price from `interaction.contractId`'s record, binds the tx to that contract and refuses a replay. + * The answer goes to `metadata.payment.anchor_check`; no delta changes. + * + * Off: returns undefined and reads nothing (the Supabase adapter is not even imported). Never throws + * into scoring. + */ +async function anchorShadow( + interaction: SettledInteraction, + opts: ScoreSettledInteractionOptions, +): Promise { + const claimed = interaction.paymentProof; + if (!claimed) return undefined; + const mode = paymentAnchorVerifyMode(); + if (mode.effective === 'off') return undefined; + try { + const deps: AnchorDeps = + opts.anchorDeps ?? + (await import('./payment-anchor-db.js').then((m) => ({ loadTerms: m.dbAnchorTerms, replay: m.dbAnchorReplayStore() }))); + return ( + (await shadowCheckPaymentAnchor( + { txHash: claimed.txHash, chainId: claimed.chainId, contractId: interaction.contractId ?? null }, + deps, + mode, + )) ?? undefined + ); + } catch { + return undefined; + } +} + +/** Record the anchor check beside the payment metadata. Shadow: the delta is untouched. */ +function withAnchor(scored: ScoredSettlement, check: ShadowAnchorResult | undefined): ScoredSettlement { + if (!check) return scored; + const payment = (scored.row.metadata['payment'] ?? {}) as Record; + return { + ...scored, + anchorCheck: check, + row: { + ...scored.row, + metadata: { + ...scored.row.metadata, + payment: { + ...payment, + anchor_check: { + mode: check.mode.effective, + requested_mode: check.mode.requested, + verdict: check.verdict, + reason: check.reason, + would_refuse: check.would_refuse, + contract_id: check.contract_id, + ...(check.settlement_kind ? { settlement_kind: check.settlement_kind } : {}), + ...(check.net_units ? { net_units: check.net_units } : {}), + ...(check.bound_contract_id ? { bound_contract_id: check.bound_contract_id } : {}), + }, + }, + }, + }, + }; } /** @@ -63,6 +135,8 @@ export async function scoreSettledInteraction( }); } + const anchor = await anchorShadow(interaction, opts); + if (!opts.payeeAddress) { // A proof we cannot resolve for want of a payee address must not be trusted // just because it is well-formed. Strip it and say why: the outcome is @@ -77,9 +151,10 @@ export async function scoreSettledInteraction( const settlement: VerifySettlementResult = { verified: false, evidence: 'NOT_CHECKED', + code: 'no_payee', reason: 'no payee address supplied — settlement could not be resolved', }; - return { ...built, settlement, ...annotate(built, settlement) }; + return withAnchor({ ...built, settlement, ...annotate(built, settlement) }, anchor); } const { proof, result } = await resolvePaymentProof(claimed, { @@ -106,7 +181,7 @@ export async function scoreSettledInteraction( }, ); - return { ...built, settlement: result, ...annotate(built, result) }; + return withAnchor({ ...built, settlement: result, ...annotate(built, result) }, anchor); } /** diff --git a/src/services/x402-settlement-verifier.ts b/src/services/x402-settlement-verifier.ts index 4d2570ada..75ebd51e1 100644 --- a/src/services/x402-settlement-verifier.ts +++ b/src/services/x402-settlement-verifier.ts @@ -53,8 +53,24 @@ import { DEFAULT_CHAIN_ID } from './x402-outcome-link'; const ERC20_ABI = ['event Transfer(address indexed from, address indexed to, uint256 value)']; const TRANSFER_TOPIC = ethers.id('Transfer(address,address,uint256)'); +/** + * EIP-3009 `AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce)`. USDC emits it + * for `transferWithAuthorization`, which is how an x402 `exact` settlement moves money. It names + * the payer but neither the payee nor the amount, so it never verifies a payment by itself; the + * `Transfer` beside it does that. It is reported so a reader can tell an x402 settlement from a + * plain transfer. + */ +const AUTHORIZATION_USED_TOPIC = ethers.id('AuthorizationUsed(address,bytes32)'); const iface = new ethers.Interface(ERC20_ABI); +/** + * The RPC error text is never copied into a result. ethers v6 puts the request URL in the + * message of a SERVER_ERROR (`info={ "requestUrl": ... }`), and a hosted RPC URL carries its API + * key. A `reason` lands in score-event metadata, so echoing it would publish the key. MEASURED + * 2026-11-16 against ethers 6.16.0 and an RPC answering 401. + */ +const RPC_DETAIL_WITHHELD = 'detail withheld: an RPC error message can carry the provider URL and its key'; + /** USDC has 6 decimals. A whole-dollar figure times this is the smallest unit. */ export const USDC_DECIMALS = 6; @@ -82,6 +98,12 @@ export interface VerifySettlementInput { payeeAddress: string; /** Service value the caller claims, in whole USDC. Verified as a lower bound. */ claimedValueUsdc: number; + /** + * The same claim in the smallest unit. When set it wins over `claimedValueUsdc`, so a value + * that is already an integer (a contract's `agreed_price_usdc_raw`) is not round-tripped + * through a float. + */ + claimedUnits?: bigint; /** Canonical token. Defaults to the configured USDC address. */ tokenAddress?: string | null; minConfirmations?: number; @@ -91,6 +113,38 @@ export interface VerifySettlementInput { export type SettlementEvidence = 'MEASURED' | 'NOT_CHECKED'; +/** + * A fixed code beside the prose `reason`, so a caller can branch on the answer without parsing + * English. Every result carries one. + */ +export type SettlementCode = + | 'malformed_tx_hash' + | 'no_payee' + | 'token_not_configured' + | 'unsupported_chain' + | 'rpc_unreachable' + | 'tx_not_found' + | 'tx_reverted' + | 'insufficient_confirmations' + | 'wrong_token' + | 'transfer_elsewhere' + | 'no_transfer_to_payee' + | 'below_claimed_value' + | 'verified'; + +/** + * What the token's logs in the receipt said, for a caller that must check more than the total + * (who paid, whether the payee sent money back in the same tx). Addresses are lowercase. + */ +export interface SettlementLogAnalysis { + /** Canonical-token units received by the payee, per sender. */ + inflowBySender: Record; + /** Canonical-token units the payee sent out in the same tx (a refund, or a pass-through). */ + outflowFromPayee: bigint; + /** Authorizers named by an EIP-3009 `AuthorizationUsed` the canonical token emitted. */ + authorizationUsedBy: string[]; +} + export interface VerifySettlementResult { /** True ONLY when a transfer of at least the claimed value to the payee was observed. */ verified: boolean; @@ -99,10 +153,13 @@ export interface VerifySettlementResult { * an absence, not a finding — never report it as a failed verification. */ evidence: SettlementEvidence; + code: SettlementCode; reason: string; observedAmount?: bigint; confirmations?: number; blockNumber?: number; + /** Present whenever the receipt's logs were read. */ + analysis?: SettlementLogAnalysis; } function eqAddr(a?: string | null, b?: string | null): boolean { @@ -135,45 +192,46 @@ export async function verifySettlement( if (!/^0x[0-9a-fA-F]{64}$/.test(input.txHash ?? '')) { // A shape failure is a finding, not an absence — we did look, at the input. - return { verified: false, evidence: 'MEASURED', reason: 'tx hash is not a 32-byte hex hash' }; + return { verified: false, evidence: 'MEASURED', code: 'malformed_tx_hash', reason: 'tx hash is not a 32-byte hex hash' }; } if (!input.payeeAddress) { - return { verified: false, evidence: 'NOT_CHECKED', reason: 'no payee address to verify against' }; + return { verified: false, evidence: 'NOT_CHECKED', code: 'no_payee', reason: 'no payee address to verify against' }; } if (!tokenAddress) { - return { verified: false, evidence: 'NOT_CHECKED', reason: 'token address not configured' }; + return { verified: false, evidence: 'NOT_CHECKED', code: 'token_not_configured', reason: 'token address not configured' }; } if (chainId !== DEFAULT_CHAIN_ID) { return { verified: false, evidence: 'NOT_CHECKED', + code: 'unsupported_chain', reason: `no provider configured for chain ${chainId}; this verifier reads chain ${DEFAULT_CHAIN_ID}`, }; } - const claimed = usdcToSmallestUnit(input.claimedValueUsdc); + const claimed = input.claimedUnits !== undefined ? input.claimedUnits : usdcToSmallestUnit(input.claimedValueUsdc); const provider = providerFactory(); let receipt: ethers.TransactionReceipt | null; try { receipt = await provider.getTransactionReceipt(input.txHash); - } catch (e: any) { - return { verified: false, evidence: 'NOT_CHECKED', reason: `rpc error fetching receipt: ${e?.message ?? e}` }; + } catch { + return { verified: false, evidence: 'NOT_CHECKED', code: 'rpc_unreachable', reason: `rpc error fetching receipt (${RPC_DETAIL_WITHHELD})` }; } if (!receipt) { // An unmined or unknown tx IS an observation: we asked and the chain has no // such settlement. That is a finding. - return { verified: false, evidence: 'MEASURED', reason: 'tx not found on chain (unmined or unknown)' }; + return { verified: false, evidence: 'MEASURED', code: 'tx_not_found', reason: 'tx not found on chain (unmined or unknown)' }; } if ((receipt as any).status === 0) { - return { verified: false, evidence: 'MEASURED', reason: 'tx reverted — no value moved' }; + return { verified: false, evidence: 'MEASURED', code: 'tx_reverted', reason: 'tx reverted — no value moved' }; } let head: number; try { head = await provider.getBlockNumber(); - } catch (e: any) { - return { verified: false, evidence: 'NOT_CHECKED', reason: `rpc error fetching head: ${e?.message ?? e}` }; + } catch { + return { verified: false, evidence: 'NOT_CHECKED', code: 'rpc_unreachable', reason: `rpc error fetching head (${RPC_DETAIL_WITHHELD})` }; } const blockNumber = receipt.blockNumber; @@ -182,6 +240,7 @@ export async function verifySettlement( return { verified: false, evidence: 'MEASURED', + code: 'insufficient_confirmations', reason: `insufficient confirmations: ${confirmations} < ${minConfirmations}`, confirmations, blockNumber, @@ -191,16 +250,24 @@ export async function verifySettlement( let observed = 0n; let sawWrongToken = false; let sawTransferElsewhere = false; + const analysis: SettlementLogAnalysis = { inflowBySender: {}, outflowFromPayee: 0n, authorizationUsedBy: [] }; for (const log of receipt.logs ?? []) { if (!log.topics || log.topics.length === 0) continue; - if (log.topics[0] !== TRANSFER_TOPIC) continue; + const topic0 = String(log.topics[0]).toLowerCase(); // The emitter check is the load-bearing one: a Transfer topic from any // address other than the canonical token is not a USDC transfer, whatever // its arguments say. const isUsdc = eqAddr(log.address, tokenAddress); + if (topic0 === AUTHORIZATION_USED_TOPIC) { + const authorizer = log.topics[1] ? `0x${String(log.topics[1]).slice(-40)}`.toLowerCase() : null; + if (isUsdc && authorizer) analysis.authorizationUsedBy.push(authorizer); + continue; + } + if (topic0 !== TRANSFER_TOPIC) continue; + let parsed: ethers.LogDescription | null = null; try { parsed = iface.parseLog({ topics: [...log.topics], data: log.data }); @@ -209,6 +276,7 @@ export async function verifySettlement( } if (!parsed) continue; + const from = parsed.args?.from as string; const to = parsed.args?.to as string; const value = parsed.args?.value as bigint; @@ -216,8 +284,12 @@ export async function verifySettlement( if (eqAddr(to, input.payeeAddress)) sawWrongToken = true; continue; } - if (eqAddr(to, input.payeeAddress)) observed += value; - else sawTransferElsewhere = true; + if (eqAddr(from, input.payeeAddress)) analysis.outflowFromPayee += value; + if (eqAddr(to, input.payeeAddress)) { + observed += value; + const sender = String(from).toLowerCase(); + analysis.inflowBySender[sender] = (analysis.inflowBySender[sender] ?? 0n) + value; + } else sawTransferElsewhere = true; } if (observed === 0n) { @@ -225,26 +297,32 @@ export async function verifySettlement( return { verified: false, evidence: 'MEASURED', + code: 'wrong_token', reason: 'the transfer to the payee was a different token, not USDC', confirmations, blockNumber, + analysis, }; } if (sawTransferElsewhere) { return { verified: false, evidence: 'MEASURED', + code: 'transfer_elsewhere', reason: 'a USDC transfer occurred but did not land at the payee address', confirmations, blockNumber, + analysis, }; } return { verified: false, evidence: 'MEASURED', + code: 'no_transfer_to_payee', reason: 'no USDC transfer to the payee found in this tx', confirmations, blockNumber, + analysis, }; } @@ -255,20 +333,24 @@ export async function verifySettlement( return { verified: false, evidence: 'MEASURED', + code: 'below_claimed_value', reason: `settlement moved ${observed} but the claimed service value is ${claimed} (smallest unit)`, observedAmount: observed, confirmations, blockNumber, + analysis, }; } return { verified: true, evidence: 'MEASURED', + code: 'verified', reason: `observed ${observed} USDC (smallest unit) to the payee at ${confirmations} confirmations`, observedAmount: observed, confirmations, blockNumber, + analysis, }; } diff --git a/supabase/migrations/20261116130000_payment_anchor_claims.rollback.sql b/supabase/migrations/20261116130000_payment_anchor_claims.rollback.sql new file mode 100644 index 000000000..a55a7fb13 --- /dev/null +++ b/supabase/migrations/20261116130000_payment_anchor_claims.rollback.sql @@ -0,0 +1,4 @@ +-- Rollback for 20261116130000_payment_anchor_claims.sql (DRAFT, not applied). +-- Safe while PAYMENT_ANCHOR_VERIFY_MODE is off: nothing else reads the table. Under shadow, the +-- verifier reports NOT_CHECKED replay_store_unreachable once the table is gone, and changes nothing. +drop table if exists public.payment_anchor_claims; diff --git a/supabase/migrations/20261116130000_payment_anchor_claims.sql b/supabase/migrations/20261116130000_payment_anchor_claims.sql new file mode 100644 index 000000000..75a3d1c90 --- /dev/null +++ b/supabase/migrations/20261116130000_payment_anchor_claims.sql @@ -0,0 +1,48 @@ +-- DRAFT — NOT APPLIED. Sean applies prod DDL (CLAUDE_RULES r6/r28). Nothing reads or writes this +-- table unless PAYMENT_ANCHOR_VERIFY_MODE is set (default off). +-- +-- PAYMENT ANCHOR CLAIMS: one on-chain settlement anchors at most one contract, once. +-- +-- Why. A payment anchor (an x402 settlement tx hash) is what lets a high-value success earn +-- RepID: wash-trading reputation is meant to require wash-trading money. Without a replay table, +-- one real 1 USDC payment can be presented again and again, for the same contract or for any +-- other, and every presentation verifies on chain because the tx is real. The E2E eval of +-- 2026-11-16 (gap 4) found the anchor accepted on shape alone; this table is the "once" half of +-- the fix. src/services/payment-anchor-verify.ts is the other half: it reads the receipt and binds +-- the tx to the contract named by our own records. +-- +-- The UNIQUE key is the authority, not the code. The verifier pre-checks with a SELECT only to skip +-- an RPC call; two concurrent presentations of one tx race on this constraint, and the loser gets +-- 23505, which the code reports as a replay. +-- +-- x402_settlements.tx_hash already exists but is NOT unique (only idx_x402_settlements_tx_hash, +-- a plain btree, MEASURED 2026-11-16), and it records server-side settlements, not anchors +-- presented by a caller. This is a separate table so a future reader never has to wonder whether a +-- row was the engine settling or a caller anchoring. +-- +-- Service role only: RLS on, no policies, no grants to anon/authenticated. + +create table if not exists public.payment_anchor_claims ( + id uuid primary key default gen_random_uuid(), + chain_id integer not null, + tx_hash text not null check (tx_hash ~ '^0x[0-9a-f]{64}$'), -- lowercase, enforced + contract_id uuid not null, + payee_address text not null check (payee_address ~ '^0x[0-9a-f]{40}$'), + payer_address text check (payer_address is null or payer_address ~ '^0x[0-9a-f]{40}$'), + amount_units numeric(78, 0) not null check (amount_units > 0), -- USDC smallest unit + settlement_kind text not null check (settlement_kind in ('eip3009', 'transfer')), + verified_at timestamptz not null, + created_at timestamptz not null default now() +); + +create unique index if not exists payment_anchor_claims_tx_uidx + on public.payment_anchor_claims (chain_id, tx_hash); + +create index if not exists payment_anchor_claims_contract_idx + on public.payment_anchor_claims (contract_id); + +alter table public.payment_anchor_claims enable row level security; +revoke all on public.payment_anchor_claims from anon, authenticated; + +comment on table public.payment_anchor_claims is + 'One settlement tx anchors at most one contract, once (unique chain_id, tx_hash). Written by src/services/payment-anchor-db.ts only after the receipt verified on chain. Read by the replay pre-check.'; diff --git a/tests/fixtures/payment-anchor/base-sepolia-x402-settlement.json b/tests/fixtures/payment-anchor/base-sepolia-x402-settlement.json new file mode 100644 index 000000000..ebe13ced9 --- /dev/null +++ b/tests/fixtures/payment-anchor/base-sepolia-x402-settlement.json @@ -0,0 +1,40 @@ +{ + "_source": { + "what": "A real x402 settlement on Base Sepolia, recorded so tests replay it offline. Public chain data only.", + "chain_id": 84532, + "tx_hash": "0xdd932691421cdd8da4a67b3283e2edd430483078384ddbef750cb17725c8a60f", + "block_number": 59543202, + "fetched_via": "eth_getTransactionReceipt + eth_getTransactionByHash, https://sepolia.base.org (read-only)", + "fetched_at": "2026-11-16" + }, + "tx": { + "to": "0x036cbd53842c5426634e7929541ec2318f3dcf7e", + "selector": "0xe3ee160e" + }, + "receipt": { + "status": 1, + "blockNumber": 59543202, + "logs": [ + { + "address": "0x036cbd53842c5426634e7929541ec2318f3dcf7e", + "topics": [ + "0x98de503528ee59b575ef0c0a2576a82497bfc029a5685b209e9ec333479b10a5", + "0x000000000000000000000000df6b8215d193b11b4903d223729c3cf7a6de271d", + "0x8d9f25019d89ae8908fb1cd921b3d5ed2260df2c2358cd0a0efe3e07da3ba73f" + ], + "data": "0x", + "logIndex": 2 + }, + { + "address": "0x036cbd53842c5426634e7929541ec2318f3dcf7e", + "topics": [ + "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", + "0x000000000000000000000000df6b8215d193b11b4903d223729c3cf7a6de271d", + "0x000000000000000000000000ced17f65e03e7b3a77d5321a2d3715840317199c" + ], + "data": "0x00000000000000000000000000000000000000000000000000000000000f4240", + "logIndex": 3 + } + ] + } +} diff --git a/tests/payment-anchor-through-scorer.test.ts b/tests/payment-anchor-through-scorer.test.ts new file mode 100644 index 000000000..4f264be90 --- /dev/null +++ b/tests/payment-anchor-through-scorer.test.ts @@ -0,0 +1,243 @@ +/** + * payment-anchor-through-scorer.test.ts — the same five cases as payment-anchor-verify.test.ts, but + * driven through `scoreSettledInteraction`, the seam built for caller-supplied payment anchors. + * + * Why a second file: this one imports only modules that exist on main, so on main each case fails + * BY ASSERTION (the anchor check is absent, or the RPC text leaks), not by a missing import. That + * makes "fails on main, passes on the branch" a statement about behaviour. + * + * The anchor check is SHADOW: these tests also pin that it changes no delta, no class and no + * anchoring decision. Those inertness tests pass on main too, which is the point. + * + * The positive control is a real Base Sepolia settlement, recorded with read-only RPC and replayed + * offline (tests/fixtures/payment-anchor/). Contract ids are fabricated. + */ +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { OutcomeClass } from '../src/services/outcome-classification'; +import { scoreSettledInteraction } from '../src/services/settled-interaction-scorer'; +import { __setSettlementProviderFactory } from '../src/services/x402-settlement-verifier'; +import type { EthProviderLike } from '../src/services/deposit-verifier'; +import type { SettledInteraction } from '../src/services/shadow-scoring'; + +const fixture = JSON.parse( + readFileSync(join(__dirname, 'fixtures', 'payment-anchor', 'base-sepolia-x402-settlement.json'), 'utf8'), +); +const REAL_TX: string = fixture._source.tx_hash; +const REAL_PAYER = '0xdf6b8215d193b11b4903d223729c3cf7a6de271d'; +const REAL_PAYEE = '0xced17f65e03e7b3a77d5321a2d3715840317199c'; +const USDC = '0x036CbD53842c5426634e7929541eC2318f3dCF7e'; +const STRANGER = '0x4444444444444444444444444444444444444444'; +const HEAD = fixture.receipt.blockNumber + 10; + +const PROVIDER = '00000000-0000-0000-0000-0000000000a1'; +const CONSUMER = '00000000-0000-0000-0000-0000000000a2'; +const CONTRACT_A = '00000000-0000-0000-0000-00000000c0a1'; +const CONTRACT_B = '00000000-0000-0000-0000-00000000c0b2'; +const KEYED_RPC_ERROR = 'server response 401 (info={ "requestUrl": "https://rpc.example.invalid/v2/FAKE-RPC-KEY-7f3a" })'; + +interface Terms { + contractId: string; + payeeAddress: string | null; + claimedUnits: bigint; + payerAddress: string | null; + recordedTxHash: string | null; +} + +function installChain(mode: 'real' | 'down') { + const p: EthProviderLike = { + async getTransactionReceipt(hash: string) { + if (mode === 'down') throw new Error(KEYED_RPC_ERROR); + return (hash.toLowerCase() === REAL_TX ? JSON.parse(JSON.stringify(fixture.receipt)) : null) as never; + }, + async getBlockNumber() { + if (mode === 'down') throw new Error(KEYED_RPC_ERROR); + return HEAD; + }, + async call() { + throw new Error('not used'); + }, + }; + __setSettlementProviderFactory(() => p); +} + +/** Contract records + a replay table with production semantics (unique on chain_id, tx_hash). */ +function anchorDeps(contracts: Record>) { + const rows: Array<{ chain_id: number; tx_hash: string; contract_id: string }> = []; + return { + loadTerms: async (id: string) => + contracts[id] + ? { + contractId: id, + payeeAddress: REAL_PAYEE, + claimedUnits: 1_000_000n, + payerAddress: REAL_PAYER, + recordedTxHash: null, + ...contracts[id], + } + : null, + replay: { + async find(chainId: number, txHash: string) { + const r = rows.find((x) => x.chain_id === chainId && x.tx_hash === txHash.toLowerCase()); + return r ? { contract_id: r.contract_id } : null; + }, + async bind(row: any) { + if (rows.some((x) => x.chain_id === row.chain_id && x.tx_hash === row.tx_hash)) return 'duplicate' as const; + rows.push(row); + return 'ok' as const; + }, + }, + timeoutMs: 2_000, + }; +} + +function interaction(over: Partial = {}): SettledInteraction { + return { + interactionId: 'fabricated-anchor-1', + providerAgentId: PROVIDER, + consumerAgentId: CONSUMER, + builderId: null, + contractId: CONTRACT_A, + outcomeClass: OutcomeClass.SUCCESS_AUDITED, + halCalibratedConfidence: 0.9, + validationResponse: 95, + serviceValueUsdc: 1, + stakeExposedUsdc: 0, + priorInteractions: 12, + paymentProof: { txHash: REAL_TX, chainId: 84532, verified: true }, + ...over, + }; +} + +const CALLER_OPTS = { payeeAddress: REAL_PAYEE, tokenAddress: USDC }; +const anchorCheck = (r: any) => (r.row.metadata['payment'] as Record | undefined)?.['anchor_check']; + +let saved: string | undefined; +beforeEach(() => { + saved = process.env.PAYMENT_ANCHOR_VERIFY_MODE; + process.env.PAYMENT_ANCHOR_VERIFY_MODE = 'shadow'; + jest.spyOn(console, 'warn').mockImplementation(() => {}); + jest.spyOn(console, 'error').mockImplementation(() => {}); +}); +afterEach(() => { + if (saved === undefined) delete process.env.PAYMENT_ANCHOR_VERIFY_MODE; + else process.env.PAYMENT_ANCHOR_VERIFY_MODE = saved; + __setSettlementProviderFactory(undefined); + jest.restoreAllMocks(); +}); + +describe('shadow anchor check, through the scorer', () => { + it('1. a real transfer: VERIFIED, as an EIP-3009 settlement', async () => { + installChain('real'); + const r = await scoreSettledInteraction(interaction(), { ...CALLER_OPTS, anchorDeps: anchorDeps({ [CONTRACT_A]: {} }) } as any); + expect(r.anchored).toBe(true); + expect(anchorCheck(r)).toMatchObject({ mode: 'shadow', verdict: 'VERIFIED', settlement_kind: 'eip3009', would_refuse: false }); + }); + + it("2. the wrong recipient: the caller's payee matches the tx, but our contract record names another", async () => { + installChain('real'); + const r = await scoreSettledInteraction( + interaction(), + { ...CALLER_OPTS, anchorDeps: anchorDeps({ [CONTRACT_A]: { payeeAddress: STRANGER } }) } as any, + ); + expect(anchorCheck(r)).toMatchObject({ verdict: 'REFUSED', reason: 'transfer_elsewhere', would_refuse: true }); + }); + + it("3. too little: the caller claims 1 USDC and paid 1, but the contract's price is 2", async () => { + installChain('real'); + const r = await scoreSettledInteraction( + interaction(), + { ...CALLER_OPTS, anchorDeps: anchorDeps({ [CONTRACT_A]: { claimedUnits: 2_000_000n } }) } as any, + ); + expect(anchorCheck(r)).toMatchObject({ verdict: 'REFUSED', reason: 'below_claimed_value', would_refuse: true }); + }); + + it('4. a replay: one real payment presented for a second contract', async () => { + installChain('real'); + const deps = anchorDeps({ [CONTRACT_A]: {}, [CONTRACT_B]: {} }); + const first = await scoreSettledInteraction(interaction(), { ...CALLER_OPTS, anchorDeps: deps } as any); + const second = await scoreSettledInteraction( + interaction({ interactionId: 'fabricated-anchor-2', contractId: CONTRACT_B }), + { ...CALLER_OPTS, anchorDeps: deps } as any, + ); + expect(anchorCheck(first)).toMatchObject({ verdict: 'VERIFIED' }); + expect(anchorCheck(second)).toMatchObject({ + verdict: 'REFUSED', + reason: 'replay_other_contract', + bound_contract_id: CONTRACT_A, + would_refuse: true, + }); + }); + + it('5. RPC down: NOT_CHECKED, and no RPC URL or key anywhere in the row', async () => { + installChain('down'); + const r = await scoreSettledInteraction(interaction(), { ...CALLER_OPTS, anchorDeps: anchorDeps({ [CONTRACT_A]: {} }) } as any); + expect(anchorCheck(r)).toMatchObject({ verdict: 'NOT_CHECKED', reason: 'rpc_unreachable', would_refuse: true }); + expect(r.settlement?.evidence).toBe('NOT_CHECKED'); + expect(JSON.stringify(r.row)).not.toContain('FAKE-RPC-KEY'); + expect(r.settlement?.reason ?? '').not.toContain('rpc.example.invalid'); + }); + + it('an anchor that names no contract is refused, and the check reads no contract table', async () => { + installChain('real'); + let loaded = 0; + const deps = anchorDeps({}); + const r = await scoreSettledInteraction(interaction({ contractId: null }), { + ...CALLER_OPTS, + anchorDeps: { ...deps, loadTerms: async (id: string) => (loaded++, deps.loadTerms(id)) }, + } as any); + expect(anchorCheck(r)).toMatchObject({ verdict: 'REFUSED', reason: 'contract_unbound' }); + expect(loaded).toBe(0); + }); +}); + +describe('the shadow check moves nothing (passes on main too, by design)', () => { + async function both(build: () => Promise) { + process.env.PAYMENT_ANCHOR_VERIFY_MODE = 'off'; + const off = await build(); + process.env.PAYMENT_ANCHOR_VERIFY_MODE = 'shadow'; + const shadow = await build(); + return { off, shadow }; + } + const shape = (r: any) => ({ anchored: r.anchored, delta: r.row.delta, cls: r.row.decision_outcome }); + + it('a refused anchor (wrong recipient) earns exactly what it earned before', async () => { + installChain('real'); + const { off, shadow } = await both(() => + scoreSettledInteraction(interaction(), { ...CALLER_OPTS, anchorDeps: anchorDeps({ [CONTRACT_A]: { payeeAddress: STRANGER } }) } as any), + ); + expect(shape(shadow)).toEqual(shape(off)); + }); + + it('a replayed anchor earns exactly what it earned before', async () => { + installChain('real'); + const deps = anchorDeps({ [CONTRACT_A]: {}, [CONTRACT_B]: {} }); + await scoreSettledInteraction(interaction(), { ...CALLER_OPTS, anchorDeps: deps } as any); + const { off, shadow } = await both(() => + scoreSettledInteraction( + interaction({ interactionId: 'fabricated-anchor-2', contractId: CONTRACT_B }), + { ...CALLER_OPTS, anchorDeps: deps } as any, + ), + ); + expect(shape(shadow)).toEqual(shape(off)); + expect(off.anchored).toBe(true); // today the replay still anchors: shadow records, does not enforce + }); + + it('off writes no anchor_check at all', async () => { + installChain('real'); + process.env.PAYMENT_ANCHOR_VERIFY_MODE = 'off'; + const r = await scoreSettledInteraction(interaction(), { ...CALLER_OPTS, anchorDeps: anchorDeps({ [CONTRACT_A]: {} }) } as any); + expect(anchorCheck(r)).toBeUndefined(); + }); + + it('enforce is refused: it records exactly what shadow records and changes nothing', async () => { + installChain('real'); + const deps = () => anchorDeps({ [CONTRACT_A]: { payeeAddress: STRANGER } }); + process.env.PAYMENT_ANCHOR_VERIFY_MODE = 'off'; + const off = await scoreSettledInteraction(interaction(), { ...CALLER_OPTS, anchorDeps: deps() } as any); + process.env.PAYMENT_ANCHOR_VERIFY_MODE = 'enforce'; + const enf = await scoreSettledInteraction(interaction(), { ...CALLER_OPTS, anchorDeps: deps() } as any); + expect(shape(enf)).toEqual(shape(off)); + expect(anchorCheck(enf)).toMatchObject({ mode: 'shadow', requested_mode: 'enforce', verdict: 'REFUSED' }); + }); +}); diff --git a/tests/payment-anchor-verify.test.ts b/tests/payment-anchor-verify.test.ts new file mode 100644 index 000000000..d472b4e01 --- /dev/null +++ b/tests/payment-anchor-verify.test.ts @@ -0,0 +1,388 @@ +/** + * payment-anchor-verify.test.ts — E2E eval 2026-11-16, gap 4: a payment anchor was accepted on + * shape alone, so reputation could be farmed by typing a hash. + * + * The positive control is a REAL Base Sepolia x402 settlement, recorded once with read-only RPC + * (tests/fixtures/payment-anchor/) and replayed offline. Every other case changes one thing about + * it, so each refusal is attributable to that one thing. Contract ids are fabricated (NIL-variant + * UUIDs); the chain data is public. + * + * Required by the brief: a real transfer, the wrong recipient, too little, a replay, RPC down. + */ +import http from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { ethers } from 'ethers'; +import { + ANCHOR_USDC, + paymentAnchorVerifyMode, + shadowCheckPaymentAnchor, + verifyPaymentAnchor, + type AnchorBindingRow, + type AnchorDeps, + type AnchorReplayStore, + type AnchorTerms, +} from '../src/services/payment-anchor-verify'; +import { __setSettlementProviderFactory, verifySettlement } from '../src/services/x402-settlement-verifier'; +import type { EthProviderLike } from '../src/services/deposit-verifier'; + +// ── the real settlement ────────────────────────────────────────────────────── +const fixture = JSON.parse( + readFileSync(join(__dirname, 'fixtures', 'payment-anchor', 'base-sepolia-x402-settlement.json'), 'utf8'), +); +const REAL_TX = fixture._source.tx_hash; +const REAL_PAYER = '0xdf6b8215d193b11b4903d223729c3cf7a6de271d'; +const REAL_PAYEE = '0xced17f65e03e7b3a77d5321a2d3715840317199c'; +const REAL_UNITS = 1_000_000n; // 1.000000 USDC +const HEAD = fixture.receipt.blockNumber + 10; + +const CONTRACT_A = '00000000-0000-0000-0000-00000000c0a1'; +const CONTRACT_B = '00000000-0000-0000-0000-00000000c0b2'; +const STRANGER = '0x4444444444444444444444444444444444444444'; +const EVAL_FAKE_TX = '0x' + 'ab'.repeat(32); // the eval's DEMO_X402_TX + +const TRANSFER_TOPIC = ethers.id('Transfer(address,address,uint256)'); +const coder = ethers.AbiCoder.defaultAbiCoder(); +const pad = (a: string) => ethers.zeroPadValue(ethers.getAddress(a), 32); + +function realReceipt(): any { + return JSON.parse(JSON.stringify(fixture.receipt)); +} + +function transferLog(token: string, from: string, to: string, value: bigint) { + return { address: token, topics: [TRANSFER_TOPIC, pad(from), pad(to)], data: coder.encode(['uint256'], [value]) }; +} + +interface ChainOpts { + receipts?: Record; + throwWith?: Error; + hang?: boolean; +} +let calls = 0; +function installChain(opts: ChainOpts) { + calls = 0; + const p: EthProviderLike = { + async getTransactionReceipt(hash: string) { + calls++; + if (opts.hang) return new Promise(() => {}) as never; + if (opts.throwWith) throw opts.throwWith; + return ((opts.receipts ?? {})[hash.toLowerCase()] ?? null) as never; + }, + async getBlockNumber() { + if (opts.throwWith) throw opts.throwWith; + return HEAD; + }, + async call() { + throw new Error('not used'); + }, + }; + __setSettlementProviderFactory(() => p); +} + +/** In-memory replay table with the production semantics: unique on (chain_id, tx_hash). */ +function memoryReplay(): AnchorReplayStore & { rows: AnchorBindingRow[] } { + const rows: AnchorBindingRow[] = []; + return { + rows, + async find(chainId, txHash) { + const r = rows.find((x) => x.chain_id === chainId && x.tx_hash === txHash.toLowerCase()); + return r ? { contract_id: r.contract_id } : null; + }, + async bind(row) { + if (rows.some((x) => x.chain_id === row.chain_id && x.tx_hash === row.tx_hash)) return 'duplicate'; + rows.push(row); + return 'ok'; + }, + }; +} + +function terms(over: Partial = {}): AnchorTerms { + return { + contractId: CONTRACT_A, + payeeAddress: REAL_PAYEE, + claimedUnits: REAL_UNITS, + payerAddress: REAL_PAYER, + recordedTxHash: REAL_TX, + ...over, + }; +} + +function deps(t: Record, replay = memoryReplay(), extra: Partial = {}): AnchorDeps { + return { loadTerms: async (id) => (id in t ? t[id]! : null), replay, timeoutMs: 2_000, ...extra }; +} + +const claimA = { txHash: REAL_TX, chainId: 84532, contractId: CONTRACT_A }; + +afterEach(() => __setSettlementProviderFactory(undefined)); + +describe('1. a real transfer verifies', () => { + it('the recorded x402 settlement verifies against its contract, as an EIP-3009 settlement', async () => { + installChain({ receipts: { [REAL_TX]: realReceipt() } }); + const replay = memoryReplay(); + const r = await verifyPaymentAnchor(claimA, deps({ [CONTRACT_A]: terms() }, replay)); + expect(r).toMatchObject({ verdict: 'VERIFIED', reason: 'verified', settlement_kind: 'eip3009', net_units: '1000000' }); + expect(replay.rows).toHaveLength(1); + expect(replay.rows[0]).toMatchObject({ tx_hash: REAL_TX, contract_id: CONTRACT_A, payer_address: REAL_PAYER }); + }); + + it('a plain USDC transfer (no AuthorizationUsed) still verifies, labelled as a transfer', async () => { + const rc = realReceipt(); + rc.logs = rc.logs.filter((l: any) => l.topics[0] === TRANSFER_TOPIC); + installChain({ receipts: { [REAL_TX]: rc } }); + const r = await verifyPaymentAnchor(claimA, deps({ [CONTRACT_A]: terms() })); + expect(r).toMatchObject({ verdict: 'VERIFIED', settlement_kind: 'transfer' }); + }); +}); + +describe('2. the wrong recipient is refused', () => { + it('a real payment to someone else does not anchor this contract', async () => { + installChain({ receipts: { [REAL_TX]: realReceipt() } }); + const r = await verifyPaymentAnchor(claimA, deps({ [CONTRACT_A]: terms({ payeeAddress: STRANGER }) })); + expect(r).toMatchObject({ verdict: 'REFUSED', reason: 'transfer_elsewhere' }); + }); + + it('a Transfer log from a token that is not canonical USDC does not count', async () => { + const rc = realReceipt(); + rc.logs = [transferLog('0x2222222222222222222222222222222222222222', REAL_PAYER, REAL_PAYEE, REAL_UNITS)]; + installChain({ receipts: { [REAL_TX]: rc } }); + const r = await verifyPaymentAnchor(claimA, deps({ [CONTRACT_A]: terms() })); + expect(r).toMatchObject({ verdict: 'REFUSED', reason: 'wrong_token' }); + }); + + it('the payment must come from the payer the contract recorded', async () => { + installChain({ receipts: { [REAL_TX]: realReceipt() } }); + const r = await verifyPaymentAnchor(claimA, deps({ [CONTRACT_A]: terms({ payerAddress: STRANGER }) })); + expect(r).toMatchObject({ verdict: 'REFUSED', reason: 'payer_mismatch' }); + }); + + it('paying yourself is not a payment', async () => { + const rc = realReceipt(); + rc.logs = [transferLog(ANCHOR_USDC, REAL_PAYEE, REAL_PAYEE, REAL_UNITS)]; + installChain({ receipts: { [REAL_TX]: rc } }); + const r = await verifyPaymentAnchor(claimA, deps({ [CONTRACT_A]: terms({ payerAddress: null, recordedTxHash: null }) })); + expect(r).toMatchObject({ verdict: 'REFUSED', reason: 'self_payment' }); + }); +}); + +describe('3. too little is refused', () => { + it('a contract priced one unit above what moved is refused', async () => { + installChain({ receipts: { [REAL_TX]: realReceipt() } }); + const r = await verifyPaymentAnchor(claimA, deps({ [CONTRACT_A]: terms({ claimedUnits: REAL_UNITS + 1n }) })); + expect(r).toMatchObject({ verdict: 'REFUSED', reason: 'below_claimed_value' }); + }); + + it('exactly the price passes: the bound is inclusive and in integer units, not a float', async () => { + installChain({ receipts: { [REAL_TX]: realReceipt() } }); + const r = await verifyPaymentAnchor(claimA, deps({ [CONTRACT_A]: terms({ claimedUnits: REAL_UNITS }) })); + expect(r.verdict).toBe('VERIFIED'); + }); + + it('pay-and-refund in the same tx nets to nothing and is refused', async () => { + const rc = realReceipt(); + rc.logs.push(transferLog(ANCHOR_USDC, REAL_PAYEE, REAL_PAYER, REAL_UNITS)); + installChain({ receipts: { [REAL_TX]: rc } }); + const r = await verifyPaymentAnchor(claimA, deps({ [CONTRACT_A]: terms() })); + expect(r).toMatchObject({ verdict: 'REFUSED', reason: 'refunded_in_tx', net_units: '0' }); + }); + + it('a contract with no price cannot be anchored', async () => { + installChain({ receipts: { [REAL_TX]: realReceipt() } }); + const r = await verifyPaymentAnchor(claimA, deps({ [CONTRACT_A]: terms({ claimedUnits: 0n }) })); + expect(r).toMatchObject({ verdict: 'REFUSED', reason: 'no_claimed_value' }); + }); +}); + +describe('4. a replay is refused', () => { + it('the same real tx cannot anchor the same contract twice', async () => { + installChain({ receipts: { [REAL_TX]: realReceipt() } }); + const d = deps({ [CONTRACT_A]: terms() }); + expect((await verifyPaymentAnchor(claimA, d)).verdict).toBe('VERIFIED'); + const again = await verifyPaymentAnchor(claimA, d); + expect(again).toMatchObject({ verdict: 'REFUSED', reason: 'replay_same_contract', bound_contract_id: CONTRACT_A }); + }); + + it('nor a different contract', async () => { + installChain({ receipts: { [REAL_TX]: realReceipt() } }); + const d = deps({ [CONTRACT_A]: terms(), [CONTRACT_B]: terms({ contractId: CONTRACT_B, recordedTxHash: null, payerAddress: null }) }); + expect((await verifyPaymentAnchor(claimA, d)).verdict).toBe('VERIFIED'); + const other = await verifyPaymentAnchor({ ...claimA, contractId: CONTRACT_B }, d); + expect(other).toMatchObject({ verdict: 'REFUSED', reason: 'replay_other_contract', bound_contract_id: CONTRACT_A }); + }); + + it('a known replay is refused even while the RPC is down', async () => { + installChain({ receipts: { [REAL_TX]: realReceipt() } }); + const d = deps({ [CONTRACT_A]: terms() }); + await verifyPaymentAnchor(claimA, d); + installChain({ throwWith: new Error('connect ECONNREFUSED') }); + expect(await verifyPaymentAnchor(claimA, d)).toMatchObject({ verdict: 'REFUSED', reason: 'replay_same_contract' }); + expect(calls).toBe(0); // refused from our own table, no chain call + }); + + it('two concurrent presentations: exactly one verifies (the unique key decides, not the pre-check)', async () => { + installChain({ receipts: { [REAL_TX]: realReceipt() } }); + const d = deps({ [CONTRACT_A]: terms(), [CONTRACT_B]: terms({ contractId: CONTRACT_B, recordedTxHash: null, payerAddress: null }) }); + const [x, y] = await Promise.all([ + verifyPaymentAnchor(claimA, d), + verifyPaymentAnchor({ ...claimA, contractId: CONTRACT_B }, d), + ]); + const verdicts = [x.verdict, y.verdict].sort(); + expect(verdicts).toEqual(['REFUSED', 'VERIFIED']); + expect([x.reason, y.reason]).toContain('replay_other_contract'); + }); + + it('a contract with a recorded settlement is bound to THAT tx; another real tx does not anchor it', async () => { + const otherTx = '0x' + '12'.repeat(32); + installChain({ receipts: { [otherTx]: realReceipt() } }); + const r = await verifyPaymentAnchor({ ...claimA, txHash: otherTx }, deps({ [CONTRACT_A]: terms() })); + expect(r).toMatchObject({ verdict: 'REFUSED', reason: 'contract_tx_mismatch' }); + expect(calls).toBe(0); + }); +}); + +describe('5. RPC down is NOT_CHECKED: never a pass, never a refusal, and no RPC text in the answer', () => { + const KEYED_URL = 'https://base-sepolia.example-rpc.invalid/v2/FAKE-RPC-KEY-7f3a'; + + it('a throwing provider whose message carries the RPC URL and key', async () => { + installChain({ throwWith: new Error(`server response 401 (info={ "requestUrl": "${KEYED_URL}" })`) }); + const r = await verifyPaymentAnchor(claimA, deps({ [CONTRACT_A]: terms() })); + expect(r).toMatchObject({ verdict: 'NOT_CHECKED', reason: 'rpc_unreachable' }); + expect(JSON.stringify(r)).not.toMatch(/FAKE-RPC-KEY|example-rpc|requestUrl/); + }); + + it('a REAL ethers provider against an RPC answering 401 (ethers puts the URL in its message)', async () => { + const server = http.createServer((_q, res) => { + res.writeHead(401, { 'content-type': 'application/json' }); + res.end('{"error":"invalid api key"}'); + }); + await new Promise((ok) => server.listen(0, '127.0.0.1', () => ok())); + const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/v2/FAKE-RPC-KEY-7f3a`; + const net = ethers.Network.from(84532); + const provider = new ethers.JsonRpcProvider(url, net, { staticNetwork: net }); + __setSettlementProviderFactory(() => provider as unknown as EthProviderLike); + try { + const r = await verifyPaymentAnchor(claimA, deps({ [CONTRACT_A]: terms() })); + expect(r).toMatchObject({ verdict: 'NOT_CHECKED', reason: 'rpc_unreachable' }); + expect(JSON.stringify(r)).not.toContain('FAKE-RPC-KEY'); + // The settlement verifier underneath must not echo it either: its reason lands in metadata. + const s = await verifySettlement({ txHash: REAL_TX, payeeAddress: REAL_PAYEE, claimedValueUsdc: 1 }); + expect(s).toMatchObject({ verified: false, evidence: 'NOT_CHECKED', code: 'rpc_unreachable' }); + expect(s.reason).not.toContain('FAKE-RPC-KEY'); + expect(s.reason).not.toContain('127.0.0.1'); + } finally { + provider.destroy(); + await new Promise((ok) => server.close(() => ok())); + } + }); + + it('a provider that never answers times out as NOT_CHECKED', async () => { + installChain({ hang: true }); + const r = await verifyPaymentAnchor(claimA, deps({ [CONTRACT_A]: terms() }, memoryReplay(), { timeoutMs: 50 })); + expect(r).toMatchObject({ verdict: 'NOT_CHECKED', reason: 'rpc_timeout' }); + }); + + it('a replay table that cannot be read: the chain still answers, the anchor is still not VERIFIED', async () => { + installChain({ receipts: { [REAL_TX]: realReceipt() } }); + const broken: AnchorReplayStore = { + async find() { + throw new Error('relation "payment_anchor_claims" does not exist'); + }, + async bind() { + throw new Error('relation "payment_anchor_claims" does not exist'); + }, + }; + const ok = await verifyPaymentAnchor(claimA, deps({ [CONTRACT_A]: terms() }, broken as any)); + expect(ok).toMatchObject({ verdict: 'NOT_CHECKED', reason: 'replay_store_unreachable', chain_verified: true }); + // ...and a chain refusal still refuses: an unreadable table never upgrades a bad anchor. + const bad = await verifyPaymentAnchor(claimA, deps({ [CONTRACT_A]: terms({ payeeAddress: STRANGER }) }, broken as any)); + expect(bad).toMatchObject({ verdict: 'REFUSED', reason: 'transfer_elsewhere' }); + }); + + it('a contract table that cannot be read is NOT_CHECKED, with no DB error text', async () => { + installChain({ receipts: { [REAL_TX]: realReceipt() } }); + const r = await verifyPaymentAnchor(claimA, { + loadTerms: async () => { + throw new Error('db host secret-db.internal refused'); + }, + replay: memoryReplay(), + }); + expect(r).toMatchObject({ verdict: 'NOT_CHECKED', reason: 'terms_unreadable' }); + expect(JSON.stringify(r)).not.toContain('secret-db'); + }); +}); + +describe("the eval's own reproduction", () => { + it('the made-up hash 0xabab…ab with no contract is refused before any RPC call', async () => { + installChain({ receipts: {} }); + const r = await verifyPaymentAnchor({ txHash: EVAL_FAKE_TX, chainId: 84532, contractId: null }, deps({})); + expect(r).toMatchObject({ verdict: 'REFUSED', reason: 'contract_unbound' }); + expect(calls).toBe(0); + }); + + it('the made-up hash bound to a real-looking contract: the chain has no such tx', async () => { + installChain({ receipts: {} }); + const r = await verifyPaymentAnchor( + { txHash: EVAL_FAKE_TX, chainId: 84532, contractId: CONTRACT_A }, + deps({ [CONTRACT_A]: terms({ recordedTxHash: null, payerAddress: null }) }), + ); + expect(r).toMatchObject({ verdict: 'REFUSED', reason: 'tx_not_found' }); + }); + + it('shape and chain still refuse first', async () => { + installChain({ receipts: {} }); + expect((await verifyPaymentAnchor({ txHash: 'pending', chainId: 84532, contractId: CONTRACT_A }, deps({}))).reason).toBe('malformed_tx_hash'); + expect((await verifyPaymentAnchor({ ...claimA, chainId: 8453 }, deps({}))).reason).toBe('wrong_chain'); + expect((await verifyPaymentAnchor(claimA, deps({}))).reason).toBe('contract_unknown'); + }); +}); + +describe('PAYMENT_ANCHOR_VERIFY_MODE', () => { + let errSpy: jest.SpyInstance; + let warnSpy: jest.SpyInstance; + beforeEach(() => { + errSpy = jest.spyOn(console, 'error').mockImplementation(() => {}); + warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {}); + }); + afterEach(() => { + errSpy.mockRestore(); + warnSpy.mockRestore(); + }); + + it('defaults to off', () => { + expect(paymentAnchorVerifyMode(undefined)).toEqual({ requested: 'off', effective: 'off' }); + expect(paymentAnchorVerifyMode('')).toEqual({ requested: 'off', effective: 'off' }); + expect(paymentAnchorVerifyMode(' OFF ')).toEqual({ requested: 'off', effective: 'off' }); + }); + + it('enforce is refused in this build: it runs as shadow and says so', () => { + const m = paymentAnchorVerifyMode('enforce'); + expect(m.requested).toBe('enforce'); + expect(m.effective).toBe('shadow'); + expect(m.note).toMatch(/refused/); + }); + + it('a typo runs as shadow (records, moves nothing), loudly', () => { + const m = paymentAnchorVerifyMode('enforec'); + expect(m).toMatchObject({ requested: 'invalid', effective: 'shadow' }); + }); + + it('off reads nothing at all', async () => { + installChain({ receipts: { [REAL_TX]: realReceipt() } }); + let loaded = 0; + const r = await shadowCheckPaymentAnchor(claimA, { loadTerms: async () => (loaded++, terms()), replay: memoryReplay() }, paymentAnchorVerifyMode('off')); + expect(r).toBeNull(); + expect(loaded).toBe(0); + expect(calls).toBe(0); + }); + + it('shadow checks, logs the would-refuse, and reports would_refuse', async () => { + installChain({ receipts: {} }); + const r = await shadowCheckPaymentAnchor( + { txHash: EVAL_FAKE_TX, chainId: 84532, contractId: null }, + deps({}), + paymentAnchorVerifyMode('shadow'), + ); + expect(r).toMatchObject({ verdict: 'REFUSED', would_refuse: true }); + expect(warnSpy.mock.calls.join(' ')).toMatch(/would REFUSE anchor reason=contract_unbound/); + }); +}); From 27d684d786492e16bf7ed2f382668b5f5996a7cc Mon Sep 17 00:00:00 2001 From: "CC (Claude Code)" Date: Mon, 16 Nov 2026 13:39:11 -0800 Subject: [PATCH 2/3] wip(payment-anchor): register flag, harness shadow line, docs Co-Authored-By: Claude Opus 5.5 --- CLAIM_LEDGER.md | 4 +-- scripts/demo/trust-harness-e2e.mjs | 38 ++++++++++++++++++++++++++ src/config/known-env-vars.generated.ts | 1 + src/ops/flag-registry.ts | 1 + src/services/x402-outcome-link.ts | 9 ++++++ 5 files changed, 51 insertions(+), 2 deletions(-) diff --git a/CLAIM_LEDGER.md b/CLAIM_LEDGER.md index afdeffe9a..6764b1051 100644 --- a/CLAIM_LEDGER.md +++ b/CLAIM_LEDGER.md @@ -59,13 +59,13 @@ failure. | Claim | What exists | Missing to reach VERIFIED | Owner | |-------|-------------|---------------------------|-------| -| x402 payment-proof linking gates positive deltas | `src/services/x402-outcome-link.ts` (+tests); STEP 2 `627e571` caught a real FAIL-OPEN | A live positive-reward run where the anchor is required and present | CC | +| x402 payment-proof linking gates positive deltas | `src/services/x402-outcome-link.ts` (+tests); STEP 2 `627e571` caught a real FAIL-OPEN. **The link checks SHAPE only unless a caller passes `requireVerified`** [E2E eval 2026-11-16 §3a: a made-up hash turned an UNCERTAIN outcome into +25 through `scripts/demo/trust-harness-e2e.mjs`]. On-chain checks: `x402-settlement-verifier.ts` (receipt, canonical-USDC `Transfer` to the payee ≥ value) and `payment-anchor-verify.ts` (payee, payer and price from the contract's own record, tx bound to that contract, replay refused), the second in SHADOW behind `PAYMENT_ANCHOR_VERIFY_MODE` (default off; enforce refused in code) | (1) the `payment_anchor_claims` replay table applied (draft migration `20261116130000`, Sean); (2) enforce, Sean's call; (3) a production caller: `scoreSettledInteraction` has none today [MEASURED 2026-11-16], so no live score consumes a caller-supplied anchor yet; (4) then a live positive-reward run where the anchor is required, present and verified | CC | | HAL confidence calibration fit on a frozen holdout | `src/services/hal-calibration.ts` + `scripts/hal-eval/fit-calibration.ts` (ECE) | A published ECE number on the current frozen corpus with its ruler | CC | | Outcome classification schema with enforced asymmetric deltas | `src/services/outcome-classification.ts` (+158-line test) | (folded into VERIFIED harness run above; keep here until independent test-count asserted) | CC | | TrustShell `presentProof` / badge path | `presentProof` + `verifyProofLocally` on the SDK client, `src/lib/badge.ts` (`renderProofBadge` / `renderProofBadgeMarkdown` / `proofBadgeStatus`), a `badge` CLI command, all exported from `src/lib/index.ts`. **14/14 `tests/badge.test.ts` pass [RUN 2026-09-04]**, and they pin the honest states, not just the happy one: verifier UNAVAILABLE → red and explicitly NOT a pass (fail-closed); no verification run → grey, "we refuse to imply unchecked trust"; the badge NEVER reveals the score in any state; the SVG is self-contained with no external references | A live run against the backend producing a real proof, verified client-side, with the badge rendered from it | CC | | TrustMarket rating ingestion consuming fold root + dual-auth decision | `src/services/rating-ingestion.ts` consumes BOTH halves — it imports `Decision` from `./dual-auth-gate` and rejects `outcome_not_authorized` unless the gate said ALLOW, and rejects `fold_root_mismatch` when the claimed root disagrees with the server's. Fails closed by design: "an unrecorded ALLOW is not an ALLOW" (`:151`). **39/39 pass across `tests/rating-ingestion.test.ts` + `tests/participant-rating.test.ts` [RUN 2026-09-04]** | A live rating ingested end-to-end against a real settled interaction; both tables held 0 rows at last check, so the path is tested but unexercised | CC | | X8 local adversarial harness (anvil fork pin + LOCAL_MODE scratch + 7 probes as code) | `scripts/adversarial-harness/` + `tests/adversarial-harness.test.ts`. One command `npm run harness`. Synthetic ids only. | Anvil binary on the operator box (optional; A1–A6 run without it). No prod writes. | XC | -| C8 grounding multiplier in shadow | `src/scoring/grounding.ts` is the single `resolveGrounding`. Floor $0.10, parties join, idempotent on (evidence, agent, event_type). | Prod unique index + RPC (Sean DDL / GROUNDING_RPC_URL). Enforce is a later ticket. | XC | +| C8 grounding multiplier in shadow | `src/scoring/grounding.ts` is the single `resolveGrounding`. Floor $0.10, parties join, idempotent on (evidence, agent, event_type). | Prod unique index + RPC (Sean DDL / GROUNDING_RPC_URL). **The table `repid_grounding_claims` itself does not exist in prod** [MEASURED 2026-11-16, `to_regclass` = null], and no production caller passes a chain reader, so a payment grounds `chain_not_checked`. Enforce is a later ticket. | XC | | C9 L5 bound-entity decay | `src/identity/decay-bound.ts` — bound kinds hold score, `last_verified_action` is the public gap, unclaimed DBT still decays with a typed event. | Kind column on prod `repid_agents` (C7 DDL, Sean). | XC | | C10 caps as config | `src/config/entity-caps.json` ladder 3→7→12→21, Bronze ceiling, claim 100%, slash drops a rung. | Custodian rows in prod (C7). | XC | diff --git a/scripts/demo/trust-harness-e2e.mjs b/scripts/demo/trust-harness-e2e.mjs index eb91c9d82..b54080169 100644 --- a/scripts/demo/trust-harness-e2e.mjs +++ b/scripts/demo/trust-harness-e2e.mjs @@ -71,6 +71,32 @@ try { // Left null → verifyProofLocally fails closed on step 3. } +/** + * The shipped payment-anchor check (src/services/payment-anchor-verify.ts), when + * PAYMENT_ANCHOR_VERIFY_MODE is set. DEMO_CONTRACT_ID names the contract the payment settles; its + * terms and the replay table are then read from Supabase (needs real credentials). Without it the + * verifier refuses the anchor as unbound, before any read. Never throws: a verifier that cannot load + * is NOT_CHECKED, never a pass. + */ +async function shadowAnchorCheck(txHash) { + const raw = (process.env.PAYMENT_ANCHOR_VERIFY_MODE ?? '').trim().toLowerCase(); + if (raw === '' || raw === 'off') return null; + try { + const { shadowCheckPaymentAnchor, paymentAnchorVerifyMode } = await import('../../dist/services/payment-anchor-verify.js'); + const contractId = process.env.DEMO_CONTRACT_ID || null; + const deps = contractId + ? await import('../../dist/services/payment-anchor-db.js').then((m) => ({ loadTerms: m.dbAnchorTerms, replay: m.dbAnchorReplayStore() })) + : { + loadTerms: async () => null, + replay: { find: async () => null, bind: async () => { throw new Error('no replay store'); } }, + }; + return await shadowCheckPaymentAnchor({ txHash, chainId: 84532, contractId }, deps, paymentAnchorVerifyMode()); + } catch { + // dist not built, or config refused to load (it needs SUPABASE_URL set, even to a dummy). + return { verdict: 'NOT_CHECKED', reason: 'verifier_unavailable (run npm run build; set SUPABASE_URL)' }; + } +} + const ENGINE = process.env.TRUSTSHELL_API_URL || 'https://repid-engine-production.up.railway.app'; // The leaf binary is RESOLVED, not assumed. This used to default to an absolute path under @@ -375,6 +401,18 @@ if (!deltaFor || !linkPaymentProof) { (linked.anchored ? ok : unk)( linked.anchored ? `payment anchor attached: ${linked.record.x402PaymentProof}` : 'no payment anchor', ); + // GAP 4 (E2E eval 2026-11-16): the attach above checks the anchor's SHAPE only, so a made-up hash + // earned +25 here. With PAYMENT_ANCHOR_VERIFY_MODE=shadow, ask the shipped verifier what it would + // do with this anchor. Shadow: it reports, and the delta below is unchanged. + if (linked.anchored) { + const a = await shadowAnchorCheck(linked.record.x402PaymentProof); + if (a) { + const tail = 'shadow only: the delta below is unchanged'; + if (a.verdict === 'VERIFIED') ok(`payment anchor VERIFIED on chain (${a.settlement_kind}), bound to its contract (${tail})`); + else if (a.verdict === 'REFUSED') bad(`payment anchor would be REFUSED: ${a.reason}. Under enforce it is stripped and the success demoted (${tail})`); + else unk(`payment anchor NOT_CHECKED: ${a.reason}. Under enforce it would not earn (${tail})`); + } + } const d = deltaFor(linked.record); const newScore = applyDelta(prevScore, d.delta); diff --git a/src/config/known-env-vars.generated.ts b/src/config/known-env-vars.generated.ts index 82d63263e..cbc90b3bf 100644 --- a/src/config/known-env-vars.generated.ts +++ b/src/config/known-env-vars.generated.ts @@ -363,6 +363,7 @@ OWNER_CEILING_SHADOW_ENABLED OWNER_DISTINCT_SHADOW PANEL_CLOSE_NO_MAJORITY PARTICIPANT_RATING_MODE +PAYMENT_ANCHOR_VERIFY_MODE PCP_THRESHOLD_FAIL PCP_THRESHOLD_PASS PCP_VALIDATOR_MODEL diff --git a/src/ops/flag-registry.ts b/src/ops/flag-registry.ts index cba89d7ce..b8b16577f 100644 --- a/src/ops/flag-registry.ts +++ b/src/ops/flag-registry.ts @@ -116,6 +116,7 @@ OWNER_BUDGET_MODE OWNER_CEILING_SHADOW_ENABLED OWNER_DISTINCT_SHADOW PARTICIPANT_RATING_MODE +PAYMENT_ANCHOR_VERIFY_MODE PEER_VERIFY_PANEL_ENABLED PEER_VERIFY_PREFILTER_MODE PEER_VERIFY_REPID_ENABLED diff --git a/src/services/x402-outcome-link.ts b/src/services/x402-outcome-link.ts index 38947aade..cad231289 100644 --- a/src/services/x402-outcome-link.ts +++ b/src/services/x402-outcome-link.ts @@ -20,6 +20,15 @@ * untestable offline. It validates SHAPE and enforces POLICY, and says so — * `verified` is only ever true when a caller supplies an actual chain * observation. + * + * SO A CALLER THAT ONLY CALLS THIS HAS CHECKED NOTHING ON CHAIN. Without + * `requireVerified`, any 64 hex characters anchor an outcome: the E2E eval of + * 2026-11-16 (§3a) passed a made-up hash through the trust harness and earned + * +25. The chain checks live elsewhere: `x402-settlement-verifier.ts` (the + * receipt holds a canonical-USDC Transfer of at least the value to the payee) + * and `payment-anchor-verify.ts` (payee, payer and price from the contract's own + * record, the tx bound to that contract, a replay refused; shadow-only behind + * PAYMENT_ANCHOR_VERIFY_MODE until Sean enables enforce). */ import { OutcomeClass, type OutcomeRecord } from './outcome-classification'; From 7f8a75c2a61ffe7267c3b46cf5d4e174bfab9aa0 Mon Sep 17 00:00:00 2001 From: "CC (Claude Code)" Date: Mon, 16 Nov 2026 13:58:36 -0800 Subject: [PATCH 3/3] test(payment-anchor): leak-only case with the anchor check off Co-Authored-By: Claude Opus 5.5 --- tests/payment-anchor-through-scorer.test.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/tests/payment-anchor-through-scorer.test.ts b/tests/payment-anchor-through-scorer.test.ts index 4f264be90..cd69da6a5 100644 --- a/tests/payment-anchor-through-scorer.test.ts +++ b/tests/payment-anchor-through-scorer.test.ts @@ -178,6 +178,17 @@ describe('shadow anchor check, through the scorer', () => { expect(r.settlement?.reason ?? '').not.toContain('rpc.example.invalid'); }); + it('5b. RPC down, with the anchor check OFF: the RPC error text still never reaches the row', async () => { + // Independent of the new check: the existing settlement verifier copied the RPC error message + // into `metadata.payment.settlement_reason`, and ethers puts the RPC URL (key included) there. + process.env.PAYMENT_ANCHOR_VERIFY_MODE = 'off'; + installChain('down'); + const r = await scoreSettledInteraction(interaction(), CALLER_OPTS); + expect(r.settlement?.evidence).toBe('NOT_CHECKED'); + expect(JSON.stringify(r.row.metadata)).not.toContain('FAKE-RPC-KEY'); + expect(JSON.stringify(r.row.metadata)).not.toContain('rpc.example.invalid'); + }); + it('an anchor that names no contract is refused, and the check reads no contract table', async () => { installChain('real'); let loaded = 0;