NFC β Cards, DBFS Switching & the Game Manifest System
Status legend used throughout this document
- π‘ DESIGNED β design settled, not yet implemented
- π VISION β future direction, depends on infrastructure not yet built
This document deliberately marks the maturity of each part. Much of the grander vision (downloading games, FPGA-core-loaded titles, signed commercial content) is π and gated on networking and the FPGA run-path existing. The card mechanics and dispatch model are π‘/β and real.
1. Overview
The Ant64 has a PN532 NFC reader/writer on Clicky's dedicated NFC SPI1 bus β separate from the housekeeping IΒ²C link over which DeMon exchanges commands and validated records with Clicky. The guiding idea is simple and powerful:
A card is a URL. The system is a browser for physical cards. Tap = navigate.
Every card holds nothing more than a short string β a URI. The leading
scheme (dbfs://, https://, β¦) tells the system what kind of card it
is and which handler should act on it. This makes cards a general-purpose
physical trigger mechanism: today they switch which user environment (DBFS)
is active and point at games; in future, anything addressable by a scheme.
Two flagship uses:
- User/environment switching β tap your card, the system switches to
your personal DBFS (your setup, your files). Type
Byeto return to the shared/main DBFS. (π‘ designed) - Games on cards β a card points at a game manifest; tap it and the system can identify, (eventually) download, and run the game β including games that run under a loaded FPGA personality core (e.g. the eZX Spectrum core). Games can effectively be sold on cards. (π vision)
Both are just scheme handlers over the same "card = URL" mechanism.
2. Hardware β
- Reader: PN532, selected for SPI mode on Clicky's dedicated SPI1 bus. The reader is selected by SPI chip-select; no PN532 IΒ²C address is used in this design.
- Wiring (Clicky):
- PA6 β RSTPDN (reset / power-down, active low, driven by Clicky)
- PA7 β IRQ (response-ready, active low, driven by the PN532)
- SPI1 master, ALT2: PB4 MOSI, PB5 MISO, PB6 SCK, PB7 SS. This is separate from Clicky's TWI0 slave link to DeMon; TWI1 remains the FireStorm side channel.
- Interface levels: translate MOSI/SCK/SS/reset from Clicky's 5 V domain to the PN532's 3.3 V interface, and MISO/IRQ back to 5 V, following Clicky's translator specification.
- Split across chips, at a high abstraction. Clicky owns the whole low-level NFC stack in firmware β the PN532 command/response protocol, card-type handling (MIFARE, NTAG21x, ISO14443Aβ¦), NDEF parsing, URI extraction, validation and anti-repeat β and hands DeMon a clean, validated card record over IΒ²C (
{ type, uid, uri }). Only good data crosses; DeMon never sees raw card bytes or card-type quirks. DeMon keeps the high-level model below β scheme dispatch, DBFS switching, the game manifest, the Luau API β now fed by Clicky's records. Writes are high-level too: DeMon says "write this URI" and Clicky does the NDEF encoding + PN532 write for the card's type. So the sections below that describe PN532 frames, card types and NDEF are Clicky-firmware concerns; DeMon'snfclibrary is a thin receive-record-and-dispatch layer. - The PN532 is a command/response device (NXP UM0701-02 information frames), not a register chip. Over I2C, each read is preceded by a status byte (bit0: 1=ready); the IRQ line signals response-ready so the host needn't busy-poll.
Driver (sys_nfc.c/.h) β
Now Clicky firmware. With the PN532 on Clicky's bus, this low-level driver β and the card-type / NDEF handling β lives in Clicky's firmware; DeMon receives a validated card record over IΒ²C. The behaviour below is unchanged β only its host chip is.
- Hard-reset pulse on RSTPDN at init.
GetFirmwareVersionhandshake (logs e.g.IC=0x32 ver=1.6).SAMConfigurationwith IRQ mode enabled.InListPassiveTargetβ detect an ISO14443A card, return UID (4/7/10 bytes), SAK, ATQA.- Frame builder verified byte-for-byte against the canonical GetFirmwareVersion frame before first flash.
Luau library (lib_nfc.cpp, nfc.lua) β
- Require-only:
local nfc = require("nfc"). nfc.ready()β boolnfc.version()β e.g."PN532 v1.6"nfc.read([timeout_ms])β{ uid=hexstr, type=str, uri=str, β¦ }or nil β the validated record Clicky relays over IΒ²C (raw card fields likesak/atqastay on Clicky).nfc.luademo:nfc(read once),nfc scan,nfc info.
Card types β verified May 30 2026
- Reading works for all ISO14443A cards (MIFARE Classic, NTAG/Ultralight,
DESFire, β¦); SAK byte is the primary type discriminator, with
GET_VERSIONused on SAK 0x00 cards to distinguish NTAG213/215/216 from older MIFARE Ultralight. - Both writable on hardware (Chapter 5A verified):
- NTAG213/215/216 β no auth, NDEF-friendly, phone-readable. The primary target.
- MIFARE Classic 1K β auth with factory default key
FFΓ6works on blank/preformatted cards. Raw URI storage (not NDEF, since iPhones don't read Classic anyway). MUST NEVER write sector trailers (blocks 7, 11, 15, β¦) β wrong values brick the sector permanently. Driver guards this unconditionally.
PN532 quirk worth knowing: InDataExchange vs InCommunicateThru
Captured here because we learned it the hard way and shouldn't re-learn it.
The PN532 has two commands for talking to an activated target:
InDataExchange(opcode 0x40): assumes NFC-Forum-standard tag commands. PN532 silently refuses to forward non-Forum opcodes β the call returns immediately with no payload. Correct for: NTAGREAD(0x30), NTAGWRITE(0xA2), MIFARE auth/read/write (0x60/0x30/0xA0).InCommunicateThru(opcode 0x42): raw passthrough (PN532 still handles CRC, but doesn't second-guess the opcode). Correct for any NTAG-extended command not in the NFC Forum spec:GET_VERSION(0x60 in this context),FAST_READ(0x3A),PWD_AUTH(0x1B),SECTOR_SELECTβ and presumably future NTAG features.
The symptom of using InDataExchange where InCommunicateThru is needed is
a clean n=-1 return with no parseable response β not a tag NACK with
a status byte. Different failure mode means different debug path; knowing
this saves real time.
Driver convention: NFC-Forum opcodes go through nfc_in_data_exchange,
extended opcodes through nfc_in_communicate_thru. The two are otherwise
structurally identical.
3. The card payload: a URI string
A card holds one short UTF-8 string: a URI with a scheme prefix. That's all. Everything else (game metadata, platform builds, DBFS contents) lives elsewhere β the card is only ever a pointer or a short command.
Examples:
dbfs://dave switch to Dave's personal DBFS
https://games.ant64.com/manic.json a game manifest URL
ftp://files.ant64.com/games/elite.json a game manifest via FTP
Because the card only holds a string:
- It fits on the smallest tag.
- It never needs rewriting when a game updates (the manifest changes; the card's URL is stable).
- Writing a card is always the same trivial operation regardless of payload.
Dispatch-time parameters: uid and aid π‘
Although the card stores only its URI, the dispatcher can append identifiers as query parameters when it acts on a scheme β information it already holds at tap time, so this costs nothing extra:
-
uidβ the card's serial.nfc.read()already returns the tag UID on every read (Β§2); for the writable NTAG family it is a 7-byte, factory-locked, globally unique value. -
aidβ the Ant64's machine ID: a 48-bit structured value (it decodes to manufacturing provenance) provisioned into DeMon's ATECC608C secure element at first-test and locked β immutable once its data zone is locked, a hard machine identity. It is stored as a 64-bitaid64(the 48-bitaidplus a 16-bit CRC-16 integrity wrapper); the URI parameter and licensing always use the 48-bitaid, never the 64-bit value. See DeMon for the full bit layout, the pinned CRC variant, and the optional HMAC attestation.- Uniqueness key is (batch, serial) β collision-free provided the manufacturing jig never reissues a serial within a batch (monotonic counter; resets only on a deliberate new batch). A process guarantee. The timestamp is provenance, not part of the key, and decodes to "first tested at hour H, batch B, unit N" β useful for support, warranty, and recall scoping.
- Provenance leaks if broadcast raw. A structured
aidin a clear query string tells a server the unit's test-hour and batch. For transmission, send a per-server salted hash of theaid(a server still recognises a returning box but can't read its production calendar or correlate it across services), or the hardware HMAC attestation (DeMon's ATECC608C) for genuine machine-side anti-clone; keep the raw structured value for local / support decode only.aidis identity-grade, not a secret β write-protected but readable on the bus and on the wire (only the optional HMAC secret is unreadable by construction).
So a stored manifest URL dispatches with the identifiers attached:
stored on card: https://games.ant64.com/manic.json
dispatched as: https://games.ant64.com/manic.json?uid=04A1B2C3D4E5F6&aid=0004A3E1A2C3
The dispatcher handles ? vs & (appending if the stored URL already carries a
query string) and URL-encodes. Whether identifiers are appended is a per-scheme
setting (Β§4) β off by default, enabled only where the destination is trusted and
the use case (registration, licensing, telemetry) calls for it.
A card may optionally also store a short one-time registration token after
its URL β see ownership registration (Β§7). That token is the only per-card data
beyond the URL; uid and aid are always supplied live at dispatch, never written
to the card.
4. URI scheme dispatch π‘
The heart of the system is a small dispatch table keyed on the URI scheme. Reading a card β parse the scheme β invoke the registered handler. This is deliberately a table, not hardcoded branches, so new card types are just new handlers.
| Scheme | Handler | Action | Status |
|---|---|---|---|
dbfs://<name> |
DBFS switch | Switch active DBFS to <name> |
π‘ |
https://β¦ |
Game manifest | Fetch & act on the manifest at the URL | π |
ftp://β¦ |
Game manifest | As above, via FTP | π |
| (future) | β | cmd://, script://, wifi://, β¦ |
π |
Design principle: the dispatch layer is small and buildable now. The
dbfs:// handler is real (ties into Β§6). The https:///ftp:// handler can
start as a stub that simply recognises and displays the manifest URL,
then grow into the full fetch/run pipeline (Β§7) when networking exists.
Background dispatch & the confirm model π‘
NFC reading runs autonomously in a background task β tap a card anytime, no need to run a script first. The confirmed model:
- Clicky owns the PN532 and polls for cards, raising KINT so DeMon reads validated card records over Clicky's IΒ²C slave interface, where the background dispatch task runs the card model (hybrid arbitration, "Option C": scripts can later claim exclusive access for write/raw ops β see Β§5 β which suspends the dispatcher; arrives with the write chapter).
- Card detected β buzzer chirp (audible "card seen") β event enqueued. Clicky owns both the NFC reader and the buzzer, so the chirp is local to Clicky; the card event is relayed to DeMon.
- Events are handled strictly in sequence β one card fully resolved (confirm β act, or skip) before the next is even processed. A second tap while the first is mid-action does NOT race; it queues. This matters because the big actions (DBFS switch) cause a warm restart, and two restarts racing would be undefined. Single-consumer work queue, not concurrent.
- Default action on a tap = confirm prompt: space confirms the action, any other key skips it. This guards against a tap silently triggering a warm restart (a big action) without the user's say-so.
- Per-scheme settings override: each scheme/card-type can be configured to
always-confirm, never-confirm (act immediately, no prompt), or the
default confirm-on-tap. e.g.
dbfs://(causes a restart) might stay "confirm", while lower-stakeshttps://game cards could be "never-confirm". The safe default is confirm; settings relax it per scheme where trusted. - Per-scheme identifier append: independently of the confirm policy, each scheme
can be set to append
uid/aidquery parameters (Β§3) when it dispatches β off by default. Enabled forhttps://game manifests where registration/licensing wants them; left off for anything that shouldn't see the card or machine identity. Confirm-policy and identifier-append are separate switches: a scheme can be never-confirm yet still append IDs, or confirm yet append nothing.
5. NFC write (provisioning cards) π‘
To make a card, write its URI to the tag. PN532 Level-2 operation
(InDataExchange + tag-side write commands). Designed as two chapters:
- Chapter 5A β write/read with no metadata. Lands first. Working cards.
- Chapter 5B β adds the AntOS metadata wrapper (write count, timestamps, previous URI for revert). Layered cleanly on top of 5A.
5.1 Supported tag types β both, transparently
The user-facing API is the same regardless of card type:
nfc.write(uri) -- writes to whatever card is presented
nfc.read() -- returns whatever is on the card
nfc.info() -- pure-inspection: read everything we can determine
Internally nfc.write / nfc.read dispatch on the SAK byte (already in
sys_nfc_target_t):
| SAK | Tag family | Format on card | Notes |
|---|---|---|---|
0x00 |
NTAG21x (any size) | NDEF (NFC Forum Type 2) | NTAG213/215/216 all dispatch the same |
0x08 |
MIFARE Classic 1K | Raw length-prefixed URI from block 4 | Auth with factory default key FFΓ6 |
| other | unknown | refused with clean error |
nfc.write returns true on success, nil + err on failure (wrong tag
type, locked, auth failure, URI too long, etc).
5.2 Storage layouts
NTAG21x (NDEF):
- Start at page 4, NDEF TLV
0x03 <len>then a URI record using NFC Forum prefix-byte encoding for common schemes (https://β 0x04,http://www.β 0x01, etc). Custom schemes likedbfs://use prefix 0x00 followed by the full literal. - Terminate the NDEF message with
0xFE. - After the terminator: AntOS metadata block (see Β§5.4) β phones and standard
NDEF parsers stop at
0xFEand ignore everything after, so the metadata is invisible to them.
MIFARE Classic 1K (raw):
- No NDEF (Apple doesn't read Classic anyway, so phone-interop is forfeit).
- Block 4 byte 0 = URI length. Bytes 1+ continue the URI into subsequent blocks.
- Skip every 4th block (block 7, 11, 15, ...) β these are sector trailers holding keys + access bits. Writing them with wrong values can permanently lock a sector. The C code MUST treat this as an assert, not a guideline.
- AntOS metadata block (Β§5.4) follows the URI in the next available non-trailer blocks.
5.3 Capacity matrix
| Tag | User memory | NDEF overhead | Typical URI (40 bytes) leaves |
|---|---|---|---|
| NTAG213 | 144 bytes | ~10 bytes | ~90 bytes for metadata |
| NTAG215 | 504 bytes | ~10 bytes | ~450 bytes for metadata |
| NTAG216 | 888 bytes | ~10 bytes | ~835 bytes for metadata |
| Classic 1K | ~752 bytes | 0 | ~710 bytes for metadata |
(NTAG216 = the production card type β 30 ordered for testing May 29.)
For typical AntOS URIs (12-50 bytes) all tag sizes have ample room. NTAG213 is the only tag where long URIs (>80 bytes) might force dropping the previous-URI field (see tier logic in Β§5.4).
5.4 AntOS metadata block (Chapter 5B)
Lives after the NDEF terminator (NTAG) or after the URI bytes (Classic).
Lets us track card history and support revert.
On-card layout (LE = little-endian, matching the CM5 ARM host):
Offset Size Field
0 4 Magic "A64C" (0x41 0x36 0x34 0x43)
4 1 Version byte: vvvvUttt
vvvv = format version (0x1 = v1)
U = clock-uninitialised flag (timestamps unreliable)
ttt = tier (0 = URI only, 1 = no prev, 2 = full)
5 2 Game ID (LE uint16, 0 = system card / no game)
7 2 Write count (LE uint16, saturates at 0xFFFF)
9 4 First-written timestamp (LE uint32 Unix epoch, 0 if unknown)
13 4 Last-written timestamp (LE uint32 Unix epoch)
[tier β₯ 2 only:]
17 1 Previous URI length (0..200)
18 N Previous URI bytes (UTF-8)
17 bytes minimum (tier 0/1), 18+N with previous URI (tier 2).
Game ID notes:
- 16 bits, opaque to AntOS β passed through unchanged to the publisher's server.
- Namespace is per-URI (publisher-private). Two cards with the same URI but different game_ids are different products in the same publisher's catalog (e.g. game_id 4 = "Manic Miner Original", game_id 5 = "Manic Miner Enhanced Edition"). game_id 4 at one URI has nothing to do with game_id 4 at a different URI β they're in different namespaces.
- No central registry. Publishers use 1β65535 however they want inside their own catalog. game_id 0 is reserved for "no game" (system cards like
dbfs://user-switch cards). - See Β§7 for the manifest-fetch protocol that consumes this field.
5.5 Tier selection at write time
Compute remaining = capacity - ndef_overhead - encoded_uri_size. Then:
| Tier | Condition | What's written |
|---|---|---|
| 2 | remaining β₯ 17 + 1 + len(previous_uri) | URI + full metadata + previous URI |
| 1 | remaining β₯ 17 | URI + metadata (no previous) |
| 0 | remaining β₯ 0 | URI only (no AntOS metadata) |
| β | remaining < 0 | refuse β URI doesn't fit |
"Drop what doesn't fit, in priority order: previous URI first, then metadata block, then refuse." The tier is encoded in the version byte so reads always know what to expect.
5.6 What counts as "previous URI"
Read-modify-write logic: read current card content, decide what (if anything) to save as previous.
- If existing content parses as a known AntOS scheme (
dbfs://,https://,ftp://, etc.) β save as previous URI - If existing content is anything else (blank, foreign NDEF, garbage) β no previous stored (revert won't be available next time)
Revert is an AntOS feature; reverting to non-AntOS content makes no sense in the family-card use case.
5.7 RTC reliability
Looking at the boot log, the RTC reports values but flags itself
UNINITIALISED until set with rtc.set(). Timestamps written when the clock
is uninitialised are some date but not necessarily the right date.
Approach: write the timestamp regardless, set the clock_uninitialised
flag in the version byte. Some date info beats none, and the flag is
honest about provenance. Once RTC is set authoritatively (e.g. NTP), the
next write to the card stores a clean timestamp and clears the flag.
5.8 nfc.info() β pure inspection
Returns a rich table with everything we can determine, regardless of tag
type. Distinct from nfc.read() (which is "give me the URI"); nfc.info()
is "tell me everything about this card."
{
uri = "dbfs://anthony", -- or nil if blank/no AntOS data
tag_type = "NTAG216", -- "MIFARE Classic 1K", "NTAG213", etc.
uid = "F2302E03", -- 4 or 7-byte UID, hex-stringified
capacity = 888, -- user bytes
bytes_used = 47, -- consumed by URI + NDEF + metadata
bytes_free = 841,
format = "ndef", -- or "raw" for Classic
writable = true, -- accepts writes (auth/lock checked)
meta = { -- nil for cards without our magic
tier = 2,
version = 1,
game_id = 4, -- 0 = no game (system card)
write_count = 3,
first_written = 1735689600, -- Unix epoch, 0 if unknown
last_written = 1748568849,
clock_reliable = true, -- false if RTC was uninit at write
previous_uri = "dbfs://sarah", -- nil if tier < 2 or no prev saved
}
}
5.9 Provisioning UX β provision.lua
The user-facing script. Reads card first, decides whether to confirm, then writes:
provision dbfs anthony
Three-tier confirm logic:
| Card state | Confirm prompt |
|---|---|
| Blank | (none β write silently) |
| Has known AntOS URI | "overwrite existing dbfs://X with dbfs://Y? (y/n)" |
| Has unknown data | "card has non-AntOS data β overwrite? (y/n)" |
Latency cost: read-before-write doubles the time per provision (~50ms extra for NTAG, ~200ms for Classic β both feel instant in practice). Worth it for the UX benefit.
Always read-back-verify after writing; if verify mismatches, report error.
For Classic cards specifically, provision.lua adds an honest heads-up
note: "wrote to MIFARE Classic β not readable by iPhones; consider NTAG
for phone-tappable cards." The C API doesn't moralise; the script does.
5.10 revert.lua β undo last write
Reads card's metadata block, takes the previous_uri field, writes it back
as the new active URI. (Also bumps write_count and swaps current/previous,
so reverting again would go back to whatever you just overwrote.)
If no previous URI is on the card (tier < 2 or never had one):
"no previous URI stored on this card β cannot revert. If you remember the previous one, use
provision dbfs <name>to set it manually."
Honest about the limit, gives a path forward.
5.11 card.lua β show full info
Trivial script wrapping nfc.info() β taps a card and prints everything
formatted nicely. Diagnostic tool, the "what is this card?" gesture.
5.12 Dispatcher Level-2 read integration
The existing dispatcher uses UID-stub fallback (uid://F2302E03) for tags
it can't read content from. With Level-2 read in place:
- Tag enters field β dispatcher reads via
nfc.read() - If read succeeds and parses to a known scheme β dispatch on URI
- If read fails (locked / blank / unparseable) β fall back to
uid://dispatch (today's behaviour)
So dbfs:// cards work via URI dispatch; bare/locked cards still get the
UID path. Clean degradation.
6. User DBFS switching π‘ (design complete; implementation pending)
Concept
The Ant64 normally runs against a shared/main DBFS (the role='MAIN'
drive β the family's common environment). A personal card switches the system
into that user's own DBFS β their setup, their files, their games β and
typing Bye returns to the shared main DBFS.
- Default / home: shared main DBFS (
sys.db). - Tap personal card (
dbfs://dave): switch into Dave's DBFS (dave.db). - Type
Bye: return to main. - Unknown / unwritten card: "user not found", stay put.
Topology is a star, not a mesh: you always go personal β main β personal. Main is the hub and the always-valid fallback. This keeps the switching logic simple and safe β if anything is ever wrong or lost, you fall back to main.
Mechanism: restart-with-override β
DBFS (D:) is the live, mounted, SQLite-backed filesystem the whole OS runs
against (open connection, shadow backup, running scripts, D:/scripts/,
working directory). Hot-swapping it under a running system invites
corruption, so the switch is done cleanly across an AntOS restart β on
the CM5 that's just Linux closing the AntOS executable and relaunching
it (a supervised process restart, sub-second), not a full reboot. The
exiting process closes the SQLite connection cleanly; the fresh one mounts
the new DBFS.
The contract is a restart preserves the override (switches DBFS); a reboot or power loss loses it (returns to family main) β the override is session state, not persistent state.
- Record the target DBFS name in a tmpfs override file (e.g.
/run/antos/dbfs_override) β RAM-backed, so it survives an AntOS restart while Linux keeps running, and is gone after a reboot or power cycle. - Exit the AntOS process cleanly; the supervisor (a
systemdservice withRestart=always, or the launcher loop) relaunches it. - On startup,
sys_os_dbfs_override_init()reads the tmpfs file:- present (a warm AntOS restart) β honour the override
- absent (a fresh boot cleared tmpfs, or
Byedeleted it) β boot intosys.db
- At mount time AntOS composes the DBFS path (
<DBFS root>/<name>.dbor.../sys.db).
This gives the exact behaviour: a restart switches DBFS; a reboot returns
to main. A tmpfs file is the natural Linux "survives software reset but
not power loss" store β the CM5 counterpart to the ESP32-P4's
RTC_NOINIT_ATTR, which the original build used and hardware-verified on 29
May 2026. Because the switch is a process restart rather than a reboot it is
also far quicker than the P4's cycle, and the clean process exit makes a
live remount largely unnecessary.
OS-level API β
Implemented in sys_os.c/.h:
void sys_os_dbfs_override_init(void); // called at app_main top
const char* sys_os_dbfs_target(void); // "sys" if no override
void sys_os_active_dbfs(char *buf, size_t); // current active DBFS name
sys_os_err_t sys_os_switch_dbfs(const char *name); // validates, sets, restarts
sys_os_switch_dbfs(name):
- Validates the name (alphanumeric + underscore only β rejects path
traversal attempts like
../sysorfoo/bar) - Confirms
<bMainRoot>/DBFS/<name>.dbexists on the current D: stick (using rawfopenprobe βsys_fs_existsis a drive-letter abstraction that doesn't accept raw VFS paths; this was a real bug caught during build) - Writes the override to the tmpfs file
- Exits the AntOS process (the supervisor relaunches it) β does not return
Special cases:
name == "sys"/""/NULLβ clear the override (= return to main)- file doesn't exist β
SYS_OS_ERR_NOT_FOUND, stays on current DBFS - D: not mounted β
SYS_OS_ERR_IO, stays on current DBFS
Luau bindings β
os.switch_dbfs(name) -- triggers the switch (does not return on success)
os.active_dbfs() -- returns current DBFS name, e.g. "sys" or "anthony"
os.list_dbfs() -- returns array of available .db files in D:/DBFS/
Scripts β
dbfs.luaβdbfs(no args, list),dbfs <name>(switch),dbfs sys(return to main),dbfs ?(help)bye.luaβ callsos.switch_dbfs("sys")
Triggers β all just callers of the one OS function β
- Tap a
dbfs://card β dispatcher'shandler_dbfscallssys_os_switch_dbfs(name) dbfs <name>console command βdbfs.luacallsos.switch_dbfs(name)byeβbye.luacallsos.switch_dbfs("sys")- Any script β can call the binding directly
One operation, three triggers, identical behaviour.
Hardware-verified β
Three round-trips in one session (May 29):
- Cold boot β sys.db
dbfs anthonyβ restart β boots to anthony.db,mkdir anthony_testbyeβ restart β boots to sys.db,anthony_testabsent (different filesystem)dbfs anthonyβ restart β boots to anthony.db,anthony_testpresent (persisted in anthony.db across switches)
The "warm restart preserves override / cold boot clears it" property was
verified by observing the post-restart log line:
AntOS restart β DBFS override = 'anthony' (warm path) vs
fresh boot β no override, DBFS = sys (cold path).
Honest caveats / known limitations
- A process restart per switch. A supervised AntOS relaunch β sub-second, far quicker than the P4's full-chip reset. A live remount (no restart at all) remains a possible future refinement but is much less pressing now β see roadmap.md.
- Shadow re-pairing. When a switch changes the active DBFS, the shadow backup must re-pair with the new file β part of the DBFS shadow-backup design.
- NFC
dbfs://card-tap path not yet exercised on hardware β mechanically identical to the console path (calls the same C function), but unverified. Lands trivially when NFC write produces the first card.
7. The Game Manifest System π
This is the grand vision: games sold on cards. It is not built and depends on infrastructure that mostly doesn't exist yet (networking, the FPGA core-loading run-path, a download/install pipeline). What is settled is the design shape β especially the manifest as a platform-aware manifest, and the cardβmanifestβbinary indirection.
The indirection: card β manifest β binary
- The card holds only the manifest URL (Β§3). Nothing about the game itself is on the card.
- The manifest (a small file at that URL) describes the game: identity, version, and β crucially β a list of platform-specific builds, each naming the FPGA core it needs (if any) and the location of its binary.
- The binary is the actual game content, fetched per the chosen build.
Three hops, each independently updatable. The card never changes; the manifest is the living source of truth; binaries can move.
Why platform-aware: games run under personality cores
An Ant64 game isn't necessarily a single artifact. A title might offer:
- a build that runs under the eZX Spectrum FPGA core (load that bitstream, then run the Spectrum game image under it),
- a build for the Agon Light core,
- a native build (Luau/FireStorm), etc.
This ties directly into the personality cartridge system: the
cores a game can target are the same
cores that system defines. The manifest's requires_core values MUST use
the exact core IDs from the personality-cartridge system β games
and cores must share one vocabulary.
The system knows which cores the user has available, offers the compatible build(s), the user picks, and the launcher: (1) ensures the required core is loaded (possibly loading the FPGA bitstream), then (2) hands the game binary to that core and runs it.
Manifest fetch protocol (settled May 29 2026) π‘
The card's URI is the manifest endpoint. AntOS appends parameters and makes one GET request β there's no separate license-check endpoint. The server's response IS the manifest (or a refusal).
URL composed by AntOS:
<card_uri>?card=<card_uid>&game=<game_id>&v=<cached_version>[&mid=<value>][&aid=<hashed>]
| Param | Sent | Purpose | Privacy |
|---|---|---|---|
card |
always | License verification β server checks if this card is licensed for this game_id | Not private β anyone with an NFC reader can read a card's UID |
game |
always | Identifies which product manifest to return | Not private β product identifier |
v |
always | Cached manifest version, if any. Server can return 304 Not Modified |
Not meaningful |
mid |
default-on, opt-out | Stable random per-machine value (see Β§7.x below) for publisher-side correlation | Not factory-linkable; doesn't leak production data |
aid |
opt-in | Per-server salted hash of the structured factory ID. Server analytics + anti-cloning detection | Private β opt-in by user (see Β§3) |
Server logic (one round-trip):
The publisher's server holds a "sold cards" database mapping
(card_uid, game_id) β license info. When AntOS fetches:
- Server looks up
(card_uid, game_id)in its sold-cards database. - Match β return the full manifest (with
binary_url,version,refresh_after_seconds,allow_outdated, signature, etc.). - No match β return a refusal stub (e.g.
{ "error": "unlicensed card", "allow_run": false }with HTTP 403). - Match but suspicious (
aidpattern shows the same card_uid being tapped from many distinct Ant64s in a way that suggests cloning) β publisher policy: refuse, warn, throttle, ignore.
The license check happens at the fetch boundary. Once a manifest is returned, AntOS caches it (see below) and uses it until it goes stale. Between fetches, the cached manifest is authoritative.
Local manifest cache (in DBFS) π‘
AntOS keeps a manifest cache in the DBFS, keyed by (uri, game_id).
Card UID is not in the key β the cache is a product catalog, not a
purchase history.
This is the structural separation:
- Server side (license enforcement): lookup is
(card_uid, game_id)β "is this specific card licensed for this product?" - Client side (product catalog): lookup is
(uri, game_id)β "do we already have the manifest for this product?"
These two keyings do different jobs. Server enforces who can buy; client caches what was bought. Conflating them would mean the cache fragments unnecessarily (each family member's card would create a separate cache entry for the same game) and would tempt AntOS into enforcing licensing locally (which is wrong β the server is the authority).
Family sharing falls out naturally: the first family member to tap a
card and successfully fetch a manifest caches it for everyone. Later, a
different card with the same (uri, game_id) (e.g. a second-hand copy)
hits the same cache entry. No duplication, no re-verification needed
locally β the publisher's server already approved this product.
What gets cached:
- Successful manifests are cached for
refresh_after_secondsfrom the manifest itself. - Refusals are not cached. A clone card returning a refusal must not block a legitimate card tapped immediately afterwards. Failures are network-cheap and rare.
- The cache is in the DBFS, so it follows the active personal DBFS. Switching DBFS gives that user their own cache view (sensible β Anthony and Sarah might have different game collections).
Refresh state machine:
| Cache state | Network | Behaviour |
|---|---|---|
| Fresh manifest cached | online | Use cached. No fetch. |
| Fresh manifest cached | offline | Use cached. |
| Stale manifest cached | online | Fetch; on success cache+use; on failure use stale + warn. |
| Stale manifest cached | offline | Use stale + warn. |
| No manifest cached | online | Fetch. Cache on success; refuse to run on refusal. |
| No manifest cached | offline | Refuse β "card unknown, need network for first use." |
Outdated handling (when fetched manifest reports a newer version than the locally cached binary):
- If manifest has
allow_outdated: trueβ run the cached binary anyway (single-player games, safe-to-be-stale). - If manifest has
allow_outdated: falseβ must download the new binary first, else refuse to run (multiplayer-compat-sensitive games).
allow_outdated is publisher policy. AntOS just obeys.
mid β per-machine correlation ID (outline; full spec TBD when built) π‘
A 32-bit random value generated on first boot ever of each Ant64,
stored in the MCP79410 RTC's protected EEPROM (the 8-byte upper region
intended by NXP for permanent identifiers). Once set, mid survives:
- All software events (resets, factory-resets of the DBFS, etc.)
- All power cycles
- Battery replacement (EEPROM is non-volatile; doesn't depend on the CR2450 backup cell β that's only for the RTC's timekeeping registers)
mid is only lost on deliberate hardware-level reset of the RTC's
protected region (which AntOS exposes as a factory-reset-the-machine
gesture, not anything routine).
Crucial framing: mid is not an AntOS-internal identity. AntOS
doesn't:
- Bind
midto any account or entitlement - Use
midas a key into any local table - Display
midto the user as "your machine ID" - Let
midgate any AntOS functionality
Its only role is to be sent in URL query parameters to publisher servers, where publishers can correlate against it however they like.
Example publisher use β anti-clone detection: the publisher's server
logs (card_uid, mid) pairs on every tap. A given card legitimately taps
from the same mid repeatedly (its owner's Ant64). If the same card_uid
later appears with a different mid, that's a clone signal β the card
data was copied but the new machine has its own mid because mid is
generated locally and never on the card. The publisher then decides
policy (revoke, throttle, warn, ignore).
This works even when aid is suppressed (privacy maxed), because mid
itself is the discriminator.
Privacy framing: mid is more privacy-friendly than aid because:
midis just a random number β it doesn't leak production calendar, batch, or serial information (which the structuredaiddoes)midis per-machine but per-server (servers can correlate within their own logs but can't trivially cross-correlate across publishers without colluding)
The privacy ladder for machine-level signals therefore becomes:
| Privacy setting | What's sent for machine identity |
|---|---|
| Strict | Neither mid nor aid β pure card-tap, no machine signal |
| Default | mid only β opaque, stable, useful for anti-clone but not for tracking |
| Permissive | mid + aid β full machine analytics for publishers who want it |
EEPROM layout (8 bytes of MCP79410 protected region):
Offset Size Field
0 4 Magic word "AID2" (identifies a written mid vs blank EEPROM)
4 4 mid (LE uint32)
If the magic isn't found at first boot, AntOS generates a fresh random
mid (from the hardware RNG β the ATECC608C TRNG / getrandom()), unlocks the protected
EEPROM, writes magic + value, relocks. Subsequent boots just read the
value.
Implementation note: needs to land BEFORE the manifest-system chapter.
By the time the manifest fetch is wired up, mid must already be
populated on every Ant64 so URL params include it from the first tap.
Small dedicated chapter β ~50 lines C plus the MCP79410
unlock-write-relock bus sequence (per the datasheet, specific timing
requirements). See roadmap.md.
Reference server implementation (PHP, ~40 lines) π‘
Concrete sample of what a publisher's manifest endpoint might look like. Demonstrates the lookup + response model. Publishers are free to use any language / framework / database β this is just the simplest thing that works.
<?php
// m.php β minimal Ant64 manifest endpoint
//
// Receives: ?card=<hex>&game=<dec>&v=<dec>[&mid=<hex>][&aid=<hex>]
// Returns: JSON manifest, or a refusal stub.
//
// Publishers use the 16-bit game_id however they like within their own
// catalog β e.g. game_id 4 = "Manic Miner Standard", 5 = "Manic Miner
// Enhanced". No central registry; namespace is per-URI.
header('Content-Type: application/json');
$card = $_GET['card'] ?? '';
$game = (int)($_GET['game'] ?? 0);
$v = (int)($_GET['v'] ?? 0);
$mid = $_GET['mid'] ?? null; // optional, default-on but suppressible
$aid = $_GET['aid'] ?? null; // optional, opt-in only
// Validate inputs (real implementations: sanitise harder)
if (!preg_match('/^[0-9A-Fa-f]{8,14}$/', $card) || $game < 1) {
http_response_code(400);
echo json_encode(['error' => 'bad request']);
exit;
}
// Look up (card_uid, game_id) in sold-cards database.
// Trivial SQLite example β real publishers will have richer schemas.
$db = new SQLite3('/var/ant64/sold.db');
$st = $db->prepare(
'SELECT manifest_json FROM sold WHERE card_uid = :c AND game_id = :g'
);
$st->bindValue(':c', strtoupper($card), SQLITE3_TEXT);
$st->bindValue(':g', $game, SQLITE3_INTEGER);
$row = $st->execute()->fetchArray(SQLITE3_ASSOC);
if (!$row) {
http_response_code(403);
echo json_encode([
'error' => 'unlicensed card',
'allow_run' => false,
]);
exit;
}
// Optional: log (card, mid, aid, timestamp) for anti-clone pattern detection.
// The key anti-clone signal is when the SAME card_uid appears with
// DIFFERENT mids over time β a clone has its own machine, hence its own mid.
if ($mid !== null) {
$log = $db->prepare(
'INSERT INTO taps (card_uid, game_id, mid, aid, ts)
VALUES (:c, :g, :m, :a, :t)'
);
$log->bindValue(':c', strtoupper($card), SQLITE3_TEXT);
$log->bindValue(':g', $game, SQLITE3_INTEGER);
$log->bindValue(':m', $mid, SQLITE3_TEXT);
$log->bindValue(':a', $aid ?? '', SQLITE3_TEXT);
$log->bindValue(':t', time(), SQLITE3_INTEGER);
$log->execute();
// Example clone detection (synchronous for illustration; production
// would do this in a background job):
// SELECT COUNT(DISTINCT mid) FROM taps
// WHERE card_uid = :c AND ts > strftime('%s','now','-7 days');
// If the count exceeds N (publisher policy), flag for review.
}
// Return the manifest. The publisher can vary `refresh_after_seconds`,
// `allow_outdated`, etc. per their policy.
echo $row['manifest_json'];
?>
A few things to note about this sample:
- One database read for the common path (the licensed-card hit).
- Refusals are cheap β a single SQL
SELECT+ a JSON response. midis the primary anti-clone signal. Default-on (privacy-friendly because it doesn't leak production data the wayaiddoes), so most taps include it. Same card_uid appearing with differentmids over a period of time = likely clone.aidis opt-in on the client side; if AntOS doesn't send it, the server simply doesn't log it. Detection still works viamid.- Anti-clone pattern detection is just SQL queries over the
tapstable β "how many distinctmids have tapped card X in the last 7 days?" If suspicious, the publisher's policy decides (revoke, warn, email, ignore).
{
"name": "Manic Miner",
"author": "β¦",
"version": "1.2.0",
"icon": "https://β¦/manic.png", // optional
"builds": [
{
"platform": "ezx-spectrum",
"requires_core": "ezx_spectrum", // MUST match cartridge-system core ID
"core_min_version": "β¦", // optional
"binary_url": "https://β¦/manic.z80",
"binary_format": "z80", // sna/tap/z80/β¦ per platform
"checksum": "sha256:β¦"
},
{
"platform": "agon",
"requires_core": "agon_light",
"binary_url": "https://β¦/manic.bin",
"binary_format": "agon-bin",
"checksum": "sha256:β¦"
},
{
"platform": "firestorm-native",
"requires_core": null,
"binary_url": "https://β¦/manic.luau-bundle",
"binary_format": "luau-bundle",
"checksum": "sha256:β¦"
}
],
"signature": "β¦" // reserved β see Trust below
}
- JSON is the lean choice: the manifest is fetched over HTTP, authored by game-makers, lives on a server β readability/authoring matter, size doesn't. The card holds only the URL.
The run pipeline (staged by dependency) π
- Layer A β dispatch (π‘, buildable now): card β scheme β handler;
https://handler stubs to "recognised manifest URL: β¦". - Layer B β fetch + match + display: fetch manifest, match
builds[]against installed cores, show runnable options. Needs networking + a registry of installed cores. - Layer C β run an installed game: for native builds, small (reuse script-running machinery). For FPGA-core builds, large β gated on the FPGA core-loading run-path existing.
- Layer D β download + install: fetch binaries into the user's chosen game store; eventually download/install cores too. The big networked chapter. Storage management, progress, integrity.
"Is it already installed?"
Layer B needs a games registry in the DBFS (what's installed, at what version) so a tapped card can resolve to "already have it β run" vs "need to fetch". Version comes from the manifest. (Schema TBD.)
Ownership registration π
With uid + aid (Β§3) plus the user's identity, a tapped product card can register
a specific copy to a specific pre-registered user. The pieces already line up:
AntOS's gossip mesh gives each user an Ed25519 keypair, and "pre-registered"
means that public key is associated with an ant64.com account once, up front.
Registration is then a signed request β no password in the loop; the server knows
which user it came from from the signature alone.
First tap of a new product card assembles:
product (from the manifest URL) + uid (card) + aid (this Ant64) + user Ed25519 signature
β
server: verify signature β known user
bind {product, uid} β that user, noting the aid it activated on
serve / download
After that, the card UID is the proof of ownership: tap the same card again,
signed in as that user, and the server answers "already owned β run / re-download"
rather than "register." Tap on a different Ant64 (new aid, same uid) and it
becomes "owned, authorise this machine?" β so aid scopes activation per box and the
owner's library follows their identity, not a particular machine.
One-time token (the cheap anti-clone). If the card also stores a short per-card
registration token (written at manufacture, alongside the URL), the bind becomes
{product, uid, token, signature} and the server marks the token spent on first
registration. A cloned card copies the UID and the token, but the token is already
spent β so the clone can't register to a different user. This is effectively how a
Steam key works, with the card as the key and the binding done automatically by the
machine's identity. It gets robust one-tap registration without the heavier per-tap
crypto of NTAG 424 DNA.
Already-registered fork (policy, not tech). When a card registered to user A is tapped by user B:
- Decline β strict, but breaks gifting/resale of the physical card.
- Transfer β A de-registers (releases), then B can claim. Preserves "I can lend or sell my card," the appeal of physical media.
- Household β bind to a small set of identities (a family), fitting the shared-main-plus-personal-cards topology (Β§6).
Lean recommendation: transfer-or-household β the point of games on cards is that they behave like objects you own, not licences you rent.
Networking & consent. Registration needs the network, so it's Layer-D (below): a
tap should queue the registration and complete when connectivity returns, not
fail. And binding uidβuser, or transmitting a stable aid, is the card/machine
phoning home its identity β intended for licensing, but it must be a visible,
consented action. The Β§4 confirm prompt is the natural home: "Register Manic Miner
to your account on this Ant64?" aid transmission should be defeatable for anyone
who doesn't want their box identified.
Trust & signing π (important once third-party)
"Games sold on cards" means a tapped physical card can cause a binary to be fetched
and run β an execution path triggered by an object. For your own games this is
low-risk; the moment third-party content is sold on cards, the manifest/binary
should be signed by a trusted key and verified before running. The signature
field is reserved in the schema now so the trust story can be added without a format
break. Native Luau is sandboxed-ish; core-loaded binaries less so. Treat signing as
required-before-commercial, optional-for-first-party.
Four independent identifiers end up in play, each answering a different question β complementary, not redundant:
| Identifier | Answers | Guards against |
|---|---|---|
Manifest signature |
Is the content from a trusted publisher? | Malicious / tampered games (protects the player) |
uid + NTAG originality signature |
Is the physical card genuine? | Cheap card clones β the NTAG21x originality signature is a 32-byte ECC signature NXP factory-writes over the UID, verifiable with their public key, free on the tags already chosen |
aid (structured 48-bit, in the ATECC608C) |
Which machine? | Board impersonation β if the read-protected-secret HMAC attestation (DeMon's ATECC608C) is used; the bare aid alone just scopes activation / re-download per box |
| User Ed25519 signature | Which owner? | Mis-attributed ownership (drives registration) |
The uid parameter plus the one-time token give soft licensing. Hard
anti-clone protection is two-ended when commercial content demands it: on the card
side the NTAG originality signature, or a step up to NTAG 424 DNA (cryptographic
per-tap authentication, immune even to a full memory clone); on the machine side the
read-protected-secret HMAC attestation in DeMon's ATECC608C secure element (an un-extractable key, so
a board can't be impersonated even with full bus access). Honest caveat: uid and
aid are themselves readable, broadcast in clear query strings (server logs,
referrer headers) β solid for identity and soft licensing, not secrets; only the
HMAC secret is unreadable by construction.
8. Build sequencing (recommendation)
Ordered by what's buildable now vs dependency-gated:
- β NFC read β done (May 2026).
- β URI dispatch (Layer A) + NFC dispatcher β done May 28; four schemes registered, confirm-prompt + OLED pin/unpin, two MIFARE cards dispatched cleanly.
- β
DBFS-switch core β done May 29.
sys_os_switch_dbfs+ warm-persistent override + warm-reboot + mount-time honouring + sys.db fallback +Bye+ Luau bindings + dispatcher wire. Hardware-verified with three round-trips. - π‘ NFC write Chapter 5A β write/read for NTAG21x (NDEF) and MIFARE
Classic 1K (raw, factory-default key).
nfc.write/nfc.read/provision.luawith read-before-write three-tier confirm. Tag-type dispatch transparent at the API level. Dispatcher Level-2 read integration. Natural next chapter. ~350 lines C + script. - π‘ NFC write Chapter 5B β AntOS metadata wrapper (write count,
timestamps, previous URI).
revert.lua,card.lua,nfc.info(). Layered on 5A; cards written without metadata read cleanly withmeta = niland gain metadata on next rewrite. ~250 lines C + scripts. - π Manifest schema design β pure design, do anytime; reconcile
requires_coreIDs with the personality cartridge system. - π Manifest fetch/match/display (Layer B) β needs networking + cores registry.
- π Run (Layer C) / download+install (Layer D) / ownership registration / signing β the large, infrastructure-gated future.
9. Notes for the documentation writer
- Honour the status markers. Don't present π vision as if implemented. The card mechanics + dispatch + DBFS-switch design are real/settled; the game download/run/core-loading pipeline is genuinely future and depends on networking and FPGA infrastructure that largely isn't built.
- Reconcile core IDs between this document's
requires_coreexamples and the real core identifiers in personality.md. They must be one shared vocabulary; the examples here are illustrative. - The mental model to lead with: a card is a URL; the system is a browser for physical cards; the scheme picks the handler. Everything else follows.
- Source of truth for the built parts:
sys_nfc.c/.h,lib_nfc.cpp,nfc.lua(read-layer design; prior P4 prototype verification does not apply to the redesigned CM/Clicky SPI architecture; PN532 fw IC=0x32 v1.6). That historical read-layer verification does not establish that the current Clicky SPI port has been bench-verified. The current wiring is SPI1 PB4βPB7, reset PA6, IRQ PA7 on Clicky; Clicky owns the PN532 driver and card-type/NDEF handling and relays validated card records to DeMon over IΒ²C. - This doc is a design capture from a build session, not a final spec β expect the schema (Β§7) and the DBFS-switch open questions (Β§6) to be refined when those chapters are actually built.