Repository navigation
feat(payment-anchor): verify an x402 anchor on chain, bound to its contract, once (shadow, default off) - #1572
DealAppSeo wants to merge 3 commits into
Conversation
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Strix Security ReviewTo fix before merging (2)
PR summary: Adds a shadow-only, default-off payment-anchor verifier that re-reads an x402 settlement receipt and binds it to a contract's own recorded payee, payer and price, plus a draft replay table and a fixed-code rewrite of the settlement verifier's error handling. Review summaryThe new verifier is carefully built — payee, payer and price come from our own records, the RPC error text is now replaced with fixed codes on every path, the replay table's unique key is treated as the authority, and the mode stays inert by default. Two problems remain in how the anchor's evidence is actually accounted for.
Both are capped by the fact that the scorer still has no production caller and the replay table is a draft, which is why the first is rated medium rather than high; neither is fixed by the flag being off. Ruled out (2)
Fixed the findings? re-run the review, or tag Review 1 on this PR · Reviewed by Strix |
| return { | ||
| contractId, | ||
| payeeAddress: (p as any)?.wallet_address ?? null, | ||
| claimedUnits: units, | ||
| payerAddress: recordedTx ? ((s as any).payer_address ?? null) : null, | ||
| recordedTxHash: recordedTx, | ||
| }; |
There was a problem hiding this comment.
🔵 Payment-anchor verification drops the payer and contract-tx binding for a contract whose recorded settlement is simulated
Severity: LOW
TL;DR: For a contract whose settlement row is is_simulated, dbAnchorTerms returns no recorded tx and no payer, so verifyPaymentAnchor skips the tx binding and credits any sender, answering VERIFIED for a transfer that never paid for this contract.
Impact: Once the draft replay table is applied and enforce ships, an agent can anchor a contract it never paid for using another buyer's real transfer to the same provider, consuming that tx so its rightful contract can no longer verify. In shadow mode no score moves.
Root cause:
- The binding strength is derived from the settlement row's
is_simulatedflag rather than from whether the contract has a real payment, so the one row that records "no money moved" is treated as carrying no binding information instead of as a reason to refuse. payment-anchor-db.ts:59-60,73nullsrecordedTxHashand gatespayerAddresson it, sopayment-anchor-verify.ts:271never compares the anchor against the contract's own tx and:315-317falls back to summing every sender's inflow in the receipt.- Nothing in the verifier treats a simulated settlement as a refusal, so our own record that this contract was never paid is outweighed by any canonical-USDC transfer to the payee and the answer is VERIFIED rather than REFUSED or NOT_CHECKED.
| return { | |
| contractId, | |
| payeeAddress: (p as any)?.wallet_address ?? null, | |
| claimedUnits: units, | |
| payerAddress: recordedTx ? ((s as any).payer_address ?? null) : null, | |
| recordedTxHash: recordedTx, | |
| }; | |
| return { | |
| contractId, | |
| payeeAddress: (p as any)?.wallet_address ?? null, | |
| claimedUnits: units, | |
| payerAddress: recordedTx ? ((s as any).payer_address ?? null) : null, | |
| recordedTxHash: recordedTx, | |
| settlementSimulated: s ? (s as any).is_simulated !== false : false, | |
| }; |
Prompt to fix with AI
This is a security vulnerability found during a code review.
Vulnerability: Payment-anchor verification drops the payer and contract-tx binding for a contract whose recorded settlement is simulated
Severity: LOW
CWE: CWE-345
**TL;DR:** For a contract whose settlement row is `is_simulated`, `dbAnchorTerms` returns no recorded tx and no payer, so `verifyPaymentAnchor` skips the tx binding and credits any sender, answering VERIFIED for a transfer that never paid for this contract.
**Impact:** Once the draft replay table is applied and `enforce` ships, an agent can anchor a contract it never paid for using another buyer's real transfer to the same provider, consuming that tx so its rightful contract can no longer verify. In shadow mode no score moves.
**Root cause:**
- The binding strength is derived from the settlement row's `is_simulated` flag rather than from whether the contract has a real payment, so the one row that records "no money moved" is treated as carrying no binding information instead of as a reason to refuse.
- `payment-anchor-db.ts:59-60,73` nulls `recordedTxHash` and gates `payerAddress` on it, so `payment-anchor-verify.ts:271` never compares the anchor against the contract's own tx and `:315-317` falls back to summing every sender's inflow in the receipt.
- Nothing in the verifier treats a simulated settlement as a refusal, so our own record that this contract was never paid is outweighed by any canonical-USDC transfer to the payee and the answer is VERIFIED rather than REFUSED or NOT_CHECKED.
Location: src/services/payment-anchor-db.ts:69-75
Context: primary: carry the simulated flag instead of silently dropping both bindings
```
// Before:
return {
contractId,
payeeAddress: (p as any)?.wallet_address ?? null,
claimedUnits: units,
payerAddress: recordedTx ? ((s as any).payer_address ?? null) : null,
recordedTxHash: recordedTx,
};
// After:
return {
contractId,
payeeAddress: (p as any)?.wallet_address ?? null,
claimedUnits: units,
payerAddress: recordedTx ? ((s as any).payer_address ?? null) : null,
recordedTxHash: recordedTx,
settlementSimulated: s ? (s as any).is_simulated !== false : false,
};
```
Location: src/services/payment-anchor-verify.ts:104-104
Context: terms type carries the simulated state
```
// Before:
recordedTxHash: string | null;
// After:
recordedTxHash: string | null;
/** True when our own record says this contract was settled in simulation: no money moved. */
settlementSimulated?: boolean;
```
Location: src/services/payment-anchor-verify.ts:163-163
Context: refusal reason
```
// Before:
| 'refunded_in_tx'
// After:
| 'refunded_in_tx'
| 'settlement_simulated'
```
Location: src/services/payment-anchor-verify.ts:263-263
Context: refuse a contract our own record says was never paid
```
// Before:
if (!terms) return refuse('contract_unknown');
// After:
if (!terms) return refuse('contract_unknown');
// Our own record says this contract was settled in simulation, so no money moved for it. An
// anchor claiming otherwise contradicts that record and is refused, not graded against the chain.
if (terms.settlementSimulated === true) return refuse('settlement_simulated');
```
How to fix:
Refuse an anchor for a contract whose own settlement record says the payment was simulated, instead of grading it against the payee's inbound transfers. Keep the payer binding independent of the tx binding so a recorded `payer_address` is still enforced when no chain tx is usable, and add a test that a simulated settlement row can never produce VERIFIED.
Please fix this vulnerability. If you propose a fix, make it concise and minimal.React 👍 / 👎 to tune Strix for this repo. A repo collaborator (or the PR author) can resolve this thread to dismiss the finding.
| /** 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; |
There was a problem hiding this comment.
terms type carries the simulated state
| recordedTxHash: string | null; | |
| recordedTxHash: string | null; | |
| /** True when our own record says this contract was settled in simulation: no money moved. */ | |
| settlementSimulated?: boolean; |
| | 'below_claimed_value' | ||
| | 'payer_mismatch' | ||
| | 'self_payment' | ||
| | 'refunded_in_tx' |
There was a problem hiding this comment.
refusal reason
| | 'refunded_in_tx' | |
| | 'refunded_in_tx' | |
| | 'settlement_simulated' |
| } catch { | ||
| return notChecked('terms_unreadable'); | ||
| } | ||
| if (!terms) return refuse('contract_unknown'); |
There was a problem hiding this comment.
refuse a contract our own record says was never paid
| if (!terms) return refuse('contract_unknown'); | |
| if (!terms) return refuse('contract_unknown'); | |
| // Our own record says this contract was settled in simulation, so no money moved for it. An | |
| // anchor claiming otherwise contradicts that record and is refused, not graded against the chain. | |
| if (terms.settlementSimulated === true) return refuse('settlement_simulated'); |
| 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; |
There was a problem hiding this comment.
🟡 verifySettlement counts a payee-to-payee USDC transfer as money received, so a gas-only self-transfer verifies a settlement and anchors a scored success
Severity: MEDIUM
TL;DR: In verifySettlement, a Transfer log where both from and to are the payee is added to observed, so a self-transfer that moves no net value returns verified: true and the scorer passes that proof on to deltaFor as an anchored outcome.
Impact: A provider agent can attach the hash of a USDC transfer it sent to itself — no money leaves its wallet, only gas — and collect the anchored success delta (up to +25 per event) that deltaFor withholds from unanchored success above $10, so reputation can be farmed without moving value.
Root cause:
- No layer of the anchor chain checks that value actually moved: the verifier sums gross inflow to the payee, and the scorer treats that boolean as sufficient evidence that a counterparty paid.
- The loop this PR edits now records who sent each transfer and what the payee sent out, but
observedstill adds a transfer the payee made to itself, soverifiedstays true for a zero-value movement. - The identical case is correctly refused in the new
payment-anchor-verify.ts(self_payment, net ofoutflowFromPayee), but that module runs only whenPAYMENT_ANCHOR_VERIFY_MODEis set and never touches the delta, so the flag that actually gates the delta is unchanged.
| 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 (eqAddr(from, input.payeeAddress)) analysis.outflowFromPayee += value; | |
| // A transfer the payee makes to itself names a transfer but moves no value: the | |
| // balance is unchanged, so it must not count toward the claimed amount. | |
| const selfTransfer = eqAddr(from, input.payeeAddress) && eqAddr(to, input.payeeAddress); | |
| if (eqAddr(to, input.payeeAddress) && !selfTransfer) { | |
| observed += value; | |
| const sender = String(from).toLowerCase(); | |
| analysis.inflowBySender[sender] = (analysis.inflowBySender[sender] ?? 0n) + value; | |
| } else if (!eqAddr(to, input.payeeAddress)) sawTransferElsewhere = true; |
Prompt to fix with AI
This is a security vulnerability found during a code review.
Vulnerability: verifySettlement counts a payee-to-payee USDC transfer as money received, so a gas-only self-transfer verifies a settlement and anchors a scored success
Severity: MEDIUM
CWE: CWE-345
**TL;DR:** In `verifySettlement`, a `Transfer` log where both `from` and `to` are the payee is added to `observed`, so a self-transfer that moves no net value returns `verified: true` and the scorer passes that proof on to `deltaFor` as an anchored outcome.
**Impact:** A provider agent can attach the hash of a USDC transfer it sent to itself — no money leaves its wallet, only gas — and collect the anchored success delta (up to +25 per event) that `deltaFor` withholds from unanchored success above $10, so reputation can be farmed without moving value.
**Root cause:**
- No layer of the anchor chain checks that value actually moved: the verifier sums gross inflow to the payee, and the scorer treats that boolean as sufficient evidence that a counterparty paid.
- The loop this PR edits now records who sent each transfer and what the payee sent out, but `observed` still adds a transfer the payee made to itself, so `verified` stays true for a zero-value movement.
- The identical case is correctly refused in the new `payment-anchor-verify.ts` (`self_payment`, net of `outflowFromPayee`), but that module runs only when `PAYMENT_ANCHOR_VERIFY_MODE` is set and never touches the delta, so the flag that actually gates the delta is unchanged.
Location: src/services/x402-settlement-verifier.ts:287-292
Context: primary fix: do not credit a transfer the payee makes to itself
```
// Before:
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;
// After:
if (eqAddr(from, input.payeeAddress)) analysis.outflowFromPayee += value;
// A transfer the payee makes to itself names a transfer but moves no value: the
// balance is unchanged, so it must not count toward the claimed amount.
const selfTransfer = eqAddr(from, input.payeeAddress) && eqAddr(to, input.payeeAddress);
if (eqAddr(to, input.payeeAddress) && !selfTransfer) {
observed += value;
const sender = String(from).toLowerCase();
analysis.inflowBySender[sender] = (analysis.inflowBySender[sender] ?? 0n) + value;
} else if (!eqAddr(to, input.payeeAddress)) sawTransferElsewhere = true;
```
Location: src/services/x402-settlement-verifier.ts:329-343
Context: second part: compare the claimed value against the net amount, not the gross inflow
```
// Before:
if (claimed > 0n && observed < claimed) {
// The claim is not merely unproven, it is CONTRADICTED. Value at risk picks
// the risk band as well as scaling the delta, so an inflated claim would buy
// both a larger movement and a self-selected level of scrutiny.
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,
};
}
// After:
const netReceived = observed - analysis.outflowFromPayee;
if (claimed > 0n && netReceived < claimed) {
// The claim is not merely unproven, it is CONTRADICTED. Value at risk picks
// the risk band as well as scaling the delta, so an inflated claim would buy
// both a larger movement and a self-selected level of scrutiny. The payee's
// own same-tx outflow is netted, so a refund or a pass-through is not a receipt.
return {
verified: false,
evidence: 'MEASURED',
code: 'below_claimed_value',
reason: `settlement moved ${netReceived} net but the claimed service value is ${claimed} (smallest unit)`,
observedAmount: netReceived,
confirmations,
blockNumber,
analysis,
};
}
```
Location: src/services/settled-interaction-scorer.ts:173-173
Context: the consumer: the verifier's boolean alone decides whether the proof is forwarded as an anchor
```
paymentProof: result.verified ? proof : null,
```
Location: src/services/payment-anchor-verify.ts:314-314
Context: the same defect correctly refused, in the module that does not affect the delta
```
if (a.inflowBySender[payee] !== undefined) return refuse('self_payment');
```
How to fix:
Make `verifySettlement`'s `verified` flag mean what it is consumed as: value received from someone other than the payee, net of anything the payee sent back in the same transaction, so a self-transfer or a round-trip refund can never satisfy the claimed amount. Keep the `analysis` fields as the richer view for callers that need per-sender detail. Add a regression case that drives a receipt containing only a payee-to-payee `Transfer` through `scoreSettledInteraction` and asserts `settlement.verified` is false and the outcome is unanchored (demoted) rather than anchored. Update the anchor module's self-payment expectation to whatever code the verifier now returns for that input, since the verifier refuses before that branch is reached.
Please fix this vulnerability. If you propose a fix, make it concise and minimal.React 👍 / 👎 to tune Strix for this repo. A repo collaborator (or the PR author) can resolve this thread to dismiss the finding.
| blockNumber, | ||
| analysis, | ||
| }; | ||
| } |
There was a problem hiding this comment.
second part: compare the claimed value against the net amount, not the gross inflow
| // 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'); |
There was a problem hiding this comment.
the same defect correctly refused, in the module that does not affect the delta
Owner action
Weight: MAJOR (money and anti-gaming, CLAUDE_RULES r31). You merge. Shipped shadow-only.
PAYMENT_ANCHOR_VERIFY_MODEis set on therepid-engineservice. Default is off: no read, no log, no write.shadowdoesenforcedoessupabase/migrations/20261116130000_payment_anchor_claims.sql(replay table). Rollback is beside it. Until it is applied, a chain-verified anchor reportsNOT_CHECKED replay_store_unreachable, never a pass.Merge alone is safe. Applying the migration and setting
shadoware separate decisions, and neither moves a score.What this closes
E2E eval 2026-11-16, gap 4: a payment anchor was accepted on shape alone.
linkPaymentProofchecks for a 0x-prefixed 32-byte hash and a chain id, and nothing else unless the caller passesrequireVerified. The eval passed a made-up hash throughscripts/demo/trust-harness-e2e.mjsand an UNCERTAIN outcome became SUCCESS_AUDITED, delta +25.What I re-verified before changing anything
x402-outcome-link.ts:88(main::79) only checksverifiedwhen asked.settled-interaction-scorer.ts:101(requireVerifiedProof: false) as "the production caller". That line runs afterresolvePaymentProofhas read the receipt, and only a resolved proof gets past it. What the scorer lacked was contract binding, replay refusal and a clean RPC error.scoreSettledInteractionhas no caller insrc/at all. So today no live score uses a caller-supplied anchor; the gap is in the shipped function and the demo, ahead of any caller.x402_settlements.tx_hashhas a plain btree index, not a unique one. The grounding resolver's claims table,repid_grounding_claims, does not exist in prod (to_regclass= null), and no production caller passes it a chain reader.verifySettlementreturnedrpc error fetching receipt: ${e.message}, and the scorer writes that reason tometadata.payment.settlement_reason. Measured with ethers 6.16.0 against an RPC that answers 401: the message carriesinfo={ "requestUrl": "<full URL, key included>" }.scripts/trust-loop/live-settlement-crosscheck.tssays it deliberately does not print the RPC URL, then printsresult.reason. Fixed here: fixed codes only.wallet_address, and the payer is not the buyer's own wallet. On the five most recent real settlements, every payee matchedwallet_address, whileerc8004_addressheld non-addresses (pending-mint:…, free text, a registry contract). Every payer was a custodian wallet, not the buyer agent'swallet_address. So the payer comes fromx402_settlements.payer_address, which the facilitator verified from the signed authorization. Binding the payer to the buyer's wallet would have refused every real payment.What the check does (
src/services/payment-anchor-verify.ts)The caller supplies only a tx hash, a chain id and a contract id. Payee, payer and price come from our own records (
service_contracts,repid_agents.wallet_address,x402_settlements).contract_unbound,contract_unknown).contract_tx_mismatch).replay_same_contract/replay_other_contract. This is checked before the chain, so a known replay is refused even while the RPC is down.Transfer(address pinned) to the payee, of at least the price, from the recorded payer, net of anything the payee sent back in the same tx (refunded_in_tx), and not a self-payment. An EIP-3009AuthorizationUsedbeside it labels it an x402 settlement (settlement_kind: eip3009). That event names no payee or amount, so it never verifies anything alone.(chain_id, tx_hash)is the authority: two concurrent presentations race on it, and the loser is refused as a replay.Three answers. VERIFIED; REFUSED (we looked, and the answer is no); or NOT_CHECKED (RPC error or timeout, contract table unreadable, replay table missing, too few confirmations). NOT_CHECKED is never a pass and never a refusal, and it would not earn under enforce.
Wired into:
scoreSettledInteraction, which recordsmetadata.payment.anchor_checkand leaves the delta alone, and the demo harness, which now prints the shadow verdict for the anchor it attaches. The harness was the eval's reproduction.x402-settlement-verifier.tsgains acodeon every result and a log analysis (inflow per sender, payee outflow, EIP-3009 authorizers). These are additive and existing callers are unchanged.Evidence (outputs under
E:\dev\reports\2026-11-16\pay-anchor\)transferWithAuthorization), recorded once with read-only RPC intotests/fixtures/payment-anchor/and replayed offline. Every other case changes one thing about it.src(af0a7461) with the branch's tests, against the branch (7f8a75c2), fromjest --json:scoreSettledInteraction)settlement_reasonpayment-anchor-verify.test.ts(28 unit tests: real fixture, recipient, payer, self-pay, wrong token, too little, refund-in-tx, replay incl. concurrent and RPC-down, contract-tx binding, 401 from a real ethers provider, timeout, unreadable tables, modes)Branch 39/39. Existing related suites on the branch:
x402-settlement-verifier,settled-interaction-scorer,x402-outcome-link,ops-flagsandprod-fixture-guardall pass. One red,env-typo-guard"finds the control…", is a 5 s timeout on a whole-tree scan, and it is identical on main'ssrcon this Windows box: ENV, not REAL.Live, read-only (the verifier against
https://sepolia.base.org, contract terms inline, replay table in memory, nothing written): the real settlement is VERIFIED (eip3009, 1000000). Replay to the same contract and to another contract: both REFUSED. Wrong recipient: REFUSEDtransfer_elsewhere. Too little: REFUSEDbelow_claimed_value. The eval's0xabab…ab: REFUSEDtx_not_foundwhen bound, andcontract_unboundwhen not.anchored, delta and class. These tests pass on main too, by design.Not done here (follow-ups)
deltaFor. Sean's call, in its own PR.scoreSettledInteraction. Until one exists, this protects the seam rather than a live path.repid_grounding_claimsis missing in prod.dbGroundingStore.findClaimByEvidenceignores its read error, so its replay pre-check fails open, whileinsertClaimthrows and the resolver fails closed to 0. Worth fixing beforeGROUNDING_MODEleaves off. I did not touch it.usdcToSmallestUnitrounds a float up. The anchor check passes integer units (claimedUnits) so it never uses that path.🤖 Generated with Claude Code