From f59ae719df65245541f289076184fd65b0f7a508 Mon Sep 17 00:00:00 2001 From: lin1er Date: Thu, 17 Sep 2026 00:44:53 +0700 Subject: [PATCH 1/2] feat(STE-46): GET /licenses lists every licence an address holds, from the contract Frontend asked (Ancung) for "which licences does G... hold" without iterating get_token 1..total_supply from the browser on every visit. Decision: the list is the tokens contract's own enumeration, not the event index the ticket suggested. getEvents only reaches back about a week on testnet, so an event-built list silently drops older licences after a rebuild; deleting a cache must never change an answer (api-spec 6). Tokens are soulbound and never burned, so each get_token record is cached by id for good and only newly minted ids are read. total_supply is read live on every request, so the list is complete to the current ledger. The indexer now also tails license_minted from the tokens contract into its own table, only to attach mint_tx; a licence older than the event window is listed with mint_tx null, never omitted. Events are accepted per contract: license_minted only from the tokens contract, registry events only from the registry, so nothing new can leak into /feed. A failed total_supply or get_token read is 502, never a shorter list; TokenNotFound below total_supply is a failed read, and the next request fills the gap. Tests: API 170 passed (25 new for /licenses, 3 for event decoding). E2E on testnet against a local API with the indexer on: - all 9 holders' lists equal a direct get_token enumeration (supply 28), every listed licence confirmed by has_license on chain; - mint_tx from indexed events matches 3 known mints; - 19 VERIFIED badges of the developer are not listed as licences; - a fresh production purchase (GAFQ6QYS..., mint dcaac10e) is listed, and its mint_tx attaches once indexed; - with the index file deleted and the indexer off, every list is unchanged (mint_tx null). --- api/src/sterish_api/chain.py | 22 ++ api/src/sterish_api/indexer.py | 55 +++- api/src/sterish_api/licenses.py | 163 ++++++++++++ api/src/sterish_api/main.py | 3 +- api/src/sterish_api/models.py | 30 +++ api/src/sterish_api/routes/license.py | 49 +++- api/tests/test_indexer_decode.py | 43 +++- api/tests/test_licenses_by_agent.py | 243 ++++++++++++++++++ docs/api-spec.md | 58 +++++ ...e-46-e2e-licenses-by-agent-2026-09-17.json | 159 ++++++++++++ 10 files changed, 818 insertions(+), 7 deletions(-) create mode 100644 api/src/sterish_api/licenses.py create mode 100644 api/tests/test_licenses_by_agent.py create mode 100644 docs/evidence/ste-46-e2e-licenses-by-agent-2026-09-17.json diff --git a/api/src/sterish_api/chain.py b/api/src/sterish_api/chain.py index 303ee17..de9038d 100644 --- a/api/src/sterish_api/chain.py +++ b/api/src/sterish_api/chain.py @@ -229,3 +229,25 @@ def is_verified_token(skill_id: str, version: str) -> bool: [scval.to_string(skill_id), scval.to_string(version)], ) ) + + +def total_supply() -> int: + """Tokens ever minted on the tokens contract. Ids run 1..total_supply and nothing + is ever burned, so this is exact (contracts/tokens/src/lib.rs::total_supply).""" + return int(_tokens_invoke("total_supply", [])) + + +def get_token(token_id: int) -> dict: + """`get_token(u32) -> TokenRecord`, decoded. `kind` is "VERIFIED" or "LICENSE".""" + raw = _tokens_invoke("get_token", [scval.to_uint32(token_id)]) + kind = raw.get("kind") + if isinstance(kind, (list, tuple)) and kind: + kind = kind[0] + return { + "token_id": int(raw["token_id"]), + "kind": str(kind).upper(), + "skill_id": str(raw["skill_id"]), + "version": str(raw["version"]), + "owner": address_str(raw.get("owner")), + "minted_at": int(raw["minted_at"]), + } diff --git a/api/src/sterish_api/indexer.py b/api/src/sterish_api/indexer.py index 188ab3d..5869ba2 100644 --- a/api/src/sterish_api/indexer.py +++ b/api/src/sterish_api/indexer.py @@ -1,7 +1,9 @@ """Lightweight event indexer. Tails the registry's `skill_registered` / `version_registered` / `version_recorded` / -`verdict_flipped` events into SQLite. Two jobs: +`verdict_flipped` events into SQLite, and the tokens contract's `license_minted` into its +own table (STE-46, only to attach a mint transaction to a licence — see licenses.py for +why the licence list itself is not built from events). Two jobs: 1. supply the transaction hashes for the `evidence` object — the contract does not store them, so without this the tx links are permanently null; @@ -83,9 +85,13 @@ def init_db() -> None: def rebuild() -> None: """Drop every indexed row and reset the cursor. The next poll refills from chain.""" + from . import licenses + + licenses.init_db() with _lock, _connect() as conn: conn.executescript(_SCHEMA) conn.execute("DELETE FROM events") + conn.execute("DELETE FROM license_events") conn.execute("DELETE FROM meta WHERE key = 'last_indexed_ledger'") logger.info("indexer cache dropped; will rebuild from chain") @@ -176,6 +182,30 @@ def feed( # --- polling ---------------------------------------------------------------- +def _decode_license_event(ev: Any, topics: list) -> dict | None: + """`license_minted` (docs/specs/events.md §3b.2): topics (name, skill_id, version), + data {agent}. Accepted only from the configured tokens contract.""" + if not settings.tokens_contract_id or getattr(ev, "contract_id", None) != ( + settings.tokens_contract_id + ): + return None + if len(topics) < 3: + return None + value = scval.to_native(stellar_xdr.SCVal.from_xdr(ev.value)) + agent = address_str(value.get("agent")) if isinstance(value, dict) else None + if not agent: + return None + return { + "tokens_contract_id": settings.tokens_contract_id, + "agent": agent, + "skill_id": str(topics[1]), + "version": str(topics[2]), + "ledger": int(ev.ledger), + "tx_hash": ev.transaction_hash, + "occurred_at": _ledger_time(ev), + } + + def _decode_event(ev: Any) -> dict | None: # Events emitted inside a contract call that ultimately failed are not facts about # the ledger state; indexing them would show phantom activity in the feed. Current @@ -189,8 +219,16 @@ def _decode_event(ev: Any) -> dict | None: if not topics: return None name = str(topics[0]) + if name == "license_minted": + row = _decode_license_event(ev, topics) + return {"_license": row} if row else None if name not in TRACKED_EVENTS: return None + # Registry events only from the registry: the filter now also covers the tokens + # contract, and nothing else it emits may land in the feed table. + contract_id = getattr(ev, "contract_id", None) + if contract_id is not None and contract_id != settings.registry_contract_id: + return None value = scval.to_native(stellar_xdr.SCVal.from_xdr(ev.value)) if not isinstance(value, dict): @@ -250,7 +288,10 @@ def _get_events(server: SorobanServer, start: int): filters=[ EventFilter( event_type=EventFilterType.CONTRACT, - contract_ids=[settings.registry_contract_id], + contract_ids=[ + c for c in (settings.registry_contract_id, settings.tokens_contract_id) + if c + ], ) ], limit=200, @@ -319,13 +360,21 @@ def poll_once() -> int: logger.warning("indexer: getEvents at %s failed: %s", start, exc) break - rows = [r for r in (_decode_event(e) for e in res.events) if r] + decoded = [r for r in (_decode_event(e) for e in res.events) if r] + rows = [r for r in decoded if "_license" not in r] new_rows = _store(rows) if new_rows: # A registration, a new version or a verdict landed: the filtered /skills # view (STE-34) may now be wrong, so drop it rather than wait out its TTL. registry_snapshot.invalidate() stored += new_rows + if any("_license" in r for r in decoded): + from . import licenses + + for r in decoded: + if "_license" in r: + licenses.record_license_event(r["_license"]) + stored += 1 start = min(start + chunk, latest + 1) _meta_set("last_indexed_ledger", str(min(start - 1, latest))) diff --git a/api/src/sterish_api/licenses.py b/api/src/sterish_api/licenses.py new file mode 100644 index 0000000..707ee6f --- /dev/null +++ b/api/src/sterish_api/licenses.py @@ -0,0 +1,163 @@ +"""Every licence one address holds (STE-46), read from the tokens contract. + +**Why not simply the event index.** The ticket suggested tailing `license_minted`. That +alone would be wrong in the same way STE-34 found for `/skills`: `getEvents` only reaches +back as far as the RPC node retains events (about a week on testnet), so an index rebuilt +today silently lacks every licence minted before that window, and an address that paid a +month ago would be told it holds nothing. Deleting the cache must never change an answer. + +So the list comes from the contract's own enumeration: `total_supply()` then +`get_token(id)` for ids 1..total_supply. Tokens are soulbound and never burned, so a +record, once read, is true forever — it is cached by id and only the ids minted since the +last request are read. Every request still reads `total_supply` live, so the list is +complete up to the current ledger, never up to whenever the cache was last filled. + +`license_minted` events are still tailed (indexer.py), but only to decorate a licence with +the transaction that minted it; a licence older than the event window is listed with +`mint_tx: null`, never left out. + +A read that fails is raised, never served as a shorter list (api-spec §6). +""" + +from __future__ import annotations + +import logging +import sqlite3 +import threading +from typing import Any + +from . import chain, fanout +from .config import settings + +logger = logging.getLogger(__name__) + +_SCHEMA = """ +CREATE TABLE IF NOT EXISTS tokens ( + tokens_contract_id TEXT NOT NULL, + token_id INTEGER NOT NULL, + kind TEXT NOT NULL, + skill_id TEXT NOT NULL, + version TEXT NOT NULL, + owner TEXT NOT NULL, + minted_at INTEGER NOT NULL, + PRIMARY KEY (tokens_contract_id, token_id) +); +CREATE INDEX IF NOT EXISTS idx_tokens_owner ON tokens (tokens_contract_id, owner, kind); +CREATE TABLE IF NOT EXISTS license_events ( + tokens_contract_id TEXT NOT NULL, + agent TEXT NOT NULL, + skill_id TEXT NOT NULL, + version TEXT NOT NULL, + ledger INTEGER NOT NULL, + tx_hash TEXT NOT NULL, + occurred_at INTEGER, + UNIQUE (tokens_contract_id, agent, skill_id, version, tx_hash) +); +CREATE INDEX IF NOT EXISTS idx_license_events ON license_events + (tokens_contract_id, agent, skill_id, version); +""" + +_db_lock = threading.Lock() +# One sync at a time: two page loads racing would otherwise both read the same new ids. +_sync_lock = threading.Lock() + + +def _connect() -> sqlite3.Connection: + conn = sqlite3.connect(settings.db_path, check_same_thread=False) + conn.row_factory = sqlite3.Row + return conn + + +def init_db() -> None: + with _db_lock, _connect() as conn: + conn.executescript(_SCHEMA) + + +def _known_ids(contract: str) -> set[int]: + with _db_lock, _connect() as conn: + conn.executescript(_SCHEMA) + rows = conn.execute( + "SELECT token_id FROM tokens WHERE tokens_contract_id = ?", (contract,) + ).fetchall() + return {int(r["token_id"]) for r in rows} + + +def _store_tokens(contract: str, records: list[dict]) -> None: + with _db_lock, _connect() as conn: + conn.executemany( + "INSERT OR IGNORE INTO tokens " + "(tokens_contract_id, token_id, kind, skill_id, version, owner, minted_at) " + "VALUES (?, ?, ?, ?, ?, ?, ?)", + [ + (contract, r["token_id"], r["kind"], r["skill_id"], r["version"], + r["owner"], r["minted_at"]) + for r in records + ], + ) + + +def sync() -> int: + """Bring the token cache up to the live `total_supply`. Returns that supply. + + Reads every id not yet cached, including gaps a crashed earlier sync left behind. + Raises `chain.ChainError` if any of them cannot be read. + """ + contract = settings.tokens_contract_id + if not contract: + raise chain.NotConfiguredError("TOKENS_CONTRACT_ID (or TOKENS_CA) is not set") + + with _sync_lock: + supply = chain.total_supply() + missing = sorted(set(range(1, supply + 1)) - _known_ids(contract)) + if not missing: + return supply + + def read(token_id: int) -> dict: + try: + return chain.get_token(token_id) + except chain.ContractError as exc: + # An id at or below total_supply that the contract cannot return is not + # "no such licence"; it is a read we could not complete. + raise chain.ChainError( + f"get_token({token_id}) failed below total_supply {supply}: {exc}" + ) from exc + + records = fanout.map_bounded(read, missing, settings.chain_concurrency) + _store_tokens(contract, records) + logger.info("licences: cached %s new token records (supply %s)", len(records), supply) + return supply + + +def record_license_event(row: dict[str, Any]) -> None: + """Store one decoded `license_minted` event (called by the indexer).""" + with _db_lock, _connect() as conn: + conn.executescript(_SCHEMA) + conn.execute( + "INSERT OR IGNORE INTO license_events " + "(tokens_contract_id, agent, skill_id, version, ledger, tx_hash, occurred_at) " + "VALUES (:tokens_contract_id, :agent, :skill_id, :version, :ledger, :tx_hash, " + " :occurred_at)", + row, + ) + + +def for_agent(agent: str) -> list[dict[str, Any]]: + """Licences held by `agent` on the configured tokens contract, newest first. + + Call `sync()` first; this reads the cache it filled. + """ + contract = settings.tokens_contract_id + with _db_lock, _connect() as conn: + conn.executescript(_SCHEMA) + rows = conn.execute( + "SELECT t.token_id, t.skill_id, t.version, t.minted_at, " + " (SELECT e.tx_hash FROM license_events e " + " WHERE e.tokens_contract_id = t.tokens_contract_id AND e.agent = t.owner " + " AND e.skill_id = t.skill_id AND e.version = t.version " + " ORDER BY e.ledger DESC LIMIT 1) AS mint_tx " + "FROM tokens t " + "WHERE t.tokens_contract_id = ? AND t.owner = ? AND t.kind = 'LICENSE' " + "ORDER BY t.minted_at DESC, t.token_id DESC", + (contract, agent), + ).fetchall() + return [dict(r) for r in rows] diff --git a/api/src/sterish_api/main.py b/api/src/sterish_api/main.py index a906c41..3fb963b 100644 --- a/api/src/sterish_api/main.py +++ b/api/src/sterish_api/main.py @@ -13,7 +13,7 @@ from fastapi.responses import JSONResponse from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware -from . import chain, indexer, payments, proofs, x402 +from . import chain, indexer, licenses, payments, proofs, x402 from .chain import ChainError, ContractError, NotConfiguredError from .config import settings from .errors import ( @@ -54,6 +54,7 @@ async def lifespan(app: FastAPI): # and the evidence lookups then read an empty index instead of erroring on a # missing table. indexer.init_db() + licenses.init_db() # The payments ledger is not a cache (STE-42): created here, never rebuilt. payments.init_db() proofs.init_db() diff --git a/api/src/sterish_api/models.py b/api/src/sterish_api/models.py index c911406..2c2233e 100644 --- a/api/src/sterish_api/models.py +++ b/api/src/sterish_api/models.py @@ -180,3 +180,33 @@ class HealthResponse(BaseModel): class ErrorResponse(BaseModel): error: str detail: str = "" + + +class LicenseItem(BaseModel): + token_id: int + skill_id: str + version: str + minted_at: int + minted_at_iso: str | None + # From the indexed `license_minted` event; null when the mint is older than the RPC's + # event window or not indexed yet. The licence is listed either way. + mint_tx: str | None + mint_tx_url: str | None + + +class LicensesByAgentResponse(BaseModel): + """`GET /licenses?agent=G...` (STE-46). + + Ownership only, like `/license`: no verdict is joined in. Whether a licensed version + is still SAFE is a different read against a different contract (`/check`). + """ + + agent: str + licenses: list[LicenseItem] + total: int + start: int + limit: int + # `total_supply()` read live for this response: the list is complete up to it. + total_supply: int + tokens_contract_id: str + contract_url: str diff --git a/api/src/sterish_api/routes/license.py b/api/src/sterish_api/routes/license.py index 0bd13f8..c3679b9 100644 --- a/api/src/sterish_api/routes/license.py +++ b/api/src/sterish_api/routes/license.py @@ -24,10 +24,10 @@ from fastapi import APIRouter, Query, Request from stellar_sdk.strkey import StrKey -from .. import chain +from .. import chain, licenses from ..config import settings from ..errors import ApiError -from ..models import LicenseStatusResponse +from ..models import LicenseItem, LicensesByAgentResponse, LicenseStatusResponse, iso_or_none router = APIRouter() @@ -97,3 +97,48 @@ def license_status( tokens_contract_id=settings.tokens_contract_id, contract_url=settings.contract_url(settings.tokens_contract_id), ) + + +@router.get("/licenses", response_model=LicensesByAgentResponse) +def licenses_by_agent( + request: Request, + agent: str | None = Query(default=None, description="Stellar account address (G...)"), + start: int = Query(default=0, ge=0), + limit: int = Query(default=50, ge=1, le=200), +): + """Every licence `agent` holds on the tokens contract, newest first (STE-46). + + Built from the contract's own `total_supply` / `get_token` enumeration, not from the + event window, so an old licence is never missing (licenses.py). A failed read is + 502, never an empty list. + """ + agent_address = _agent_address(request, agent) + + if not settings.tokens_contract_id: + raise ApiError(503, "NOT_CONFIGURED", "TOKENS_CONTRACT_ID (or TOKENS_CA) is not set") + + supply = licenses.sync() + rows = licenses.for_agent(agent_address) + page = rows[start : start + limit] + + return LicensesByAgentResponse( + agent=agent_address, + licenses=[ + LicenseItem( + token_id=r["token_id"], + skill_id=r["skill_id"], + version=r["version"], + minted_at=r["minted_at"], + minted_at_iso=iso_or_none(r["minted_at"]), + mint_tx=r["mint_tx"], + mint_tx_url=settings.tx_url(r["mint_tx"]) if r["mint_tx"] else None, + ) + for r in page + ], + total=len(rows), + start=start, + limit=limit, + total_supply=supply, + tokens_contract_id=settings.tokens_contract_id, + contract_url=settings.contract_url(settings.tokens_contract_id), + ) diff --git a/api/tests/test_indexer_decode.py b/api/tests/test_indexer_decode.py index 2469789..0085814 100644 --- a/api/tests/test_indexer_decode.py +++ b/api/tests/test_indexer_decode.py @@ -5,13 +5,15 @@ from stellar_sdk import Address, scval from sterish_api import indexer +from sterish_api.config import settings G = "GD73M4F7RN74KBLFGJP4WKBMCBJWBOA4SFNOP5HG4NBCDQUQCC2ARSZU" HASH = bytes.fromhex("c2bd4a316415b4919e3f1f40d9925f4052d020cf3dc2ecabe0e7c9dd28cc87f0") -def _event(topics, value, successful=True, ledger=4482518, tx="ab" * 32): +def _event(topics, value, successful=True, ledger=4482518, tx="ab" * 32, contract_id=None): ev = Mock() + ev.contract_id = contract_id or settings.registry_contract_id ev.topic = [ scval.to_symbol(t).to_xdr() if isinstance(t, str) and t.islower() and "." not in t @@ -70,3 +72,42 @@ def test_versionless_event_stores_empty_string_so_dedupe_works(): assert indexer._store([row]) == 1 assert indexer._store([row]) == 0 # the duplicate is rejected assert indexer.feed()[1] == 1 + + +# --- STE-46: license_minted from the tokens contract ------------------------------------- + + +def _license_event(contract_id=None, agent=G): + value = scval.to_map({scval.to_symbol("agent"): scval.to_address(Address(agent))}) + return _event( + ["license_minted", "com.acme.pdf-suite", "1.0.0"], value, + contract_id=contract_id or settings.tokens_contract_id, + ) + + +def test_license_minted_decodes_to_a_license_row(): + row = indexer._decode_event(_license_event()) + assert row == { + "_license": { + "tokens_contract_id": settings.tokens_contract_id, + "agent": G, + "skill_id": "com.acme.pdf-suite", + "version": "1.0.0", + "ledger": 4482518, + "tx_hash": "ab" * 32, + "occurred_at": row["_license"]["occurred_at"], + } + } + + +def test_license_minted_from_another_contract_is_ignored(): + """The filter lists our contracts, but a decoder must not trust that alone.""" + other = "CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA" + assert indexer._decode_event(_license_event(contract_id=other)) is None + + +def test_a_registry_event_name_from_the_tokens_contract_never_reaches_the_feed(): + value = scval.to_map({scval.to_symbol("owner"): scval.to_address(Address(G))}) + ev = _event(["skill_registered", "com.acme.pdf-suite"], value, + contract_id=settings.tokens_contract_id) + assert indexer._decode_event(ev) is None diff --git a/api/tests/test_licenses_by_agent.py b/api/tests/test_licenses_by_agent.py new file mode 100644 index 0000000..60f7986 --- /dev/null +++ b/api/tests/test_licenses_by_agent.py @@ -0,0 +1,243 @@ +"""`GET /licenses?agent=G...` (STE-46), with the tokens contract stubbed. + +The tests that matter are the ones about what the list must never do: miss a licence +because its event fell out of the RPC window, shrink because a read failed, or change +because the cache was deleted. +""" + +import sqlite3 + +import pytest + +from sterish_api import chain, licenses +from sterish_api.config import settings + +AGENT = "GD73M4F7RN74KBLFGJP4WKBMCBJWBOA4SFNOP5HG4NBCDQUQCC2ARSZU" +OTHER = "GCFCURTZ7XHMTKZR7QN2MXRRAIWKGVOOVQV4KCP5EIQ62HGG4S3Y2XPL" + + +def _token(token_id, kind, skill_id, version, owner, minted_at): + return { + "token_id": token_id, "kind": kind, "skill_id": skill_id, "version": version, + "owner": owner, "minted_at": minted_at, + } + + +class Tokens: + """A tokens contract: ids 1..n, never burned, reads counted.""" + + def __init__(self, monkeypatch): + self.records = [ + _token(1, "VERIFIED", "com.acme.pdf-suite", "1.0.0", OTHER, 100), + _token(2, "LICENSE", "com.acme.pdf-suite", "1.0.0", AGENT, 200), + _token(3, "LICENSE", "com.acme.pdf-suite", "1.0.0", OTHER, 300), + _token(4, "LICENSE", "com.acme.weather", "2.0.0", AGENT, 400), + ] + self.get_calls: list[int] = [] + self.supply_calls = 0 + self.fail_ids: set[int] = set() + self.supply_error: Exception | None = None + monkeypatch.setattr(chain, "total_supply", self.total_supply) + monkeypatch.setattr(chain, "get_token", self.get_token) + + def total_supply(self): + self.supply_calls += 1 + if self.supply_error: + raise self.supply_error + return len(self.records) + + def get_token(self, token_id): + self.get_calls.append(token_id) + if token_id in self.fail_ids: + raise chain.ChainError(f"rpc timeout on {token_id}") + return dict(self.records[token_id - 1]) + + def mint(self, kind, skill_id, version, owner, minted_at): + self.records.append( + _token(len(self.records) + 1, kind, skill_id, version, owner, minted_at) + ) + + +@pytest.fixture +def tokens(monkeypatch): + return Tokens(monkeypatch) + + +def ids(response): + return [(r["token_id"], r["skill_id"], r["version"]) for r in response.json()["licenses"]] + + +class TestTheList: + def test_only_this_agents_licences_newest_first(self, client, tokens): + r = client.get("/licenses", params={"agent": AGENT}) + assert r.status_code == 200 + assert ids(r) == [(4, "com.acme.weather", "2.0.0"), (2, "com.acme.pdf-suite", "1.0.0")] + body = r.json() + assert body["agent"] == AGENT + assert body["total"] == 2 + assert body["total_supply"] == 4 + assert body["tokens_contract_id"] == settings.tokens_contract_id + assert body["contract_url"].endswith(settings.tokens_contract_id) + + def test_a_verified_badge_is_not_a_licence(self, client, tokens): + """Token 1 is OTHER's VERIFIED badge; OTHER holds exactly one licence (3).""" + assert ids(client.get("/licenses", params={"agent": OTHER})) == [ + (3, "com.acme.pdf-suite", "1.0.0") + ] + + def test_an_address_with_nothing_gets_an_empty_list_not_an_error(self, client, tokens): + stranger = "GBFXMHA77OLBYF3JJB43O6CKZ4QR35AAQALJK72MUIHTZNBVAQGTTZWY" + body = client.get("/licenses", params={"agent": stranger}).json() + assert body["licenses"] == [] and body["total"] == 0 and body["total_supply"] == 4 + + def test_fields_and_iso_time(self, client, tokens): + row = client.get("/licenses", params={"agent": AGENT}).json()["licenses"][0] + assert row["minted_at"] == 400 + assert row["minted_at_iso"] == "1970-01-01T00:06:40Z" + + def test_no_verdict_is_joined_in(self, client, tokens): + """Ownership and verdict are two reads (api-spec §3.8); this is the first only.""" + row = client.get("/licenses", params={"agent": AGENT}).json()["licenses"][0] + for leaked in ("verdict", "trust_score", "is_verified", "evidence"): + assert leaked not in row + + def test_the_header_form_works(self, client, tokens): + r = client.get("/licenses", headers={"X-AGENT-ADDRESS": AGENT}) + assert r.status_code == 200 and r.json()["total"] == 2 + + def test_paging(self, client, tokens): + for n in range(5, 12): + tokens.mint("LICENSE", f"com.acme.s{n}", "1.0.0", AGENT, 1000 + n) + first = client.get("/licenses", params={"agent": AGENT, "limit": 3}).json() + second = client.get("/licenses", params={"agent": AGENT, "start": 3, "limit": 3}).json() + assert first["total"] == second["total"] == 9 + assert [r["token_id"] for r in first["licenses"]] == [11, 10, 9] + assert [r["token_id"] for r in second["licenses"]] == [8, 7, 6] + + +class TestWhereTheListComesFrom: + def test_a_licence_is_listed_even_when_no_mint_event_was_indexed(self, client, tokens): + """The reason the list is not built from events: an old licence has none left.""" + row = client.get("/licenses", params={"agent": AGENT}).json()["licenses"][0] + assert row["token_id"] == 4 + assert row["mint_tx"] is None and row["mint_tx_url"] is None + + def test_an_indexed_mint_event_attaches_its_transaction(self, client, tokens): + licenses.record_license_event({ + "tokens_contract_id": settings.tokens_contract_id, "agent": AGENT, + "skill_id": "com.acme.weather", "version": "2.0.0", + "ledger": 10, "tx_hash": "cd" * 32, "occurred_at": 400, + }) + rows = client.get("/licenses", params={"agent": AGENT}).json()["licenses"] + assert rows[0]["mint_tx"] == "cd" * 32 + assert rows[0]["mint_tx_url"].endswith("/tx/" + "cd" * 32) + assert rows[1]["mint_tx"] is None # another licence's event is not borrowed + + def test_only_new_ids_are_read_on_the_next_request(self, client, tokens): + client.get("/licenses", params={"agent": AGENT}) + assert sorted(tokens.get_calls) == [1, 2, 3, 4] + tokens.get_calls.clear() + + tokens.mint("LICENSE", "com.acme.new", "1.0.0", AGENT, 500) + r = client.get("/licenses", params={"agent": AGENT}) + assert tokens.get_calls == [5] + assert ids(r)[0] == (5, "com.acme.new", "1.0.0") + + def test_supply_is_read_live_on_every_request(self, client, tokens): + client.get("/licenses", params={"agent": AGENT}) + client.get("/licenses", params={"agent": AGENT}) + assert tokens.supply_calls == 2 + + def test_deleting_the_cache_does_not_change_the_answer(self, client, tokens, _isolated_db): + before = client.get("/licenses", params={"agent": AGENT}).json() + with sqlite3.connect(_isolated_db) as conn: + conn.execute("DELETE FROM tokens") + conn.execute("DELETE FROM license_events") + after = client.get("/licenses", params={"agent": AGENT}).json() + assert before == after + + def test_records_from_another_tokens_contract_are_not_mixed_in( + self, client, tokens, monkeypatch + ): + client.get("/licenses", params={"agent": AGENT}) + previous = settings.tokens_contract_id + object.__setattr__( + settings, "tokens_contract_id", + "CCHVZRLOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + ) + try: + tokens.records = [_token(1, "LICENSE", "com.acme.v1-only", "1.0.0", AGENT, 50)] + assert ids(client.get("/licenses", params={"agent": AGENT})) == [ + (1, "com.acme.v1-only", "1.0.0") + ] + finally: + object.__setattr__(settings, "tokens_contract_id", previous) + + +class TestAFailedReadIsNeverAShorterList: + def test_total_supply_failing_is_502(self, client, tokens): + tokens.supply_error = chain.ChainError("rpc down") + r = client.get("/licenses", params={"agent": AGENT}) + assert r.status_code == 502 + assert r.json()["error"] == "RPC_UNAVAILABLE" + + def test_one_token_read_failing_is_502_not_the_other_licences(self, client, tokens): + tokens.fail_ids = {4} + r = client.get("/licenses", params={"agent": AGENT}) + assert r.status_code == 502 + assert "licenses" not in r.json() + + def test_the_next_request_fills_the_gap(self, client, tokens): + tokens.fail_ids = {4} + client.get("/licenses", params={"agent": AGENT}) + tokens.fail_ids = set() + tokens.get_calls.clear() + r = client.get("/licenses", params={"agent": AGENT}) + assert r.status_code == 200 + assert 4 in tokens.get_calls + assert ids(r)[0][0] == 4 + + def test_a_contract_refusal_below_supply_is_502_not_skipped(self, client, tokens, monkeypatch): + """TokenNotFound for an id <= total_supply cannot be "no licence"; ids are dense.""" + real = tokens.get_token + + def refuse(token_id): + if token_id == 2: + raise chain.ContractError(2, "TokenNotFound") + return real(token_id) + + monkeypatch.setattr(chain, "get_token", refuse) + assert client.get("/licenses", params={"agent": AGENT}).status_code == 502 + + +class TestValidation: + @pytest.mark.parametrize( + "params, code", + [ + ({}, "MISSING_AGENT"), + ({"agent": "not-an-address"}, "INVALID_AGENT"), + ({"agent": settings.tokens_contract_id}, "INVALID_AGENT"), + ( + {"agent": "MA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJUAAAAAAAAAAAAGZFQ"}, + "INVALID_AGENT", + ), + ], + ) + def test_agent_is_required_and_must_be_an_account(self, client, tokens, params, code): + r = client.get("/licenses", params=params) + assert r.status_code == 400 + assert r.json()["error"] == code + assert tokens.supply_calls == 0 # rejected before any chain read + + @pytest.mark.parametrize("params", [{"limit": 0}, {"limit": 201}, {"start": -1}]) + def test_paging_bounds(self, client, tokens, params): + assert client.get("/licenses", params={"agent": AGENT, **params}).status_code == 422 + + def test_not_configured_is_503(self, client, tokens): + previous = settings.tokens_contract_id + object.__setattr__(settings, "tokens_contract_id", "") + try: + r = client.get("/licenses", params={"agent": AGENT}) + assert r.status_code == 503 + finally: + object.__setattr__(settings, "tokens_contract_id", previous) diff --git a/docs/api-spec.md b/docs/api-spec.md index 52b0b8f..cbfb639 100644 --- a/docs/api-spec.md +++ b/docs/api-spec.md @@ -664,6 +664,64 @@ in 3.4 — a feed dominated by 47 scaffolding skills shows activity nobody perfo --- +### 3.10 `GET /licenses?agent=G…` — every licence one address holds (STE-46) + +Ownership only, newest first. Like §3.8 it joins in **no verdict**: whether a licensed version is +still `SAFE` is a separate read (`/check`), and the dashboard's licences page asks both. + +**Query parameters** + +| Parameter | Type | Default | Notes | +|---|---|---|---| +| `agent` | `G…` account address | — | Required. May instead be sent as `X-AGENT-ADDRESS`. `C…` and `M…` are refused. | +| `start` | integer ≥ 0 | `0` | | +| `limit` | integer 1–200 | `50` | | + +```json +{ + "agent": "GAISQEDZDZO3ZODO6DRDD3DV5VKMVNOULTU7B4VASXSXH56BUOAIPXAG", + "licenses": [ + { + "token_id": 25, + "skill_id": "org.stellar.skills.agentic-payments.x402", + "version": "2026.8.31", + "minted_at": 1789578660, + "minted_at_iso": "2026-09-16T17:11:00Z", + "mint_tx": "167557302d8a0d43e75325b012dd4c4a57da82a403a946fb13ac09f0587414b1", + "mint_tx_url": "https://stellar.expert/explorer/testnet/tx/167557302d8a0d43e75325b012dd4c4a57da82a403a946fb13ac09f0587414b1" + } + ], + "total": 1, + "start": 0, + "limit": 50, + "total_supply": 28, + "tokens_contract_id": "CB6VK4EXEN7V6MXLOFUI2ECMLSDUXAUV5EZICWBICKJDL3WPPU3CTP3T", + "contract_url": "https://stellar.expert/explorer/testnet/contract/CB6VK4EXEN7V6MXLOFUI2ECMLSDUXAUV5EZICWBICKJDL3WPPU3CTP3T" +} +``` + +**Where the list comes from — and why not the event index alone.** The ticket suggested tailing +`license_minted`. Built only from events, the list would have the flaw §3.4 describes for `/skills`: +`getEvents` reaches back only as far as the RPC node retains events (about a week on testnet), so a +rebuilt index would silently drop every older licence, and an address that bought a month ago would +be told it holds nothing. So the list is the tokens contract's own enumeration: `total_supply()`, +then `get_token(id)` for ids `1..total_supply`. Tokens are soulbound and never burned, so a record, +once read, is cached by id for good, and a request reads only the ids minted since the last one. +`total_supply` is read **live on every request**, so the list is complete up to the current ledger, +and `total_supply` in the response says what it was complete up to. VERIFIED badges share the id +space and are filtered out (`kind = License`). + +`license_minted` events are tailed by the indexer too, only to attach `mint_tx`. A licence whose +mint is older than the event window, or not indexed yet, is listed with `mint_tx: null` — never +left out. Deleting the index changes nothing but those links. + +**Degradation.** If `total_supply` or any not-yet-cached `get_token` cannot be read, the response +is `502 RPC_UNAVAILABLE` — never a shorter list. A `TokenNotFound` for an id at or below +`total_supply` is a failed read, not "no such licence": ids are dense. The next request fills the gap. + +**Errors:** `400 MISSING_AGENT`, `400 INVALID_AGENT`, `422` (paging bounds), `502 RPC_UNAVAILABLE`, +`503 NOT_CONFIGURED`. + ## 4. Errors All error responses share one shape: diff --git a/docs/evidence/ste-46-e2e-licenses-by-agent-2026-09-17.json b/docs/evidence/ste-46-e2e-licenses-by-agent-2026-09-17.json new file mode 100644 index 0000000..5111090 --- /dev/null +++ b/docs/evidence/ste-46-e2e-licenses-by-agent-2026-09-17.json @@ -0,0 +1,159 @@ +{ + "ticket": "STE-46", + "date": "2026-09-17", + "api": "local API on this branch against testnet (indexer on, caught up to ledger)", + "tokens_contract": "CB6VK4EXEN7V6MXLOFUI2ECMLSDUXAUV5EZICWBICKJDL3WPPU3CTP3T", + "total_supply": 27, + "holders": 8, + "checks": [ + { + "check": "GCF76SG6\u2026: 1 licence(s) == direct get_token enumeration", + "ok": true + }, + { + "check": " has_license(GCF76SG6\u2026, org.stellar.skills.agentic-payments.x402@2026.8.31) true on chain", + "ok": true + }, + { + "check": "GCGV7KHN\u2026: 1 licence(s) == direct get_token enumeration", + "ok": true + }, + { + "check": " has_license(GCGV7KHN\u2026, org.stellar.skills.dapp.data-fetching@2026.8.31) true on chain", + "ok": true + }, + { + "check": " mint_tx from the indexed license_minted event == known mint 3e6fcf75\u2026", + "ok": true + }, + { + "check": "GDAVKROB\u2026: 1 licence(s) == direct get_token enumeration", + "ok": true + }, + { + "check": " has_license(GDAVKROB\u2026, org.stellar.skills.data.horizon@2026.8.31) true on chain", + "ok": true + }, + { + "check": "GA5VKC7Q\u2026: 1 licence(s) == direct get_token enumeration", + "ok": true + }, + { + "check": " has_license(GA5VKC7Q\u2026, org.stellar.skills.agentic-payments.mpp@2026.8.31) true on chain", + "ok": true + }, + { + "check": "GCZDHFCV\u2026: 1 licence(s) == direct get_token enumeration", + "ok": true + }, + { + "check": " has_license(GCZDHFCV\u2026, com.sterish.e2e-rehearsal-unit-converter-1789569559@1.0.0) true on chain", + "ok": true + }, + { + "check": "GDUKDRK6\u2026: 1 licence(s) == direct get_token enumeration", + "ok": true + }, + { + "check": " has_license(GDUKDRK6\u2026, org.stellar.skills.cross-chain.axelar@2026.8.31) true on chain", + "ok": true + }, + { + "check": "GAISQEDZ\u2026: 1 licence(s) == direct get_token enumeration", + "ok": true + }, + { + "check": " has_license(GAISQEDZ\u2026, org.stellar.skills.agentic-payments.x402@2026.8.31) true on chain", + "ok": true + }, + { + "check": " mint_tx from the indexed license_minted event == known mint 16755730\u2026", + "ok": true + }, + { + "check": "GDH5RSHS\u2026: 1 licence(s) == direct get_token enumeration", + "ok": true + }, + { + "check": " has_license(GDH5RSHS\u2026, org.stellar.skills.cross-chain.cctp@2026.8.31) true on chain", + "ok": true + }, + { + "check": " mint_tx from the indexed license_minted event == known mint e9ea2e19\u2026", + "ok": true + }, + { + "check": "developer GD73M4F7\u2026 (owns 19 VERIFIED badges): badges are not listed as licences", + "ok": true + }, + { + "check": "no agent -> 400 MISSING_AGENT", + "ok": true + }, + { + "check": "{'agent': 'CB6VK4EXEN7V6MXLOFUI2ECMLSDUXAUV5EZICWBICKJDL3WPPU3CTP3T'} -> 400 INVALID_AGENT", + "ok": true + } + ], + "result": "pass", + "fresh_purchase": { + "agent": "GAFQ6QYS73QXCOGJSCSBR7HAQBUKNNCIE5JQINF6TH2TMF6N6OSI6TY5", + "skill": "org.stellar.skills.dapp.react@2026.8.31", + "mint_tx": "dcaac10eb4f02afe65ae31a83874e1d37dd7700a23794e23c230c019b3aab3f0", + "listed": true, + "mint_tx_attached_once_indexed": true + }, + "cache_deleted_indexer_off": { + "total_supply": 28, + "holders": 9, + "all_lists_match_direct_enumeration": true, + "mint_tx": "null for all (decoration only)", + "rows": [ + { + "agent": "GCF76SG6QUBTJHK6AEFPS22TOB6JO5TKXXR5FW3QSDFOFLNXNLCJTXSC", + "licences": 1, + "match": true + }, + { + "agent": "GCGV7KHNO5G6MSRTJHIXDYROGOFR2VF5Y4CS5ADS2ZW4SPIU6HVON36R", + "licences": 1, + "match": true + }, + { + "agent": "GDAVKROBU6VGWMAY36YMHQ6LV7XD7D5R5T3LJTTEBJKX3EURZAEDHSPL", + "licences": 1, + "match": true + }, + { + "agent": "GA5VKC7QHIIC7GBXMHLILU2LMKKXYAHOFNE77CUOGMLO4GB3ZKP5HZS7", + "licences": 1, + "match": true + }, + { + "agent": "GCZDHFCV73PFEO53ERKVOEBU3X2QYL7UGHOX5BBSDEID4FSM4NDCPWQN", + "licences": 1, + "match": true + }, + { + "agent": "GDUKDRK63Q24NORQ4SQPUQKZNASZELTDXR7TCLV5T6X5X2BYCLEYNITH", + "licences": 1, + "match": true + }, + { + "agent": "GAISQEDZDZO3ZODO6DRDD3DV5VKMVNOULTU7B4VASXSXH56BUOAIPXAG", + "licences": 1, + "match": true + }, + { + "agent": "GDH5RSHSA6QHHJEFP5XNFMKCRGOEAFCJCH2ZETTTSECFMYD7TJGUMJ2M", + "licences": 1, + "match": true + }, + { + "agent": "GAFQ6QYS73QXCOGJSCSBR7HAQBUKNNCIE5JQINF6TH2TMF6N6OSI6TY5", + "licences": 1, + "match": true + } + ] + } +} \ No newline at end of file From a13e621c81d0573722e3d870b8f1acccbc2f2ccd Mon Sep 17 00:00:00 2001 From: lin1er Date: Thu, 17 Sep 2026 18:57:44 +0700 Subject: [PATCH 2/2] test(STE-46): one poll stores registry and licence events once each, and only registry events drop the /skills snapshot Rebasing onto STE-34 put both tickets' changes into the same poll loop. The first automatic resolution concatenated the two versions and stored registry rows twice; the events table's UNIQUE constraint made that harmless (INSERT OR IGNORE), so it was wasted work rather than wrong data, and this test cannot tell the two apart. The loop was merged by hand; the test pins the combined behaviour that does matter. --- api/tests/test_licenses_by_agent.py | 51 +++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/api/tests/test_licenses_by_agent.py b/api/tests/test_licenses_by_agent.py index 60f7986..d9edc31 100644 --- a/api/tests/test_licenses_by_agent.py +++ b/api/tests/test_licenses_by_agent.py @@ -241,3 +241,54 @@ def test_not_configured_is_503(self, client, tokens): assert r.status_code == 503 finally: object.__setattr__(settings, "tokens_contract_id", previous) + + +def test_one_poll_stores_registry_and_licence_events_once_each(client, monkeypatch, _isolated_db): + """STE-46 and STE-34 both changed the poll loop. Each event lands exactly once, a + registry event drops the /skills snapshot, and a licence event alone does not.""" + from sterish_api import indexer, registry_snapshot + + dropped = [] + monkeypatch.setattr(registry_snapshot, "invalidate", lambda: dropped.append(1)) + + class Server: + def __init__(self, url): + pass + + def get_health(self): + return type("H", (), {"oldest_ledger": 10})() + + def get_latest_ledger(self): + return type("L", (), {"sequence": 10})() + + registry_row = { + "event": "verdict_flipped", "skill_id": "com.acme.weather", "version": "1.0.0", + "content_hash": None, "verdict": "DANGEROUS", "trust_score": 5, "owner": None, + "auditor": None, "ledger": 10, "tx_hash": "e" * 64, "occurred_at": 1, + } + licence_row = {"_license": { + "tokens_contract_id": settings.tokens_contract_id, "agent": AGENT, + "skill_id": "com.acme.weather", "version": "2.0.0", "ledger": 10, + "tx_hash": "cd" * 32, "occurred_at": 1, + }} + decoded = iter([dict(registry_row), dict(licence_row)]) + monkeypatch.setattr(indexer, "SorobanServer", Server) + monkeypatch.setattr( + indexer, "_get_events", lambda server, start: type("R", (), {"events": [1, 2]})() + ) + monkeypatch.setattr(indexer, "_decode_event", lambda ev: next(decoded)) + + assert indexer.poll_once() == 2 + with sqlite3.connect(_isolated_db) as conn: + assert conn.execute("SELECT COUNT(*) FROM events").fetchone()[0] == 1 + assert conn.execute("SELECT COUNT(*) FROM license_events").fetchone()[0] == 1 + assert dropped == [1] + + # A poll that brings only a licence event must not drop the registry snapshot. + decoded = iter([dict(licence_row, _license=dict(licence_row["_license"], tx_hash="ab" * 32))]) + monkeypatch.setattr(indexer, "_decode_event", lambda ev: next(decoded)) + monkeypatch.setattr( + indexer, "_get_events", lambda server, start: type("R", (), {"events": [3]})() + ) + indexer.poll_once() + assert dropped == [1]