# SPDX-License-Identifier: MIT """Milestone 0: the formats front door on synthetic images (no ROM is copied or made). The whole-library judge is scripts/m0_formats.py (docs/validation.md, M0); these tests pin each rule on bytes made up here. """ from __future__ import annotations import hashlib import io import shutil import subprocess import zipfile from pathlib import Path import pytest from lynx_python import bootrom from lynx_python.bootrom import REFERENCE_SHA1 from lynx_python.cart import NotACart, describe, load from lynx_python.cart.bll import as_cart from lynx_python.cart.bll import loader as bll_loader from lynx_python.cart.convert import ConvertError, to_lnx, to_lyx from lynx_python.cart.formats import ( FormatError, LnxHeader, decode_eeprom, encode_eeprom, parse_lnx_header, sniff, unwrap, ) from lynx_python.cart.table import CartTable, default_table TEST_ROMS = Path(__file__).parent / "test_roms" / "lynx-tests-1.4.9.zip" def payload(size: int, seed: int = 1) -> bytes: """A made-up payload: a 1-block frame byte, then a pattern.""" body = bytes((i * 7 + seed) & 0xFF for i in range(size - 1)) return b"\xff" + body def lnx(data: bytes, block=1024, rotation=0, audin=0, eeprom=0, name="TEST", maker="ME") -> bytes: header = LnxHeader(block, 0, 1, name, maker, rotation, audin, eeprom, b"\0\0\0") return header.to_bytes() + data def bll(load=0x0400, body=b"\xa9\x01\x60") -> bytes: length = 10 + len(body) return b"\x80\x08" + load.to_bytes(2, "big") + length.to_bytes(2, "big") + b"BS93" + body def table_for(sha1: str, **fields) -> CartTable: return CartTable( { "entries": { sha1: { "name": "Tabled", "sources": ["softlist"], "fields": {k: {"value": v, "source": "softlist"} for k, v in fields.items()}, } } } ) EMPTY = CartTable({}) OBSERVED_FIELDS = { "bank0_block": 512, "bank1_block": 0, "audin": False, "rotation": "none", "eeprom": None, } def test_sniff_reads_content_not_extension(): assert sniff(lnx(payload(1024))) == "lnx" assert sniff(bll()) == "bll" assert sniff(payload(1024)) == "raw" assert sniff(b"LYNX") == "raw" # too short for a header def test_lnx_header_round_trips(): data = lnx(payload(2048), block=512, rotation=2, audin=1, eeprom=0x41, name="N", maker="M") header = parse_lnx_header(data) assert (header.bank0_block, header.rotation_name, header.audin, header.eeprom) == ( 512, "right", 1, 0x41, ) assert header.to_bytes() == data[:64] def test_eeprom_byte(): assert decode_eeprom(0) is None assert decode_eeprom(1) == ("93C46", 16) assert decode_eeprom(0x45) == ("93C86", 8) assert decode_eeprom(0x81) == ("93C46", 16) # the SD-card bit is a flash-cart matter assert decode_eeprom(6) is None assert encode_eeprom(("93C66", 8)) == 0x43 def test_lnx_and_lyx_meet_at_one_key(): p = payload(256 * 512) a, b = describe(lnx(p, block=512), table=EMPTY), describe(p, table=EMPTY) assert a.sha1 == b.sha1 == hashlib.sha1(p).hexdigest() assert a.kind == "lnx" and b.kind == "raw" assert a.bank0_block == b.bank0_block == 512 assert a.provenance["bank0_block"] == "header" assert b.provenance["bank0_block"] == "size-rule" def test_precedence_user_table_header_rule_default(): p = payload(256 * 1024) sha1 = hashlib.sha1(p).hexdigest() image = lnx(p, block=2048, rotation=0) table = table_for(sha1, bank0_block=1024, rotation="left") d = describe(image, table=table) assert (d.bank0_block, d.provenance["bank0_block"]) == (1024, "table:softlist") assert (d.rotation, d.provenance["rotation"]) == ("left", "table:softlist") assert d.bank0_alternatives == ((2048, "header"),) # decision 3: try the header's next assert any("header says 2048" in w for w in d.warnings) assert any("header says none" in w for w in d.warnings) d = describe(image, table=table, overrides={"rotation": "right", "bank0_block": 512}) assert (d.rotation, d.provenance["rotation"]) == ("right", "user") assert (d.bank0_block, d.provenance["bank0_block"]) == (512, "user") d = describe(p, table=EMPTY) assert d.provenance["rotation"] == "default" and d.rotation == "none" assert d.provenance["eeprom"] == "default" and d.eeprom is None def test_header_block_that_breaks_the_size_rule_loses_to_it(): # Mines 2 (Demo): LNX header 2048 on a 256 KiB payload (128 pages); the size rule's # 1024 boots (sweep 2026-11-19; OBSERVED MAME 0.285 the same). The header's value # stays as the alternative, whether read from the file or recorded in the table. p = payload(256 * 1024) sha1 = hashlib.sha1(p).hexdigest() d = describe(lnx(p, block=2048), table=EMPTY) assert (d.bank0_block, d.provenance["bank0_block"]) == (1024, "size-rule") assert d.bank0_alternatives == ((2048, "header"),) assert any("header says 2048" in w for w in d.warnings) recorded = CartTable( { "entries": { sha1: { "name": "Mines", "sources": ["lnx-header"], "fields": {"bank0_block": {"value": 2048, "source": "lnx-header"}}, } } } ) for image in (p, lnx(p, block=2048)): d = describe(image, table=recorded) assert (d.bank0_block, d.provenance["bank0_block"]) == (1024, "size-rule") assert d.bank0_alternatives == ((2048, "header"),) # A curated table entry keeps its precedence; the user's override is above all. d = describe(p, table=table_for(sha1, bank0_block=2048)) assert (d.bank0_block, d.provenance["bank0_block"]) == (2048, "table:softlist") d = describe(lnx(p, block=2048), table=EMPTY, overrides={"bank0_block": 2048}) assert (d.bank0_block, d.provenance["bank0_block"]) == (2048, "user") # A header that agrees with the size rule, or a payload with no rule size, is unchanged. d = describe(lnx(payload(256 * 512), block=512), table=EMPTY) assert (d.bank0_block, d.provenance["bank0_block"]) == (512, "header") d = describe(lnx(payload(100_000), block=1024), table=EMPTY) assert (d.bank0_block, d.provenance["bank0_block"]) == (1024, "header") def test_off_size_payload_gets_a_labelled_default(): d = describe(payload(224433), table=EMPTY) # Xump's size: a trimmed image assert (d.bank0_block, d.provenance["bank0_block"]) == (1024, "default") def test_bll_is_a_ram_program(): d = describe(bll(0x0400), table=EMPTY) assert (d.kind, d.boot, d.bll_load) == ("bll", "ram", 0x0400) assert d.bank0_block == 0 def test_bll_program_goes_behind_the_kits_cart_loader(): # The BLL kit's recipe (uloader/Makefile): bll.enc, the whole .o file, $FF to 256 KiB. program = bll(0x0400) image, block = as_cart(program) loader = bll_loader() assert (len(loader), block, len(image)) == (246, 1024, 256 * 1024) assert image[: len(loader)] == loader and loader[0] == 0xFF # one-block frame (count byte) assert image[len(loader) : len(loader) + len(program)] == program assert set(image[len(loader) + len(program) :]) == {0xFF} def test_bll_program_runs_through_the_boot_rom(): # The real boot ROM decrypts the kit's loader, which copies the program to its load # address and jumps there: the program's own stores are the verdict. rom = bootrom.find() if rom is None: pytest.skip("no boot ROM (bring your own: $MAME_ROMPATH/lynx.zip or $LYNX_BOOT_ROM)") from lynx_python.board import Lynx body = bytes.fromhex("a9a58d0003a95a8d010380fe") # STA $0300/$0301, then BRA * image, block = as_cart(bll(0x0400, body)) board = Lynx(image, block, boot_rom=rom) board.reset() for _ in range(8 * 60): board.run_ticks(266_667) if board.ram[0x0300:0x0302] == b"\xa5\x5a": break assert board.ram[0x0300:0x0302] == b"\xa5\x5a" assert board.ram[0x0400 : 0x0400 + len(body)] == body def test_containers_zip_7z_and_loose(tmp_path): p = payload(256 * 512, seed=3) for image, kind in ((lnx(p, block=512), "lnx"), (p, "raw"), (bll(), "bll")): loose = tmp_path / f"cart.{kind}" loose.write_bytes(image) assert load(loose, table=EMPTY, use_override_file=False).container == "loose" buf = io.BytesIO() with zipfile.ZipFile(buf, "w") as z: z.writestr("readme.txt", "not the cart") z.writestr(f"cart.{kind}", image) zpath = tmp_path / f"cart-{kind}.zip" zpath.write_bytes(buf.getvalue()) d = load(zpath, table=EMPTY, use_override_file=False) assert (d.container, d.kind) == ("zip", kind) if shutil.which("7z"): spath = tmp_path / f"cart-{kind}.7z" subprocess.run(["7z", "a", "-bd", str(spath), str(loose)], check=True, capture_output=True) # fmt: skip d = load(spath, table=EMPTY, use_override_file=False) assert (d.container, d.kind) == ("7z", kind) loose.unlink() def test_two_carts_in_one_archive_is_refused(): buf = io.BytesIO() with zipfile.ZipFile(buf, "w") as z: z.writestr("a.lyx", payload(1024, 1)) z.writestr("b.lyx", payload(1024, 2)) with pytest.raises(FormatError): unwrap(buf.getvalue()) def test_convert_refuses_to_invent_fields(): p = payload(256 * 1024) with pytest.raises(ConvertError, match="rotation"): to_lnx(describe(p, table=EMPTY)) d = describe(p, table=EMPTY, overrides={"rotation": "none", "eeprom": "none", "audin": 0}) with pytest.raises(ConvertError, match="bank1_block"): to_lnx(d) d = describe( p, table=EMPTY, overrides={"rotation": "left", "eeprom": "93C46:16", "audin": 0, "bank1_block": 0}, ) image = to_lnx(d) h = parse_lnx_header(image) assert (h.bank0_block, h.rotation_name, h.eeprom) == (1024, "left", 1) assert to_lyx(image) == p def test_round_trip_with_an_observed_header(): p = payload(256 * 512) sha1 = hashlib.sha1(p).hexdigest() image = lnx(p, block=512, name="Observed", maker="Maker") table = CartTable( { "entries": { sha1: { "name": "No-Intro Name", "sources": ["nointro", "lnx-header"], "fields": { k: {"value": v, "source": "lnx-header"} for k, v in OBSERVED_FIELDS.items() }, "lnx_header": { "name": "Observed", "maker": "Maker", "version": 1, "audin_byte": 0, "eeprom_byte": 0, "spare": "000000", }, } } } ) assert to_lnx(describe(to_lyx(image), table=table)) == image def test_user_override_file(tmp_path, monkeypatch): monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path)) p = payload(256 * 512, seed=9) path = tmp_path / "x.lyx" path.write_bytes(p) from lynx_python.cart.loader import save_override save_override(hashlib.sha1(p).hexdigest(), {"rotation": "right"}) d = load(path, table=EMPTY) assert (d.rotation, d.provenance["rotation"]) == ("right", "user") def test_shipped_table_carries_the_two_known_conflicts(): table = default_table() conflicts = { (e.name, c["field"]) for e in (table.get(s) for s in table.sha1s()) for c in e.conflicts } assert ("Zaku (World) (Beta) (Unl)", "bank0_block") in conflicts assert ("Raiden (USA) (Beta)", "rotation") in conflicts assert len(conflicts) == 2 def test_boot_rom_is_refused_as_a_cart(): data = bootrom.find() if data is None: pytest.skip("no boot ROM (bring your own: $MAME_ROMPATH/lynx.zip or $LYNX_BOOT_ROM)") assert hashlib.sha1(data).hexdigest() == REFERENCE_SHA1 with pytest.raises(NotACart): describe(data) def test_lynx_tests_roms_load(): if not TEST_ROMS.is_file(): pytest.skip("run scripts/fetch_references.py for the lynx-tests ROMs") with zipfile.ZipFile(TEST_ROMS) as z: for name in z.namelist(): d = describe(z.read(name), member=name) assert d.kind == "lnx" and d.boot == "encrypted", name