feat(indexer): shielded-flow classification, non-attribution and note discovery without actor linkage #1585
Labels
No labels
agent:fix_bugfix
agent:fix_conflicts
agent:fix_security
agent:gap_analysis
agent:implement
agent:implement
agent:implement
agent:open_issues
agent:ready
agent:research
agent:security_audit
agent:verify
architecture
backend
blocker:hybrid
blocker:launch
blocker:limit-orders
blocker:v2
block:log_only
block:security
bug
ci
contracts
correctness
deploy
dev
devops
docs
documentation
duplicate
e2e
enhancement
epic
feature
frontend
functional-completion
gas
good first issue
governance
help wanted
high-risk
hooks
hybrid
indexer
infra
infrastructure
integrators
invalid
launch-blocker
limit-orders
localnet
localterra
low priority
missing-implementation
needs-design
ops
performance
priority
high
priority
medium
product
qa
QA
question
ready
ready
research
scripts
security
security-hardening
smartcontracts
tech-debt
testing
ux
UX
v2
verification
wontfix
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
code/cl8y-dex-terraclassic#1585
Loading…
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Problem and scope
Make the indexer and its public API honest and non-attributing for shielded activity, and give shielded clients a way to discover their notes without handing the indexer a user key or wallet address.
The indexer must:
/api/v1/traders/{addr}, leaderboard, positions/P&L, trader CSV) and never invent a note owner;This issue does not implement the pool (#1583), the swap (#1584), the dApp (#1586) or the security/abuse program (#1587). It depends on the emitted event shapes defined by #1583/#1584 and must be implemented against a final event schema, not a guess.
Current codebase and investigation
Reviewed checkout:
38c154958.indexer/migrations/20260310000001_initial_schema.sqlcreatesswap_eventswithsender VARCHAR(64) NOT NULL,receiver VARCHAR(64),tx_hash,offer_amount,return_amount, andidx_swaps_sender (sender, block_timestamp DESC).swap_events.senderis the DEX-visible counterparty (the pair's CW20 sender: a wallet for a direct swap, the router for a routed swap). There is no shielded/source column.indexer/src/db/queries/swap_events.rsselects bysenderfor trader histories;indexer/src/db/queries/positions.rskeystrader_positions.trader_address;indexer/src/indexer/trader_tracker.rsandposition_tracker.rsbuild trader/position state from swaps.indexer/src/api/mod.rs:/api/v1/pairs/{addr}/trades(returnsTradeResponse.sender,api/pairs.rsaround line 524–588),/api/v1/traders/leaderboard,/api/v1/traders/{addr}and/trades,/limit-fills,/limit-placements,/limit-cancellations(CSV export infrontend-dapp/src/services/indexer/client.tsaround lines 476–557),/api/v1/compliance/blacklist-check(takeswallet),/api/v1/evidence/daily(schema 2, no actor identifiers), plus GT/CG/CMC, DeFiLlama and protocol fee/volume endpoints.indexer/src/api/route_solver.rsacceptstrader/sender(lines ~46, 92–124) and caches(trader, sender) -> discount_bps;frontend-dapp/src/services/indexer/client.tsalways sends the connected wallet astraderfor ordinary quotes. This is a direct wallet-to-intent leak if reused for shielded quotes.indexer/src/indexer/parser.rswalks wasm events;event_amount.rsnormalises amounts;asset_code_id_freeze.rsandlisting_exclude.rsalready classify assets by code id/listing.docs/indexer-invariants.mdis the invariant home;docs/indexer-http.mdis the HTTP pack/OpenAPI source; #1397 is the precedent for schema-2 evidence with explicit non-anonymity language.swap_events.senderand would appear as a "trader" with volume, positions, a leaderboard rank and CSV history.Why a new implementation is needed
If the pool's swaps are indexed like any other swap, the public API will publish the pool as a trader, rank it, compute positions and P&L, and serve its history under
/api/v1/traders/{pool}. That is not a direct user-address leak, but it is misleading analytics, it creates an attribution surface the feature explicitly must not create, and it invites scraping/correlation of shielded flows. Conversely, dropping shielded swaps from the tape would undercount pair volume, protocol fees, TVL and every external listing (GT/CG/CMC/DeFiLlama), breaking existing accounting invariants.Clients also need note discovery. If the API offers "notes for pubkey P", it becomes a per-key balance oracle and the indexer sees the user's key in every request. If it offers nothing, the dApp must scan all chain history itself, which is not viable on mobile. A range-based, cacheable, opaque-payload endpoint with strict budgets is the compromise.
Relevant files
indexer/migrations/(new migration; follow the date-prefixed pattern, include a revert)indexer/src/indexer/{parser,trader_tracker,position_tracker,volume_aggregator,protocol_fees,asset_code_id_freeze}.rsindexer/src/db/queries/{swap_events,positions,traders,pairs,pair_volume_usd,protocol_fee_series,evidence_daily,evidence_digest}.rsindexer/src/api/{mod,pairs,traders,compliance,route_solver,evidence,gt,cg,cmc,defillama,protocol_volume,protocol_fees,overview}.rsindexer/src/config.rs(shielded pool addresses/allowlist; read-only env)indexer/tests/(integration tests; Postgres under #1396)docs/indexer-http.md,docs/indexer-invariants.md,docs/qa/issue-<N>/README.md,skills/AGENTS_INDEXER_SHIELDED.mdindexer/src/api/route_solver.rs(no-RPC and discount cache),indexer/src/api/evidence.rs(schema 2),docs/qa/issue-1397/README.mdanddocs/qa/issue-694/README.md(budgets)Recommended direction
Trusted classification, not heuristics. Configure
SHIELDED_POOL_ADDRESSES(and the pool's code id/checksum pin) in indexer config. Mark a swap shielded only when on-chain evidence is unambiguous: the pair'sreceiveris the pool and/or the initiating sender is the pool, or the pool emits its ownaction=shielded_swapattribute. Do not trust a user-suppliedshieldedflag or a token metadata field. If the evidence is ambiguous, leave the row unclassified (fail-closed for non-attribution) and surface an internal counter; do not guess.Schema. Add a small, explicit classification to
swap_events(e.g.venue_source TEXT NOT NULL DEFAULT 'dex'with valuesdex,shielded_pool, plusshielded_pool_id/shielded_pool_addressnullable) or a dedicatedshielded_swapstable; choose the option that keeps pair/protocol queries simple and does not duplicate economic rows. Add an index for the classifier. Backfill is not required for pre-deployment rows, but the migration must be idempotent and re-runnable and must not rewrite history. Do not store note commitments, nullifiers, openings, owner pubkeys or change notes in the indexer. The indexer's job is the swap/transfer, not the note graph.Economic inclusion. Pair volume/candles, protocol volume, protocol fees, TVL, DeFiLlama UTC-day volume/fees, GT/CG/CMC trade and pair surfaces and the overview must include shielded swaps exactly once. Guard against double counting: the pair emits the swap and the pool emits settlement; the parser must not write two
swap_eventsrows for one swap. Add an invariant test that sums the shielded + non-shielded rows against the pair's own swap count for a fixture.Non-attribution.
trader_trackerandposition_trackermust skip rows wherevenue_source = 'shielded_pool'.GET /api/v1/traders/{addr}for the pool address returns a documented404/not_attributableresponse (not a 200 with zeroed stats, which invites "the pool has no activity" confusion); leaderboard queries exclude the pool; CSV exports must not include shielded rows under a wallet identity.GET /api/v1/pairs/{addr}/tradesmay keep the pool address assender(it is public on chain) but must addshielded: trueso clients can label it without a user identity. Do not add a per-note or per-owner field anywhere.Note discovery endpoint. Add
GET /api/v1/shielded/notes?pool=<addr>&from_leaf=<n>&limit=<n>returning a bounded page of opaque note payloads emitted by the pool (leaf index, commitment, token, amount, owner pubkey, blinding/opening if phase-1 policy makes them public, plus the insert height and root). Requirements: query only by pool + leaf range; no pubkey/wallet/owner filter; no authentication that ties a request to a user;limit≤ e.g. 200;from_leafmonotonic; cacheable with a short TTL; no note payload in access logs; API4-style in-flight/output caps (#694/#1397) and a 429/400 policy for oversize or malformed ranges. If the pool later encrypts the payload, the endpoint returns ciphertext unchanged and the contract is unchanged. Document that the endpoint reveals the public note set and is not an anonymity service.Quote privacy. Shielded quotes must use the pool address or no
trader/sender; never the user's wallet. Validate and normalise the quote parameters, keep the existing no-request-triggered-RPC rule, and ensure the discount cache key can never mix the user's address into a shielded quote. Add an indexer test that a shielded quote with a wallettraderis rejected or ignored deterministically, and a frontend contract (with #1586) that the wallet is not sent.Evidence and listings. Evidence schema remains schema 2 with no actor identifiers; shielded swaps are included in the economic rows with the pool address (public) and no note/owner data. Confirm schema/privacy-policy strings remain accurate and update the "retained public transaction hashes" language if needed. GT/CG/CMC/DeFiLlama can include shielded volume/trades; no new actor fields. Keep the existing no-actor guarantees of #1397.
Operations and docs. Update
docs/indexer-http.md/OpenAPI with the new field/endpoint and explicit privacy language; updatedocs/indexer-invariants.mdwith the classification, double-count and non-attribution invariants; add a runbook note for the pool address/code-id pin and for re-ingesting after a pool upgrade.Constraints and guardrails
from_leaftogether with a client identifier; retain only aggregate counters.limit, no per-key query. Caches must be keyed by pool + leaf range, not by client.Acceptance criteria
shieldedattribute from a non-pool contract or a user-supplied flag cannot classify a row./api/v1/pairs/{addr}/tradesmarks shielded rows without a user identity and keeps the pool address (public) where the chain shows it; pair/protocol volume, fees, candles and TVL include shielded swaps exactly once./api/v1/traders/{pool}, the leaderboard, positions/P&L and CSV exports never attribute shielded activity; the pool is excluded (or returns the documented non-attributable response) and non-shielded trader surfaces are unchanged.GET /api/v1/shielded/notesreturns bounded, cacheable opaque pages by pool + leaf range only; there is no pubkey/wallet filter and no per-key balance surface; caps and error codes are documented and tested.traderfor shielded quotes; no request-triggered RPC and no cache-key cross-contamination with wallet-discount entries.docs/indexer-http.md,docs/indexer-invariants.md, the OpenAPI spec,docs/qa/issue-<N>/README.mdandskills/AGENTS_INDEXER_SHIELDED.mdare updated;make verify-issue-<N>exists.Test plan: functional paths
shieldedattribute, missing/duplicate pool config, pool code-id drift, ambiguous evidence./api/v1/traders/{addr}for a user, the pool and an unknown address; leaderboard before/after shielded volume; positions/P&L; CSV exports; limit fills/placements/cancellations; assert no shielded attribution./api/v1/pairs/{addr}/tradesordering, pagination, sender=pool,shieldedflag, amount/price fields, mixed shielded/non-shielded pages, cursor stability.from_leafat/after the end, maxlimit, over-cap, malformed/negative/non-numeric ranges, cross-pool request, cache hit/miss, payload with future encrypted/phase-2 shape.senderset, mixed case, invalid address, cached discount entries; assert request path and cache keys.Test plan: attacks, hacks and abuse
trader/sender/wallet parameters on shielded paths, cache keys keyed by wallet, response timing differences, CSV/OpenAPI examples,Referer/query-string logging, and public API joins. Prove no endpoint returns a note owner or a user wallet for shielded activity, and no cache key contains a user address.action=shielded_swapor a fake pool address; a user supplies ashieldedflag; a token metadata field claims shielding; the pool address is copied by an attacker contract. Classification must use the configured pool and verified code id, never self-report.from_leafscans, combining the endpoint with public deposits, adding a pubkey filter, or using response sizes/timings to infer a user's note count. Enforce range-only queries, caps, caching, no per-key aggregation and no request-time key handling.SHIELDED_POOL_ADDRESSESupdate, a pool code-id drift, or an attacker-controlled pool upgrade that changes event names. Fail closed, alert, and do not reclassify old rows.Verification criteria
make verify-issue-<N>runs indexer fmt/clippy/build, the new migration up/down, integration tests against disposable Postgres (#1396), OpenAPI/schema checks, doc cross-links and the existing indexer suites (cargo test --lib, relevant--testbins).docs/qa/issue-<N>/README.mdrecords executed checks, explicit skips (e.g. deployed-indexer verification) and the agent checklist. Executed failures remain FAIL; unavailable checks may be explicit SKIP with PASS WITH SKIPS, without claiming deployed acceptance.Out of scope / follow-ups