Implementation#

Repository map#

src/grantstamp/     client package `grantstamp` (Apache-2.0)
  fingerprint/      bundle.py (files, folders, zip/tar), cdc.py, strings.py, winnow.py, image.py,
                    sampling.py, background.py (+ background_*_v1.u64), filetypes.py
  site/             the website: home, check, stamps (search), security, pricing, status, docs/<version>/,
                    assets/ (CSS, fonts, JS); built by scripts/build_site.py
  cli.py  client.py  mcp_server.py  hook.py  crypto.py  httpsig.py  policy.py  tokens.py  claims.py
  manifest.py  markers.py  pow.py  util.py  brand.py
server/src/grantstamp_server/
                    registry package `grantstamp-server` (AGPL-3.0-only): app.py (FastAPI),
                    matching.py, store.py, db.py, net.py, ratelimit.py, pages.py, admin.py,
                    config.py, cli.py
tests/              75 tests: crypto, signatures, fingerprints, policies, tokens, server flow, claims and audit,
                    search, fair use, caller identity, the website,
                    JS/Python parity, hook, MCP, Postgres
bench/              run_bench.py + RESULTS.md (detection); load_bench.py + LOAD.md (speed and size)
examples/           demo.py (end-to-end story), toygame/ (sample C "game")
integrations/       Claude Code, Claude Desktop, Cursor, VS Code configs; agent instructions
scripts/            build_site.py (docs and shared page chrome), build_background.py, rebrand.py, announce.py
spec/               grantstamp-protocol-v0.1.md

Fingerprinting algorithms#

All feature hashes are first 8 bytes of SHA-256(domain || 0x00 || data), read as a big-endian unsigned 64-bit integer. The domains are protocol constants: dm/chunk/v1, dm/str/v1 and dm/win/v1.

Content-defined chunking (cdc.py): - Polynomial rolling hash over a 32-byte window: h_i = Σ_{j<32} T[b_{i-j}] · P^j mod 2^32. Here T[i] is the first 4 bytes of SHA-256("dm/buz/v1" || i) and P = 0x9E3779B1. - A boundary falls where the top 12 bits of h are zero. Chunks are 2 KiB to 64 KiB, about 6 KiB on average. - It is computed with numpy prefix sums: h_i = (S_i − S_{i−32}) · P^i, where S is the cumulative sum of T[b_k] · P^{−k}. Throughput is about 70 MB/s per core. - It is tested against a brute-force reference.

Strings (strings.py): 1. Take ASCII runs of 0x20–0x7E of at least 6 bytes. Non-text files also contribute UTF-16LE runs. 2. Inside runs that contain a quote, take every "..." literal, split it on backslash escapes, and keep the pieces. 3. Code files (by extension) contribute literal pieces only. 4. Normalise each feature: collapse whitespace, then keep it if its length is at least 6, it has at least 4 ASCII letters, and at least 60% of it is letters, digits or spaces. Truncate to 256 characters. 5. Split identifier-like features (^[A-Za-z_][A-Za-z0-9_.:$@]*$) into the symbols layer.

The browser checker (site/assets/grantstamp-check.js) implements exactly the same rules, and tests/test_js_parity.py proves it bit for bit.

Winnowing (winnow.py): tokenise; drop comments; replace string literals with "S", identifiers (except keywords) with "I" and numbers with "N". Hash every 12-token k-gram and keep the minimum of every 8-hash window.

dHash (image.py, needs Pillow): convert to greyscale, resize to 9×8, compare adjacent pixels to get 64 bits. Stored with four 16-bit bands for candidate lookup.

Markers (markers.py): GRANTSTAMP:1:stamp_<16 chars> in ASCII or UTF-16LE. grantstamp marker <stamp> --lang c|cpp|csharp|rust|... prints a snippet that keeps the notice in release builds (__attribute__((used)), /include: for MSVC, AssemblyMetadata for .NET, #[used] for Rust).

Sampling (sampling.py): when a layer has more features than a cap (262,144 when registering, 65,536 when checking), keep only hashes whose top s bits are zero, increasing s until the count fits. Two sampled sets stay comparable: filter both to the larger s.

Background (background.py): curated Windows/MSVC/runtime strings, plus every string and chunk seen in at least 5 (strings) or 3 (chunks) of 2,106 Linux system executables. This gives 66,758 string hashes and 375 chunk hashes, removed on both sides. Rebuild or extend it with scripts/build_background.py.

Excludes: grantstamp register skips common third-party runtimes (vcruntime, msvcp, steam_api, SDL2, libcef, UnityPlayer, ...) unless --no-default-excludes is passed.

Matching and bands (grantstamp_server/matching.py)#

For each (query file, registered file) pair, a layer's containment is max(hits / |query features|, hits / |registered features|), both measured at the larger sampling rate. Hashes held by three or more owners are ignored.

Layer high (hits, containment) medium low
chunks 4, 0.5 4, 0.2 8, 0.05
strings 20, 0.6 6, 0.3 10, 0.1
winnow 10, 0.5 6, 0.25 6, 0.1
symbols 60, 0.7 25, 0.45 20, 0.15
dhash Hamming distance ≤ 4 ≤ 10 none
exact same SHA-256 gives exact; a SHA-256 registered by two or more owners counts only as low

Per stamp: - the band is the best pair; - three or more query files at medium upgrade the stamp to high; - a marker or signed manifest naming the stamp makes it medium, or high if any other evidence agrees.

Results are ordered by band, then verified owners, then score, then earliest registration.

Policy is applied at medium and above. Medium turns deny into ask, so only high and exact can produce a hard deny. Anonymous callers do not see low matches or any scores. Registered agents see low matches and match counts. Trusted agents and the owner see full evidence and scores.

Security primitives#

HTTP API#

Method and path Auth Purpose
GET /.well-known/grantstamp none descriptor: version, signing keys, vocabularies, limits, endpoints
GET /.well-known/http-message-signatures-directory none registry JWKS (to verify receipts and webhooks)
POST /v1/check optional {bundle, use, purpose?, license_tokens?} → verdict, matches, receipt
GET /v1/range/{prefix5} optional exact-hash suffixes for a 5-hex-character prefix
POST /v1/owners signed by the new key {name, contact?, url?, jwk}
GET /v1/owners/{id} none public profile, verified domains, stamps
POST /v1/owners/{id}/domains owner {domain} → DNS and HTTPS challenge
POST /v1/owners/{id}/domains/{domain}/verify owner checks DNS TXT _grantstamp.<domain> or https://<domain>/.well-known/grantstamp-verify.txt
PUT /v1/owners/{id}/webhook owner {url, format: json\|slack\|discord}
GET /v1/alerts?since= owner alerts and per-stamp event summary
POST /v1/stamps owner {title, version?, kind?, description?, policy?, bundle, listed?, claim?} → stamp, conflicts, marker, notice, receipt
POST /v1/stamps/{id}/files owner append more files (the CLI splits large builds); {files, claim?}
PUT /v1/stamps/{id}/policy owner replace the policy; {policy, claim?}
PUT /v1/stamps/{id}/listing owner show the stamp in search or keep it out; {listed, claim?}
POST /v1/stamps/{id}/withdraw owner withdraw a stamp and delete its fingerprints; {claim?}
POST /v1/stamps/{id}/attest owner add an owner claim to a stamp registered without one; {claim}
GET /v1/stamps?q=&owner=&before=&limit= optional search listed stamps by title, version, kind or owner name
GET /v1/stamps/{id} · GET /s/{id} none public stamp as JSON or HTML
GET /v1/stamps/{id}/proof none owner claims, owner keys and DNS records, and the stamp's log entries
GET /s/{id}/qr.svg · qr.png · badge.svg none QR code for the stamp's page, and a badge
GET /v1/stamps/{id}/snippet?lang= none marker source snippet
POST /v1/tokens/verify · POST /v1/tokens/revoke none · owner licence tokens
POST /v1/agents signed by the new key register an agent key
POST /v1/disputes · GET /v1/disputes/{id} · GET /v1/disputes/new?stamp= none disputes (form included)
GET /v1/log · GET /v1/log/head none transparency log
GET /v1/pow · GET /v1/stats · GET /healthz none utilities
GET /v1/status none version, build commit, database health and size, log head (cached for 10 seconds)
GET /v1/whoami optional the caller's class and rate limit, as the registry sees it
GET /v1/docs none OpenAPI UI (it was at /docs in 0.1; /docs/ now serves this documentation)

The check response looks like this:

{
  "registry": "https://registry.grantstamp.io",
  "access": "anonymous",
  "verdict": {"band": "high", "decision": "deny", "stamp": "stamp_…", "guidance": "This content is very likely derived from …"},
  "matches": [{"band": "high", "stamp": {"id": "stamp_…", "title": "…", "page": "…/d/stamp_…"},
               "owner": {"name": "…", "verified": true, "verified_domains": ["…"]},
               "policy": {"default": "ask", "uses": {"port": "deny", "…": "…"}},
               "decision": {"action": "deny", "via": "policy", "use": "port", "contact": "…"}}],
  "receipt": "eyJhbGciOiJFZERTQSIs…"
}

Command-line reference#

Command What it does
grantstamp keygen [--role owner\|agent] create ~/.grantstamp/<role>.key
grantstamp owner create --name … [--url --contact] create the owner and save the id in ~/.grantstamp/config.json
grantstamp owner domain <domain> / verify <domain> domain challenge, then verification
grantstamp owner webhook <url> --format slack alerts to Slack, Discord or JSON
grantstamp register <path> --title … [--preset --policy --contact --manifest --exclude --unlisted] fingerprint locally, sign a claim and register a stamp; saves the receipt
grantstamp policy <stamp> --preset … · withdraw <stamp> manage stamps
grantstamp list <stamp> · unlist <stamp> show a stamp in search or keep it out
grantstamp search <words> [--owner] search listed stamps
grantstamp qr <stamp> [--out file.png] save the QR code for a stamp's page
grantstamp attest <stamp> sign a stamp that was registered with 0.1
grantstamp audit [<stamp> …] [--witness --no-dns --json] verify the log, the public witness and stamps; exits 1 on any problem
grantstamp alerts [--hours 24] matches, probing, conflicts, disputes
grantstamp token issue --stamp … --to … --uses port,modify [--days] · verify · revoke licence tokens
grantstamp marker <stamp> --lang cpp · manifest <stamp> --dir build/ embedded notice and signed sidecar
grantstamp check <path> --use port [--purpose --token --exit-code] check before working; exits 2 on deny and 3 on ask
grantstamp fingerprint <path> [--out bundle.json] local fingerprint, no network
grantstamp agent register --name … [--url] sign agent requests from now on
grantstamp log verify · show <id> · dispute <stamp> … auditing and public actions
grantstamp serve [--db --public-url --dev] · grantstamp mcp run the registry or the MCP server
grantstamp admin --db … verify-domain\|trust-agent\|stamp-status\|owner-status\|disputes\|resolve\|stats operator actions (logged)

Environment variables: GRANTSTAMP_REGISTRY, GRANTSTAMP_HOME, GRANTSTAMP_DB (or DATABASE_URL), GRANTSTAMP_PUBLIC_URL, GRANTSTAMP_REGISTRY_KEY, GRANTSTAMP_DEV, GRANTSTAMP_POW_BITS, GRANTSTAMP_LIMIT_ANONYMOUS (and the other LIMIT_* variables), GRANTSTAMP_IP_HEADER, GRANTSTAMP_PROXY_HOPS, GRANTSTAMP_QUOTA_STAMPS_UNVERIFIED, GRANTSTAMP_QUOTA_FEATURES_UNVERIFIED, GRANTSTAMP_QUOTA_STAMPS_VERIFIED, GRANTSTAMP_QUOTA_FEATURES_VERIFIED, GRANTSTAMP_QUOTA_FEATURES_UNVERIFIED_TOTAL, GRANTSTAMP_QUOTA_FEATURES_TOTAL, GRANTSTAMP_COMMIT, GRANTSTAMP_COMMON_OWNERS, GRANTSTAMP_OPEN_REGISTRATION, GRANTSTAMP_HOOK_FAIL_CLOSED.

MCP tools (grantstamp-mcp or grantstamp mcp)#

Claude Code hook (grantstamp-hook)#

The hook reads the PreToolUse JSON on stdin and watches Read, Edit, MultiEdit, Write and Bash calls. Bash commands are scanned for file arguments. A file is watched if it has a binary, game-archive or model extension, or if it is binary, and it is at least 512 bytes.

It infers the use: Read means analyze; Edit or Write means modify; a Bash command with objdump, r2, ghidra and similar tools means decompile, and with recompilers or wine means port.

It prints permissionDecision: deny|ask with the owner's guidance and stays silent otherwise. Results are cached per file hash for an hour. If the registry is unreachable the hook fails open, unless GRANTSTAMP_HOOK_FAIL_CLOSED=1 is set.

Tests and benchmark#

pytest                                   # 75 tests (the Postgres tests run if GRANTSTAMP_TEST_PG is set)
python examples/demo.py                  # end-to-end story in ~10 s
python bench/run_bench.py                # detection + cross-match + throughput → bench/RESULTS.md
python bench/load_bench.py --db postgresql://…   # speed and storage with 3,000 files → bench/LOAD.md

Benchmark summary (prototype scale; see bench/RESULTS.md): - Detection. Recompiled toy-game variants all matched high, and the exact copy matched exact. The variants covered gcc and clang at -O0, -O2, -O3, -Os and -O3 with LTO, plus stripped, 50 bytes flipped and half the strings rewritten. The ported folder matched exact (copied assets) and synthetic decompiler output matched high. - Cross-matches. 400 Linux executables were checked against 60 others registered under 60 owners, with 0 medium-or-higher matches across different Debian source packages. All 21 medium or high matches were within the same source package (real shared code). - Speed. About 20 MiB/s per core for all layers on random data, with parallel workers for large folders. With 3,000 real executables registered on PostgreSQL, a check round trip takes 15 ms at the median and 87 ms at the 95th percentile on a 2-CPU machine, and one server process answers about 58 checks a second (bench/LOAD.md). - Size. About 76 KB of database per registered executable (842 features at 92 bytes each, indexes included).

Source of this page on GitHub. Documentation for Grantstamp 0.2, licensed CC BY 4.0.