Pages of this audit: Overview · tower_sim (32) · turbine (8) · bunker_coin (4) · dts02-6502-signer (133)
| Audited | aeyakovenko/dts02-6502-signer at commit a7cbac2ed7093a3cd994c4b7f1109396cd1d2faf |
|---|---|
| Date | 15 November 2026; suggested fixes written 16 November 2026 |
| How it ran | local run on our workstation, full audit, Standard review |
| Verdict after review | Pass with notes (Fail if a High finding remains after review, otherwise Pass with notes) The verdict is for the whole audit: 177 findings in 4 repositories, counted once. |
The suggested fixes were written by a reviewer after the audit, with the code open. They were not compiled or run.
This page holds 133 of the 177 findings of the audit: the findings in dts02-6502-signer. No finding is on two pages.
This audit uses a fuller method than our first audit of 4 November 2026 (page removed 9 November 2026): the whole code was read file by file, then checked against our written rules, then against our detection checks. Because the method differs, the totals of the two audits are not comparable. All 4 Medium findings of the audit were checked again by a second reviewer, and so were 7 of its 124 Low findings; the other Low and Info findings are shown as first rated. This page: its 2 Medium findings were all checked again by a second reviewer, and 4 of its 94 Low findings were checked again. The code was read at the commit named above; it was not built or run.
How far the reading reached. Each reading reports the line ranges it covered, and a script checks every report against the file:
- dts02-6502-signer: 39 non-empty files, read in 384 line ranges. The reading of 53 of the 384 ranges could not be confirmed by script; all 39 files are covered by at least one confirmed range. One line of this repository (
sim/solana.py:81) was replaced by a placeholder in the copy we read.
Each finding keeps the number it has in the audit. It is shown with its rating, its location, the evidence it quotes and a suggested fix. Each location links to the file and line at the audited commit; evidence is quoted from the code as it stands there.
Compared with the first audit
Same commit as the first audit: on 17 November 2026 the default branch of each repository had no later commit. Each finding that our first audit of 4 November 2026 (page removed 9 November 2026) reported in this repository was checked again against the code. 7 findings in the first audit: 7 still in the code; 5 reported again in this audit, 2 not re-reported. This page has 133 findings, 129 of them new. This audit uses a fuller method, so the totals of the two audits are not comparable.
Still in the code = the code at the audited commit, the same commit the first audit read, still has the defect. Reported again = this audit lists it under the number shown. Not re-reported = this audit does not list it as a finding of its own. Cannot tell = it could not be decided from the code.
| First audit | Finding | Rating then, after review | In the code now | In this audit |
|---|---|---|---|---|
| #2001 | Generated build list contradicts the BOM: oscillator capacitor is 330 pF, spec rev 0.5 requires 560 pF, and no check catches it.sim/layout.py:278 | Medium | Still in the code | Reported again: #5101 |
| #2002 | A value the host can set is a claim: the expected public key is copied from the host envelope, so the derived-key check is not against an independently configured key as spec 10.3 requires.sim/signer_fw.py:1254 | Low | Still in the code | Reported again: #5758 |
| #2003 | Expected public key is taken from the host envelope, not an independently configured key; spec and FINDINGS claim otherwise.sim/signer_fw.py:1254 | Medium | Still in the code | Reported again: #5758 |
| #2004 | Secret cleanup sited at the end of the routine and incomplete: zero page and stack left, reset path never clears them.sim/signer_fw.py:1295 | Low | Still in the code | Reported again: #5009 |
| #2005 | Host-side verdict does not test the lock and fault outcome it prints.sim/__main__.py:175 | Low | Still in the code | Not re-reported |
| #2006 | Checker exit status is the same whether or not the limits it prints are exceeded.sim/__main__.py:155 | Low | Still in the code | Not re-reported |
| #2007 | Analog check claims to evaluate the spec's component values but still uses rev 0.3 values (330 pF, 400 kHz, 70-90 ms).sim/analog.py:141 | Low | Still in the code | Reported again: #5212 |
Medium after review (2)
sim/layout.py:278L.part("C", "C_OSC", "330p C0G", ("OSC_RC", "BB1", dict(near_row=u5(1)[2], side="L")),
The layout generator types the oscillator capacitor as "330p C0G" at sim/layout.py line 278, and that value is carried into the generated build list (wiring/WIRING.md line 73 and wiring/wiring.csv line 24), while the governing document fits 560 pF C0G in the U5 table at spec.md line 307 and explains at line 316 that the earlier 330 pF could exceed the clock ceiling. A builder who follows the wiring list therefore fits the superseded part. The spec is the authority here; the generator must not restate the value. Read the capacitor value for the U5 oscillator from the spec text (through sim/specdoc.py, as the placement and parts-list checks already do) or from one shared constant that sim/layout.py line 278 and the oscillator analysis in sim/analog.py (default at line 44, label at line 141) both use, then regenerate the two wiring files with python3 -m sim wiring and never edit them by hand. Add a row for the oscillator capacitor to the parts-list comparison in bom in sim/checks.py (lines 197-214), so that a difference between the spec and the build list fails the check. To confirm, run grep -rn '330p' sim wiring in the repository root: it lists 4 lines today and must list none, or only a line in sim/analog.py that is explicitly labelled as the earlier value; and add a test that compares the value of the C_OSC item returned by layout.generate() with the value parsed from spec.md Section 5.3. Not compiled or run.
sim/__main__.py:237 s.add_argument("--freq", type=float, default=380, help="master clock, kHz")
The loop at sim/__main__.py lines 228-240 gives the options --freq, --seed, --rev03 and --vcd to all four sub-commands run, diag, handoff and race, but cmd_race (lines 125-138) builds its benches without _bench_kw and reads only a.seed, so python3 -m sim race --freq 100 --rev03 --vcd x.vcd is accepted and all three options are silently ignored; README.md line 60 repeats the claim that the options are shared by all four. The smallest fix is to stop offering what race does not honour: add --freq, --rev03 and --vcd at lines 237, 239 and 240 only when name is not "race", keep --seed for all four, and correct README.md lines 60-64. The alternative is to honour them: pass master_hz and the VCD writer from _bench_kw(a) into both Bench calls at line 129 and reject --rev03 for race with a parser error, because that command always compares both revisions. In the same edit close the waveform file in cmd_handoff (lines 114-122), which opens it through _bench_kw and never closes it. To confirm, add one test per sub-command: main(["race", "--freq", "100"]) must end in SystemExit with code 2 under the first option, or print a different result for two frequencies under the second; handoff with two --freq values must print different master_period_ns; and run with --vcd must leave a closed, non-empty file. Not compiled or run.
Low after review (94)
sim/emu.py:70ctypes.memmove(ctypes.addressof(self.m.mem) + addr, bytes(data), len(data))
Machine.load in sim/emu.py copies data into the emulator's 64 KiB memory with ctypes.memmove at line 70 without checking the address or the length, so a caller can write outside the memory array and corrupt the process; the constructor has the same gap at line 56, where 65,536 bytes are copied from whatever image64k holds, and its ROM length check at line 58 is an assert that disappears under python -O. Validate at these three entry points and raise ValueError naming the offending value: in load require 0 <= addr and addr + len(data) <= 65536; in __init__ require len(image64k) == 65536 and replace the assert with a test that len(rom) == 32768. Machine.read at line 72 slices a ctypes array and needs no change. To confirm, add tests expecting ValueError for load(0xFFFF, b"ab"), load(-1, b"a"), Machine(image64k=bytes(10)) and Machine(rom=bytes(10)), and run the last one once with python3 -O. Not compiled or run.
sim/__main__.py:165to = SOL.b58decode(a.to) if a.to else E.public_key(hashlib.sha256(b"recipient").digest())
cmd_sign in sim/__main__.py decodes --to and --blockhash at lines 165-166 and passes them, with --lamports, straight into SOL.transfer_message at line 167 without checking them, so a value that does not decode to 32 bytes produces a malformed message that is still signed and printed as a transaction at line 184, and a character outside the base58 alphabet ends in a Python traceback from b58decode (sim/solana.py line 20). Validate where the values enter: give the --to and --blockhash arguments at lines 221-222 a type function that calls SOL.b58decode, turns its ValueError into argparse.ArgumentTypeError and rejects any result whose length is not 32 bytes, and give --lamports at line 223 a type function that rejects values outside 0 to 2**64 - 1. Invalid input then stops in the argument parser with a message naming the option, before any signing. To confirm, add tests that call main with a short --to, a --to containing the character 0, a 33-byte --blockhash, --lamports -1 and --lamports 2**64, each expecting SystemExit with code 2 and no tx line on standard output. Not compiled or run.
sim/__main__.py:163seed = hashlib.sha256(a.seed_text.encode()).digest()
cmd_sign derives the signing seed as a single unsalted SHA-256 of the --seed-text option (sim/__main__.py line 163; the default text is set at line 220 and is a published test value), prints the text back at line 177, and the derived seed is written into a temporary key file for the OpenSSL comparison (sim/solana.py lines 80-81). The owner must decide what the option is for. If the command is a test tool only, which is what the surrounding code suggests, refuse any text other than the built-in default unless an explicit acknowledgement flag is given, say in the option help that the resulting key must never hold funds, and stop printing the text at line 177. If real secrets are ever to be accepted, do not take them from the command line at all (they stay in shell history and the process list): read them with getpass, derive the seed with a salted slow function from hashlib such as scrypt, and skip the OpenSSL comparison that writes the key to disk. To confirm the first option, run python3 -m sim sign --seed-text x and observe a refusal with a non-zero exit code, and run grep -cF 'a.seed_text!r' sim/__main__.py in the repository root, which prints 1 today and must print 0. Not compiled or run.
sim/signer_fw.py:21Memory: zero page $10-$5F, buffers $0200-$1BFF, envelope $2000-$3EFF,
The module docstring of sim/signer_fw.py says at line 21 that the firmware uses zero page $10-$5F, but the table ZP allocates up to SQJ2 at $60 (line 47), two more zero-page names, CPTR at $40 and CRC at $42, are declared outside that table at line 1360, and the 64-byte product buffer T64 lies in zero page at $80-$BF (line 49). Correct the sentence to the real ranges, move CPTR and CRC into the ZP table so there is one list, and replace the reliance on a comment with a check at build time: give every zero-page entry its size, and raise an error from source() when two entries overlap or when one reaches into the T64 range. To confirm, run grep -cF 'zero page $10-$5F' sim/signer_fw.py in the repository root: it prints 1 today and must print 0, and add a test that adds a deliberately overlapping entry to a copy of the table and expects the build to raise. Not compiled or run.
sim/signer_fw.py:1295# wipe: zero $0200-$3FFF (secret scratch); zero page and stack are left to the caller
The wipe routine generated at sim/signer_fw.py lines 1295-1298 clears $0200-$3FFF only, on the success path (line 1293) and on the fail path (line 1294) alike; its comment leaves zero page and the stack "to the caller", and no caller in the file clears them. The zero-page working bytes ($10-$60) and the product buffer at $80-$BF therefore still hold the last intermediate values of the secret computation when sign_main returns, although spec.md lines 251-252 name zero page and the stack as secret scratch. The owner must choose. Either extend wipe so that, after the page loop, it also clears the zero-page working range and the product buffer (its own pointer last) and the part of the stack page below the current stack pointer, and write STATUS only afterwards as now. Or keep the code and record the limit in the spec and in FINDINGS.md as a known gap of this fixture build that a live-key build must close. In both cases state that the wipe cannot work once FAULT is set, because every RAM write is then blocked. To confirm the first option, add a test that after sign_main reads $0010-$00BF and the stack page and asserts every byte is zero apart from a named list of public status bytes; that test fails on the present code. Not compiled or run.
sim/emu65.c:207return rd(m, z) | (rd(m, (uint8_t)(z + 1)) << 8);
Five expressions in sim/emu65.c call rd twice inside one expression, at lines 207, 210, 216, 340 and 355, in the form rd(m, lo) | (rd(m, hi) << 8). Each rd updates the bus-address trace hash through the TRACE macro (lines 35 and 40), and C does not define which operand of | is evaluated first, so the order of the two reads, and with it the trace value that the constant-time tests compare, may differ between compilers or optimisation levels. Split each expression into two statements that read the low byte into a local variable first and the high byte second, and then combine the two values. To confirm, run grep -cE 'rd\(m, .*\) \| \(rd\(m, ' sim/emu65.c in the repository root: it prints 5 today and must print 0; then build the library at two optimisation levels (and with a second compiler if one is available) and check that a fixed run of the signing firmware gives the same trace value in every build. Not compiled or run.
sim/emu65.c:366m->pc += e->nb - 1; cyc = e->nc; break;
The header of sim/emu65.c says at line 3 that the emulator mirrors the instruction semantics of the Python core, but for the undefined two- and three-byte NOP opcodes the C code only advances the program counter (m->pc += e->nb - 1 at line 366) and never reads the operand bytes, while the Python core in sim/cpu65c02.py performs a bus read for each operand byte in its handling of these opcodes (around line 323). The two cores therefore differ in bus reads and in the trace value whenever such an opcode runs. Either make the C code perform the same reads, by calling fetch(m) once for each operand byte in the O_NOP case instead of adding to the program counter and reproducing any further dummy reads the Python core makes for these opcodes, or keep the code and state the difference in the header comment. To confirm the first option, add a cross-check that executes every multi-byte undefined NOP on both cores and compares the sequence of bus addresses, the cycle count and the final program counter; the existing comparison in tests/test_emu.py does not execute these opcodes with the trace compared. Not compiled or run.
sim/emu65.c:400uint64_t limit = m->cycles + max_cycles;
emu_run in sim/emu65.c computes its stopping point as m->cycles + max_cycles in 64-bit unsigned arithmetic (line 400); for a very large max_cycles the sum wraps round, the loop condition at line 403 is false at once and the function returns 0 as if the cycle limit had been reached. A negative Python integer passed to Machine.run (sim/emu.py lines 66-67) reaches the C function as such a huge value, because the argument type declared at sim/emu.py line 42 is an unsigned 64-bit integer and the conversion wraps without an error. Saturate the sum in C: when max_cycles is greater than UINT64_MAX - m->cycles use UINT64_MAX as the limit. In Machine.run reject a max_cycles that is negative or does not fit in 64 bits with ValueError before calling the library. To confirm, add a test that Machine.run(max_cycles=-1) raises ValueError, and a test that sets the cycle counter close to its maximum, asks for ten more cycles of a short loop and observes that instructions are executed instead of an immediate return. Not compiled or run.
sim/runner.py:27 self.cpu_period = self.sim.master_per_cpu * 1e9 / kw.get("master_hz", 380e3)
Bench.__init__ in sim/runner.py divides by the master clock frequency at line 27 without checking it. The value comes from the --freq option, declared as a plain float at sim/__main__.py line 237, so --freq 0 ends in a ZeroDivisionError traceback and a negative value gives a negative clock period and a simulation that cannot advance. Check the value where it enters: give --freq an argparse type function that converts to float and raises argparse.ArgumentTypeError unless the result is greater than zero, and in Bench.__init__ (or in build in sim/board.py, which receives master_hz at line 36) raise ValueError for a master_hz that is not positive, so that code calling the classes directly is covered as well. To confirm, add a test that main(["diag", "--freq", "0"]) and main(["diag", "--freq", "-5"]) end in SystemExit with code 2 and a message naming --freq, and a test that Bench(master_hz=0) raises ValueError. Not compiled or run.
sim/specdoc.py:30exec(compile(src, "spec.md:11.3", "exec"), ns)
diagnostic_rom in sim/specdoc.py extracts the Python block of spec.md Section 11.3 and executes it with exec at line 30. The block's file write and its print are disarmed only by two exact text replacements at lines 27-28; if the wording of either line in the spec changes by a single character, the replacement silently does nothing and the executed block writes a file to its own output path every time check, diag, race or roms runs. As the minimum, make a missed replacement an error: before each replace test that the expected text is present in the source and raise ValueError saying that the Section 11.3 generator has changed when it is not, handle a missing code block at lines 20-21 the same way, and after exec check that the name rom exists and holds 32,768 bytes. The more robust alternative is to stop executing text from a document: keep the generator as a normal function in the package and add a test that compares its source, or its output hash, with the block and the hash printed in the spec. To confirm, add a test that feeds diagnostic_rom a generator source in which the write line is spelt slightly differently, runs it in an empty temporary working directory, and asserts that it raises and that the directory is still empty. Not compiled or run.
sim/__main__.py:192os.makedirs(a.out, exist_ok=True)
The command-line tool overwrites existing files without notice: cmd_roms writes the ROM images and SHA256SUMS into the --out directory (sim/__main__.py lines 192-207), cmd_wiring rewrites the tracked wiring/WIRING.md and wiring.csv through LY.write_docs (line 144), --vcd opens any given path for writing (line 30, sim/vcd.py line 16), the emulator build writes sim/_build/_emu65.so (sim/emu.py line 39) and the OpenSSL comparison writes a key file into a temporary directory (sim/solana.py lines 78-81). For the three writers that take a user path, check before writing whether the target exists: if its content is identical say so and skip, otherwise either refuse unless a --force option is given or print the name of each file being replaced; write to a temporary name in the same directory and move it into place with os.replace so an interrupted run leaves the old file intact. Add a --check option to the wiring command that compares the generated text with the files on disk and reports differences without writing. To confirm, add a test that runs the roms command twice into a temporary --out directory, alters one image in between, and asserts that the second run reports the replacement (or refuses) instead of silently overwriting. Not compiled or run.
sim/asm.py:109return int(tok[1:], 16)
Assembler.atom in sim/asm.py converts hex and binary literals with int() at lines 109 and 111 without catching the conversion error, so a malformed literal such as $, $GG or %2 leaves the assembler as a bare ValueError and the line-number wrapping at lines 178-179, which only catches AsmError, is skipped. The .ALIGN directive at lines 225-227 divides by its operand, so .align 0 ends in a ZeroDivisionError, and .RES at lines 220-224 accepts a negative count and moves the address backwards. Wrap the two conversions in try/except ValueError and raise AsmError naming the token; in .ALIGN raise AsmError unless the operand is greater than zero, and in .RES unless it is zero or more. To confirm, extend test_malformed_expressions_rejected in tests/test_static.py (lines 84-89) with the expressions $, $GG and %2, and add a test that assembling a source with .align 0 raises AsmError whose message begins with the word line. Not compiled or run.
tests/test_cpu_core.py:92if __name__ == "__main__":
unittest.main()
In tests/test_cpu_core.py the guard if __name__ == "__main__": unittest.main() stands at lines 92-93, before the class TestBootRomIdealBus is defined at line 96, so when the file is run directly unittest.main() collects and runs the tests while that class does not yet exist and its test never runs. Move the two guard lines to the very end of the file, after the last line of TestBootRomIdealBus. Discovery through python3 -m unittest discover is not affected, because it imports the whole module first. To confirm, run python3 -m tests.test_cpu_core -v from the repository root and check that test_full_zeroing_build_boots appears in the list of executed tests; grep -n '__main__' tests/test_cpu_core.py reports line 92 today and must afterwards report the second-last line of the file. Not compiled or run.
sim/parts.py:813width = t - self.t_load_edge
if width < T["tCSW"] and load == 1:
The MAX7219 model in sim/parts.py checks the LOAD pulse at lines 811-815: on every LOAD edge it measures the time since the previous edge and reports a violation when that time is below tCSW and the new level is 1. At a rising edge the time since the previous edge is how long LOAD was low, so the model compares the low time with the figure that the parameter table at line 741 lists as tCSW. Check the timing table of the MAX7219 datasheet to see which level tCSW constrains; if it is the high pulse, move the comparison to the falling edge (load == 0), where the measured time is the high time. The table at line 741 holds only tDS, tDH, tCH, tCL, tCSW and tDO, and the model checks nothing about the timing of LOAD relative to CLK. Check in the same datasheet table whether it specifies a setup or a hold time between LOAD and CLK; if it does, add those figures to MAX7219_T and test them against the stored edge times t_clk_edge and t_load_edge. This fix states no datasheet value or parameter beyond those the repository already names; the owner reads them from the datasheet of the part actually fitted, including the second sources named in the class docstring at line 747. To confirm, add a unit test that drives a powered MAX7219 with a LOAD pulse that violates the limit at the level the datasheet constrains and expects one pulse-width violation for LOAD, and with a short pulse at the other level between two long ones and expects none. Not compiled or run.
sim/timing.py:8paths. Edit here and re-run; nothing else hard-codes timing.
The header of sim/timing.py ends at line 8 with "nothing else hard-codes timing", but sim/parts.py does: the display power switch delays of 3,000 and 50,000 ns (lines 871 and 873), the reset RC discharge of 1,000 ns (line 726), the 1 ns delays of the row diode and the keypad (lines 886 and 927), the 1 ns EPROM turn-on (line 616), the zero delay of the series resistor (line 633), the fallback range (5, 35) at line 309 and the whole MAX7219_T table (line 741). In the other direction sim/timing.py holds entries no model reads. The HC595 keys in TEN and TDIS (lines 29-30) are unread, because the HC595 class (sim/parts.py line 401) takes its delays from the separate HC595 table and is itself no longer placed on the board. The RSER entry in TPD (line 25) is unread as well: the series-resistor part carries the kind "RSER" (sim/parts.py line 626) only as a label for the rule check and the layout, it schedules its output with the literal 0 at line 633, and the lookup T.TPD.get(fam, ...) at line 309 is reached only from the two calls at lines 332 and 352, which pass "HCT541" and "HCT244". Re-check each of these with grep before removing it. Make the sentence true by moving the listed figures into sim/timing.py as named entries that sim/parts.py reads, with the series resistor reading its RSER entry, or reword it to say which delays live in the part models and why. To confirm the first option, run grep -c 'MAX7219_T = dict' sim/parts.py in the repository root: it prints 1 today and must print 0, and the listed delay literals must no longer appear in sim/parts.py; for the second option the reworded sentence must name the exceptions. Not compiled or run.
sim/board.py:39[(net, ohms, pf)]. The netlist is then whatever the breadboard wiring
The docstring of build in sim/board.py says at lines 38-40 that the physical pull-up list holds entries of the form (net, ohms, pf), but the loop at line 62 unpacks four values per entry (net, ohms, pf, level). The producer has the matching slip: the docstring of physical_netlist at sim/layout.py line 534 announces three return values (pin_remap, pullups, report) while the function returns four, which cmd_wiring unpacks at sim/__main__.py line 145. The code is the side that works, so correct the two docstrings: describe the pull-up entry as (net, ohms, pf, pull level) in sim/board.py and list the four return values in sim/layout.py. To confirm, run grep -cF '[(net, ohms, pf)]' sim/board.py in the repository root: it prints 1 today and must print 0, and each corrected sentence must match the unpacking at sim/board.py line 62 and sim/__main__.py line 145. Not compiled or run.
sim/layout.py:487_, board, rail = f
The docstring of connectivity in sim/layout.py describes the third fault form at lines 468-469 as ("drop_wire", net, predicate-text), but the code at lines 486-489 unpacks it as (board, rail) and removes the bridge wire that joins the two halves of that rail on that board; the test that injects a missing rail bridge in tests/test_breadboard.py passes a board name and a rail name. The code and its caller agree, so correct the docstring: describe the form as ("drop_wire", board, rail) and say what it removes. To confirm, run grep -c 'predicate-text' sim/layout.py in the repository root: it prints 1 today and must print 0, and the corrected sentence must match the unpacking at line 487. Not compiled or run.
sim/layout.py:740with open(os.path.join(outdir, "WIRING.md"), "w") as f:
write_docs in sim/layout.py opens its two output files in text mode without naming an encoding (wiring.csv at line 673 and WIRING.md at line 740), and the waveform writer does the same at sim/vcd.py line 16. The WIRING.md text contains characters outside ASCII, for example the less-or-equal sign written at line 699 and the dash at line 713, so on a system whose default encoding is not UTF-8 the write fails or produces a file that differs from the committed one. Pass encoding="utf-8" to the three open calls. To confirm, run grep -c 'encoding=' sim/layout.py in the repository root: it prints 0 today and must print 2; then regenerate the wiring files once with the environment variable PYTHONIOENCODING unset under a non-UTF-8 locale and check that WIRING.md is byte-identical to the one produced under a UTF-8 locale. Not compiled or run.
sim/analog.py:125seg_nom = (5 - 1.9) / 3300
seg_bound = 5.25 / (3300 * 0.95)
display_current in sim/analog.py (lines 124-129) still computes the display current from a 3300 ohm resistor per segment, which is the earlier shift-register display; the current design drives the digits from two MAX7219 drivers whose segment current is set by the 47 kOhm RSET resistor listed at spec.md lines 122 and 705, and the result of the old formula is also typed as the literal 214.4 into the worst-case budget in power() at line 113 and asserted in tests/test_static.py lines 129-131. Rework display_current as a calculation for the fitted driver: take the segment current that the MAX7219 datasheet gives for the fitted RSET value, apply the multiplexing the driver uses and add the driver's own supply current, and record each datasheet figure with its source in the DATASHEET table at line 12. Then make power() read the display bound from display_current() instead of the literal at line 113, and recompute the regulator dissipation and temperature rise that depend on it. Which datasheet figure and corner to use is for the owner to settle against the MAX7219 datasheet; this fix names no value. To confirm, run grep -c '3300' sim/analog.py in the repository root: it prints 2 today and must print 0, and add a test asserting that the display entry of the budget returned by power() equals the bound returned by display_current(). Not compiled or run.
sim/analog.py:153f"datasheet-max {pdc['total_max']:.0f} pF (budget 60 pF)")
The analog report in sim/analog.py prints "(budget 60 pF)" at line 153, although spec.md line 1065 now sets the acceptance from the input-transition limit at about 320 pF on P_D and 150 pF on C_D, and sim/layout.py checks the generated layout against exactly those two numbers typed in again at lines 640-643 and 699; sim/board.py line 33 keeps 60 and 45 pF as the load the simulator assumes. Give the two limits one home: define them once as named constants (or derive them once from the 500 ns/V limit with the pullup function at sim/analog.py line 80), use them in the report line at 153 and import them in sim/layout.py at lines 640-643 and 699. Add a comment at sim/board.py line 33 saying that DEFAULT_CAP is the nominal simulated load and not a limit. To confirm, run grep -c 'budget 60 pF' sim/analog.py in the repository root: it prints 1 today and must print 0; and a test must compare the limit used by the layout check with the constant, so that changing one without the other fails. Not compiled or run.
U7 pin 2 strip and the U1 pin 37 strip.sim/layout.py:638if phi2_seg and phi2_seg > 50:
wire_report in sim/layout.py sets phi2_seg only when one wire joins exactly the strip of U7 pin 2 and the strip of U1 pin 37 (lines 583-587); in any other routing it stays None. harness_checks then tests it with "if phi2_seg and phi2_seg > 50" at line 638, so a segment that was not found is treated the same as a segment within the limit, and write_docs prints the limits as met (line 700). Make the missing measurement a failure: in harness_checks add an entry to the returned list of unmet targets when phi2_seg is None, saying that the U7 to U1 segment was not found, or replace the single-wire search by the length of the wire path between the two pins. To confirm, add a test that makes wire_report return None for the segment (for example by patching it) and asserts that harness_checks reports an unmet target and that the wiring command exits with a non-zero code or prints the target as not met. Not compiled or run.
U7 to U1), P_D and C_D.wiring/wiring.csv:399wire,,,PHI2_FAULT,BB1:a35,BB9:a16,416
The generated build list routes the clock of the fault latch, the net PHI2_FAULT, as one jumper of 416 mm from BB1 to BB9 (wiring/wiring.csv line 399), and no check looks at it: harness_checks in sim/layout.py applies a length or capacitance limit only to the PHI2 segment between U7 and U1 and to the P_D and C_D lines (lines 627-643). A clock input fed over a long unshielded jumper is a signal-integrity question the layout check should not pass by silence. The owner has two directions. Either state a limit for this net, derived from the clock-input requirements in the datasheet of the flip-flop it drives and from the edge-rate rules of spec.md Section 5.4, and add it to harness_checks as a further target using the net's total length or its estimated capacitance, both of which the function already computes for other nets. Or shorten the net by design, for example by placing its buffer gate on the lock board, which is a change to the placement in spec.md and not to the generated file. Do not edit wiring.csv by hand. To confirm the first direction, run python3 -m sim wiring and check that the report now names PHI2_FAULT with its length and verdict, and add a test that asserts the reported value against the chosen limit. Not compiled or run.
sim/checks.py:198("DIP ICs", int(m.group(2)), len(ics)),
bom in sim/checks.py searches the spec text for the "Installed total" sentence at line 196 and uses m.group at lines 198-199 without testing the match, so when that sentence is reworded or missing the check stops with an AttributeError instead of reporting a parts-list problem; the helper qty at lines 177-179 already returns None for a missing line. Test m before the return at line 197: when it is None, give the two rows that depend on it ("DIP ICs" and "all ICs") a spec quantity of None, exactly as qty does, so that both callers (tests/test_static.py lines 104-105 and cmd_check at sim/__main__.py line 71) report them as mismatches. To confirm, add a test that replaces checks.spec_text with a function returning the spec text without the "Installed total" sentence and asserts that bom returns a row ("DIP ICs", None, n) and raises nothing. Not compiled or run.
sim/engine.py:260self.now = t_end
Simulator.run_until in sim/engine.py (lines 255-269) sets self.now = t_end at line 260 whenever the next queued event lies after t_end, without checking that t_end is not earlier than the present time, so a caller that passes a time in the past moves the simulation clock backwards; sim/brownout.py line 50 can do this when its offset is negative. Reject the call instead of adjusting it silently: as the first statement of run_until raise ValueError naming both times when t_end is not None and t_end < self.now. Rejecting is preferred over clamping to the present time because a past target is a caller mistake that should be seen. To confirm, add a test that advances a Simulator, calls run_until with now minus one and expects ValueError, and asserts that now is unchanged afterwards; the existing suite must still pass, which shows no current caller relies on rewinding. Not compiled or run.
sim/brownout.py:46t_we = target[0]
dip_during_write in sim/brownout.py runs the simulation at line 45 until the stop function has seen nth_write write strobes with mixed data, and then reads target[0] at line 46 without checking that the stop condition was ever met; if the scenario produces fewer such writes within the 400,000-cycle window the list is empty and the caller gets an IndexError that says nothing about the cause. Use the value run_until returns at line 45 (or test the list) and raise a RuntimeError that names the scenario, the requested nth_write and the number of mixed-data writes actually seen. At the top of the function also reject nth_write below 1 and a negative offset_ns with ValueError, because a negative offset would ask the simulator at line 50 to run to a time before the strobe it has already reached. To confirm, add a test that calls dip_during_write with nth_write=10**6 and expects the RuntimeError with the scenario name in its message, and one that passes offset_ns=-1 and expects ValueError. Not compiled or run.
sim/board.py:326if lab in row:
Harness.press_keypad in sim/board.py (lines 322-328) looks each label up in Keypad4x4.LABELS and silently skips a label it does not find, so a misspelt key presses nothing and the caller then observes "no key" as if that were the result. After the inner loop over the rows, raise ValueError naming the label when no row contained it (a for/else on the loop at line 325 does this), before set_pressed is called at line 328, so that either all labels are valid or nothing is pressed. To confirm, add a test that calls press_keypad with a label that is not on the keypad, for example "Z", and expects ValueError, and one that presses "1" and "D" and checks that the keypad's pressed set holds exactly those two positions. Not compiled or run.
U8 pin 9 as grounded, but Section 8 (line 673) wires U8 pin 9 to DISPLAY_OE_N, with output pin 8 as DISPLAY_ON. sim/board.py line 139 also uses pin 9 as DISPLAY_OE_N.spec.md:514- Pins 9,11,13=ground; corresponding outputs unused.
spec.md Section 7.1 says of the inverter package U8 at line 514 "Pins 9,11,13=ground; corresponding outputs unused", but Section 8 wires U8 pin 9 to DISPLAY_OE_N (the U18 table at line 656) and states at line 666 that U8 pin 9 takes DISPLAY_OE_N and its output pin 8 is DISPLAY_ON, the display power request; the simulated netlist agrees with Section 8 (sim/board.py line 139). A builder who follows Section 7.1 alone grounds the input of the gate that switches the display supply. Section 8 and the netlist are the two places that agree, so correct Section 7.1: change line 514 to state that pin 9 is DISPLAY_OE_N with output pin 8 as DISPLAY_ON (referring to Section 8) and that pins 11 and 13 are grounded with their outputs unused. Before editing, confirm against the wiring the owner intends that Section 8 is the governing text. To confirm, run grep -c 'Pins 9,11,13=ground' spec.md in the repository root: it prints 1 today and must print 0, and the U8 lines of Section 7.1, the U18 table and sim/board.py line 139 must then name the same nets for pins 8 and 9. Not compiled or run.
spec.md:219The DIP switch and pushbuttons can sit on a separate passive panel or free terminal strips, with the individual connections shown in Section 8.
The last sentence of the placement paragraph at spec.md line 219 still says "The DIP switch and pushbuttons can sit on a separate passive panel", although this revision replaced the DIP switch with the 4x4 membrane keypad (lines 18 and 585). Reword the sentence to name the keypad connector and the pushbuttons, with the connections shown in Section 8. The other two mentions of the DIP switch, at lines 18 and 585, describe the change from the earlier revision and can stay. The sentence is a leftover of the kind a long single document collects: consider moving the three "Changes from revision" lists (lines 14-41) into a separate history file when the document is next reorganised, so that the body describes only the current design. To confirm, run grep -c 'The DIP switch and pushbuttons' spec.md in the repository root: it prints 1 today and must print 0, and grep -n 'DIP switch' spec.md must then list only the two historical mentions. Not compiled or run.
spec.md:297leaving about 50 mV for load regulation and the 120 mA display-current steps
The supervisor paragraph at spec.md line 297 argues its margin with "the 120 mA display-current steps". That figure belongs to the earlier display; the same document now bounds the display at about 210 mA with every segment lit (line 291) and uses 0.34 A for the regulator budget (line 289). Rework the sentence for the present display: state the load step that the two MAX7219 drivers can cause when the display is switched or its content changes, taken from the display bound at line 291 and the driver datasheet, and re-derive from the regulator's load-regulation figure what margin remains to the supervisor trip range; or, if the sentence is meant only as history of the earlier supervisor choice, say explicitly that the 120 mA and the 50 mV refer to that earlier revision. This fix supplies no new electrical value; the owner computes it from the datasheets named in Section 13. To confirm, run grep -c '120 mA' spec.md in the repository root: it prints 1 today and must print 0 unless the figure is labelled as historical, and the acceptance check at the end of the paragraph must still follow from the reworked numbers. Not compiled or run.
README.md:92spec.md the design under test (rev 0.4; rev 0.3 is in git history)
The Layout block of README.md says at line 92 that spec.md is "rev 0.4; rev 0.3 is in git history", but line 3 of the same file calls spec.md the revision 0.5 specification. Change the entry at line 92 to "rev 0.5; earlier revisions are in git history", or better, remove the revision from that line so that line 3 is the only place in the README that states it and cannot drift again. To confirm, run grep -c 'rev 0.4; rev 0.3 is in git history' README.md in the repository root: it prints 1 today and must print 0, and the revision named in README.md must equal the one in the heading of spec.md. Not compiled or run.
FINDINGS.md:200| Pinouts and wiring for all 43 DIPs | ERC: 0 errors. No undriven inputs, no output-to-output or output-to-rail shorts, and the only three-state-only nets (P_D, C_D) have pull-ups. |
The "Confirmed correct" table in FINDINGS.md still carries revision 0.4 content: line 200 says "all 43 DIPs" and line 201 "43 rows", while the same file's line 170 and wiring/WIRING.md line 14 give 28 DIP ICs for revision 0.5 and tests/test_static.py line 64 asserts 28 placement rows; line 202 lists resistor values to be compared with the current parts list in spec.md; and line 208 describes the shift-register display chain (QA-QH mapping) that line 163 says was replaced by the MAX7219 drivers. Either rewrite lines 200-202 and 208 from the present outputs (the placement check, the ERC result, the parts-list comparison and the display test), or add a heading line to the table that says its rows record the revision 0.4 check. To confirm, run grep -cE '43 (DIPs|rows)' FINDINGS.md in the repository root: it prints 3 today and must print 1 after a rewrite (the historical comparison at line 170 stays), and every remaining figure in the table must be traceable to a named test or command. Not compiled or run.
FINDINGS.md:203| Johnson timing, write strobes, read latch | One WR_GPIO_N edge per $7F02 store, exactly one master period before PHI2 falls. C_D is held about 2.66 µs after PHI2 falls. RWB_CYCLE changes only at PHI2 rises. |
FINDINGS.md line 203 says the WR_GPIO_N edge comes "exactly one master period before PHI2 falls", but spec.md lines 597 and 1048 require two master periods and tests/test_bus.py lines 93-94 assert a lead of 1.9 to 2.1 periods. Line 204 gives "P_D gap >= 2 master periods, C_D gap >= 1", while spec.md lines 1060 and 1063 require three and two. Correct line 203 to two master periods, and replace the gaps at line 204 with the values the current measurement returns (the P_D_min_gap_ns, C_D_min_gap_ns and gpio_edge_lead_before_phi2_fall_ns results of sim.handoff.measure that tests/test_bus.py reads), or label both rows as the revision 0.3 results. The comment at sim/handoff.py line 70 repeats the one-period wording and needs the same correction. To confirm, run grep -c 'exactly one master period' FINDINGS.md in the repository root: it prints 1 today and must print 0, and the numbers at lines 203-204 must agree with spec.md lines 597, 1060 and 1063. Not compiled or run.
FINDINGS.md:126- **Field multiplication:** about 155k cycles. The 6502 has no multiply instruction, and a constant-time shift-and-add over 256 bits is the price of avoiding secret-indexed tables.
The "dominant costs" list at FINDINGS.md lines 125-128 quotes figures of the first firmware version inside a section that otherwise describes the optimized one: line 126 gives about 155k cycles for a field multiplication although line 115 gives 133k for the multiply and 107k for the squaring, and line 128 gives about 574M cycles for verification although the table at line 108 totals 0.65e9 cycles for the whole optimized flow with two signatures of about 0.24e9 each (line 107). Re-measure the three items (multiplication, inversion, verification) on the optimized build and replace the figures, naming the test or command that produced each; or head the list "first version" and add the optimized figures beside it. To confirm, run grep -cE '155k|574M' FINDINGS.md in the repository root: it prints 2 today and must print 0 unless the lines are explicitly labelled as first-version figures, and the three items must then be consistent with the totals at lines 107-108. Not compiled or run.
tests/test_static.py:150# Finding F3: 10k/330p does not guarantee the spec's 400 kHz ceiling
test_oscillator_spread_finding in tests/test_static.py (lines 149-153) carries the comment "Finding F3" at line 150, but in FINDINGS.md the oscillator finding is F2 (line 41) and F3 is the P_D capacitance budget; and the test exercises only the retired 330 pF value, because analog.oscillator defaults to c=330e-12 (sim/analog.py line 44) and the report line is labelled "Oscillator 10k/330p" (sim/analog.py line 141). The fitted part is 560 pF with a stated range of about 76 to 530 kHz and a 600 kHz ceiling (spec.md lines 307 and 316), and no test or check output covers it. Correct the comment to F2 and say that the test reproduces the earlier value; add a test that calls analog.oscillator(c=560e-12) and asserts that min_hz and max_hz agree with the range in spec.md line 316 within a stated tolerance and that max_hz does not exceed 600e3; and make the report print the fitted capacitor, keeping the 330 pF line marked as historical. To confirm, run grep -c 'Finding F3' tests/test_static.py in the repository root: it prints 1 today and must print 0, and python3 -m sim check must print an oscillator line for 560 pF. Not compiled or run.
tests/test_bus.py:14CORNERS = (127e3, 380e3, 890e3) # oscillator spread from sim/analog.py
tests/test_bus.py line 14 sets the clock corners for the Monte Carlo test to 127, 380 and 890 kHz with the comment "oscillator spread from sim/analog.py". Those are the figures for the earlier 330 pF capacitor; spec.md line 307 now fits 560 pF and line 316 gives a master clock of about 76 to 530 kHz with an acceptance ceiling of 600 kHz, so the slow end of the real range is never simulated and the fast corner lies above the ceiling the spec allows. Compute the corners instead of typing them: call analog.oscillator(c=560e-12) and use its min_hz, mid_hz and max_hz, add the 600 kHz ceiling as a fourth corner, and correct the comment. To confirm, run grep -c '890e3' tests/test_bus.py in the repository root: it prints 1 today and must print 0; add an assertion that the lowest corner is below 100 kHz so the slow end cannot be dropped again, and run test_monte_carlo_delays_and_clock_corners at the new corners. Not compiled or run.
tests/test_static.py:125 self.assertAlmostEqual(pw["p_spec_w"], 2.2, delta=0.05)
self.assertAlmostEqual(pw["rise_spec_c"], 45, delta=1)
test_power_numbers_in_spec in tests/test_static.py asserts at lines 125-126 a regulator dissipation of 2.2 W and a rise of 45 degrees, the figures for an assumed 0.30 A, while spec.md line 289 now states 0.34 A, about 2.5 W and a rise of roughly 51 degrees; lines 130-131 assert 120 mA and 214.4 mA of display current from the earlier resistor-per-segment calculation, while spec.md line 291 bounds the display at about 210 mA for the two MAX7219 drivers. The test therefore passes while the code and the document disagree. Make the test follow the document: read the current, power and temperature figures from the sentence at spec.md line 289 through specdoc.spec_text() with a regular expression, and compare them with the worst-case values that analog.power() already returns (i_worst_a, p_worst_w and rise_worst_c); compare the display bound returned by the display calculation with the figure at spec.md line 291; and remove the assertions on p_spec_w and rise_spec_c or mark them as the superseded case. To confirm, run grep -cF '2.2, delta' tests/test_static.py in the repository root: it prints 1 today and must print 0, and changing the figure in a scratch copy of spec.md must make the new test fail. Not compiled or run.
tests/test_signer.py:199self.assertEqual(fw.get(0x0200, 0x3E00), bytes(0x3E00)) # secrets wiped
The "secrets wiped" assertions in tests/test_signer.py (line 199 on the success path and line 237 on the refusal paths) read only $0200-$3FFF, which is exactly the range the firmware's wipe routine clears (sim/signer_fw.py lines 1295-1298). spec.md lines 251-252 name zero page and the stack as secret scratch as well, the firmware leaves both untouched, and no test reads $0000-$01FF after signing, so secret-dependent bytes left there are neither removed nor noticed. The owner must choose. Either extend the wipe to the zero-page working bytes and the used part of the stack and add an assertion that $0000-$01FF hold only zeros apart from a named list of public status bytes; or keep the behaviour, state in the test comment and in FINDINGS.md that zero page and stack are outside the wipe in this fixture build, and add the same assertion as an expected failure so the gap stays visible. To confirm, the new assertion must fail on the present firmware, which shows it can detect leftover bytes, and must pass once the wipe is extended. Not compiled or run.
tests/test_signer.py:221 cases = {
"bad crc": good[:-1] + bytes([good[-1] ^ 1]),
spec.md line 982 requires the firmware to reject, among other things, extra bytes and unknown profiles. test_fail_closed in tests/test_signer.py (cases at lines 221-228) covers only profile 1 for the profile rule and has no case with bytes after the CRC or with a truncated envelope. For profiles, add cases for profile 2 and for an unassigned value such as 255 and expect the same refusal. For extra bytes there is nothing to test yet, because the firmware cannot know how many bytes were delivered: gen_main computes the envelope size as 44 plus the length field and reads the CRC at that offset (sim/signer_fw.py lines 1237-1246). The owner must decide: either give the firmware the number of bytes received, in a location the loader fills in, and refuse when it differs from the size implied by the length field plus the CRC; or reword the sentence at spec.md line 982 to say that the envelope is delimited by its length field and that bytes after the CRC are ignored. To confirm, the profile cases must pass at once on the present firmware; for the first decision add a case with one byte appended after the CRC and expect status $EE with no RESULT_LOCK. Not compiled or run.
tests/test_bus.py:73self.assertGreater(self.r["C_D_min_gap_ns"], 0.95 * self.r["master_period_ns"])
Two assertions in TestHandoff in tests/test_bus.py are weaker than the acceptance figures they are named after. test_item5 at line 73 requires the C_D gap to exceed 0.95 master periods, while spec.md line 1063 requires at least two; test_item2 at line 70 requires the P_D quiet time to exceed 1.9 periods, while spec.md line 1060 requires at least three (line 100 of the same file already asserts 2.9). Raise the factor at line 73 to 1.9 and the factor at line 70 to 2.9, and rename the two tests so their names state the spec figure. If a raised assertion fails, do not lower it again: that would mean the simulated board does not meet the spec item, which has to be resolved in the design or in the spec. To confirm, run grep -cF '0.95 * self.r' tests/test_bus.py in the repository root: it prints 1 today and must print 0, and then run the TestHandoff class. Not compiled or run.
README.md:32Both CPU models pass Klaus Dormann's 6502/65C02 conformance tests with identical cycle counts.
README.md line 32 states that both CPU models pass Klaus Dormann's conformance tests, and line 55 advertises a suite of 98 tests, but those tests run only after the optional ./tools/fetch_klaus.sh (line 54): tests/test_emu.py line 40 skips the whole TestKlaus class when third_party/klaus is absent, so a clean checkout reports success without running them. Reword line 32 to say the two models pass when the test ROMs have been fetched and that the class is skipped otherwise, and at line 55 say how many tests are skipped without the ROMs or drop the count. In tools/fetch_klaus.sh line 7 replace the clone of the moving default branch with a checkout of one fixed commit and check the SHA-256 of the two .bin files named in tests/test_emu.py lines 11-12 after download, so that "pass" always refers to the same ROMs. To confirm, on a clean checkout run python3 -m unittest tests.test_emu -v and observe that the two TestKlaus tests are reported as skipped with the reason, exactly as the README now says; grep -c '98 tests' README.md in the repository root prints 1 today. Not compiled or run.
sim/signer_fw.py:1"""DTS-02 signing firmware: Ed25519 (RFC 8032) for the W65C02S, generated as
sim/signer_fw.py is 1,411 lines long and combines parts that have separate concerns: the memory map and slot allocator (lines 35-101), constants and table builders (107-166), the code-generation helpers (172-214), field arithmetic (220-572), group arithmetic (578-762), scalar arithmetic and recoding (768-850), SHA-512 (856-1024), the sign, verify and envelope flow (1030-1321), data tables and build (1324-1389), and the host-side helpers envelope and expected_record (1395-1411). At this size split it before adding anything: put the memory map into one module that the generators, the harness and the command line all import, give each arithmetic layer and the flow a generator module of its own, and move the host helpers out. Move code without changing what it emits. To confirm, record the SHA-256 of build()[0] for all four combinations of the double_sign and verify options before the split and check that all four are identical afterwards, then run the unchanged signer tests. Not compiled or run.
sim/signer_fw.py:60MAX_MSG = 4096
sim/signer_fw.py defines MAX_MSG = 4096 at line 60 and never uses it. The limit the firmware really applies is typed separately as the literal CMP #$10 on the high byte of the length in gen_main (line 1237), and the host helper envelope (line 1396) applies no limit at all. Give the limit one home: build the comparison at line 1237 from the constant (its high byte, with a build-time error if the constant is not a whole number of 256-byte pages, since the test only looks at the high byte and a zero low byte), and use the same constant for a length check in envelope; or delete line 60 if the literal is to stay. To confirm, run grep -c 'MAX_MSG' sim/signer_fw.py in the repository root: it prints 1 today and must print at least 3 when the constant is used (or 0 when it is deleted); the SHA-256 of build()[0] must be unchanged, and the existing refusal of a 4,097-byte length in tests/test_signer.py must still pass. Not compiled or run.
sim/signer_fw.py:90fe = FE()
The slot allocator fe in sim/signer_fw.py is one module-level object (line 90) shared by the generator, the test harness and the tests, and its __call__ (lines 82-87) creates a new 32-byte slot for any name it has not seen. A misspelt slot name therefore gets a fresh unrelated buffer instead of an error, and the memory map depends on which caller asked first. Make the map fixed data: after the registrations at lines 92-101, freeze the allocator so that a call with an unknown name raises KeyError listing the known names; every name the generator functions use is registered in those lines. A cleaner alternative is to create the allocator inside build() and pass it to the generator functions, returning the finished map to the harness. To confirm, add a test that fe("NO_SUCH_SLOT") raises KeyError, and a test that the address of every slot is the same whether the harness or the generator is used first. Not compiled or run.
sim/signer_fw.py:993 g(f"LDA {T1w + i}", "ADC (KPTR),Y", "STA " + str(T1w + i), "INY") if False else None
In gen_sha512 in sim/signer_fw.py the loop at lines 992-993 ends in "if False else None", so it never emits anything; the addition of the round constant it describes is emitted by the next block at lines 995-997. Delete lines 992-993. The statement just before them, line 991, does emit two instructions (LDY #0 and CLC) that the block at line 995 repeats immediately, so that pair is redundant in the ROM as well; removing it changes the image and lowers the cycle count of every SHA-512 round, so decide separately whether to remove it and, if so, re-measure the figures quoted in the documents. To confirm, run grep -c 'if False else None' sim/signer_fw.py in the repository root: it prints 1 today and must print 0; deleting lines 992-993 alone must leave the SHA-256 of build()[0] unchanged, and the SHA-512 boundary test in tests/test_signer.py must pass in either case. Not compiled or run.
sim/signer_fw.py:728 g("LDA BK", "STA T0", "ASL A", "CLC", "ADC T0", "ASL A", "ASL A", "STA T1", # BK*12 (high bytes / 64)
In the base_mult generator in sim/signer_fw.py, lines 728-729 emit instructions that compute BK*12 into T1 and clear T0, and lines 731-732 then overwrite T1 with BK*3, which is the value the table pointer really uses; T0 is written again before anything reads it. The first sequence is dead ROM code executed on every pass of the inner loop, and its comment describes a calculation the design does not use. Delete lines 728-729 and keep the comment at line 730 as the description of the pointer arithmetic. The image and the cycle count of base_mult change, by the same amount for every input, so re-measure any quoted cycle figures. To confirm, run grep -cF 'BK*12' sim/signer_fw.py in the repository root: it prints 1 today and must print 0; test_fixed_base_multiplication and the trace-equality tests in tests/test_signer.py must still pass. Not compiled or run.
sim/signer_fw.py:804def gen_prod64(g):
The constant-time row multiply exists three times in sim/signer_fw.py. gen_prod64 (lines 804-833) emits the same instructions that _gen_rowmul (lines 472-501) emits for a length of 32, and build_aks (lines 285-300) repeats the loop that builds the table of shifted copies a third time. A correction to the constant-time multiply would have to be made in each copy. Replace the body of gen_prod64 with a call to _gen_rowmul for the name prod64 and the length 32, and move the loop that builds the shifted copies into one helper that both _gen_rowmul and build_aks call, with the buffer length as its parameter. To confirm, record the SHA-256 of build()[0] before the change and check that it is identical afterwards, which shows the emitted code did not change, and run the multiply and scalar tests in tests/test_signer.py. Not compiled or run.
sim/emu65.c:125static Ent T[256]; static int inited = 0;
The opcode table T in sim/emu65.c is a file-level array (line 125) filled on first use: emu_reset and emu_run each call init() when the flag inited is 0 (lines 389 and 401), and init() first overwrites all 256 entries with NOP (line 142) before filling them in, with no lock. Python releases its interpreter lock while a ctypes call runs, so a second thread that makes its first call while another thread is executing can make the running emulator see a table that is half built. Remove the shared mutable state: either write the table out as a static const array so nothing is built at run time, or export init as a function that lib() in sim/emu.py (lines 34-45) calls exactly once, under a threading.Lock that also guards the creation of the module-level _lib, before any Machine can run, and delete the two lazy calls. To confirm, run grep -c 'if (!inited) init();' sim/emu65.c in the repository root: it prints 2 today and must print 0; and add a test that starts several threads which each create a Machine and run the same short program and asserts that all finish with the same registers and cycle count. Not compiled or run.
tools/fetch_klaus.sh:7git clone -q --depth 1 https://github.com/Klaus2m5/6502_65C02_functional_tests third_party/klaus
tools/fetch_klaus.sh clones the default branch of the upstream test-ROM repository at line 7 with no fixed revision and no check of what arrived, and tests/test_emu.py lines 11-12 then assert exact end addresses and cycle counts that are true for one particular build of those ROMs only. Pin the input: fetch one specific commit, chosen and recorded in the script by the owner (a branch or tag name is not enough because it can move), and after the download compute the SHA-256 of the two files named in tests/test_emu.py lines 11-12 under third_party/klaus/bin_files and compare them with expected values written in the script; stop with a non-zero exit code and a message on any difference, and print the commit that was used. The expected hashes must come from a copy the owner has already verified, the one that produced the numbers in tests/test_emu.py, and not from whatever the script has just downloaded. If no integrity check is wanted, say so in the header comment at lines 2-3. To confirm, run grep -c 'sha256' tools/fetch_klaus.sh in the repository root: it prints 0 today and must print at least 1; then change one byte of a fetched .bin file, run the check step again and observe that the script stops with an error. Not compiled or run.
tests/test_emu.py:103self.assertEqual(m.cycles, cyc) self.assertEqual(m.m.pc, core.pc) self.assertEqual(bytes(m.m.mem[:0x7F00]), bytes(mem[:0x7F00]))
The docstring of test_signer_prefix_identical_on_both_cores in tests/test_emu.py (lines 61-62) claims identical cycle-by-cycle progress and memory on the Python core and the C emulator, but the assertions at lines 103-106 compare only the final cycle count, the final program counter and the RAM below $7F00 after 300,000 cycles; the registers A, X, Y, S and the status flags are never compared, and the I/O stand-in on the Python side (lines 89-98) models only the message lock, so the emulator's result lock, fault latch and write blocking are not cross-checked at all. Either widen the test or narrow the claim. To widen it, advance the C emulator one instruction at a time with run(max_cycles=1), which executes exactly one instruction, and compare the program counter, A, X, Y, S, the flags and the cycle count with the Python core after every instruction, stopping at the first difference with the address in the message; then extend the Python-side stand-in to the result lock, the fault latch and blocked writes and run a sequence that triggers them on both sides. To narrow it, reword the docstring to say that the final cycle count, program counter and RAM agree. To confirm the widened test, change one flag update in a scratch copy of the C source and observe that the test fails at the first instruction affected. Not compiled or run.
sim/checks.py:25 if net is None:
continue
erc in sim/checks.py skips every pin that has no net at lines 25-26, and the supply checks at lines 27-30 come after that skip, so a part whose supply or ground pin is not connected at all passes the electrical check; only a supply pin wired to the wrong net is reported. Before the skip at line 25, add a test for the roles vcc and gnd with no net and append an error such as "<part> pin <n>: supply pin left unconnected"; decide in the same edit whether the MAX7219 supply pin, which carries the role pwr_sw (sim/parts.py line 756), is to be covered too. Then add a negative control to the tests: build a small Simulator holding one gate package created without its pin 14, run erc on it and assert that the error list names that part and pin; without such a test the check is never shown to fail. To confirm, that new test must fail on the present code and pass after the change, and the existing test_erc_clean in tests/test_static.py (line 97) must still pass on the full board. Not compiled or run.
sim/checks.py:124 min_gap = min_gap_change = float("inf")
handoff_stats in sim/checks.py starts both minimum gaps at infinity (line 124) and returns them unchanged when the interval list holds fewer than two entries, and contained (lines 157-165) returns an empty list for an empty input; the tests in tests/test_bus.py then pass on nothing, because assertGreater against infinity (lines 70, 73 and 100) and equality with zero over an empty list (lines 76-87) both succeed when no bus activity was recorded. Make the population visible and required: return the number of gaps examined from handoff_stats beside the existing intervals count (line 134), and in measure in sim/handoff.py add to the result the number of P_D and C_D intervals and gaps and the number of RD_WIN_N low intervals, write-buffer intervals and RWB_CYCLE edges that were examined (lines 18-42 and 62-69). In TestHandoff assert that each of these counts is greater than zero and that the minimum gaps are finite before comparing them. To confirm, add a test that calls handoff_stats on an empty list and on a single interval and asserts a gap count of 0, and check that the new count assertions fail when measure is given a window in which the CPU never runs. Not compiled or run.
sim/corners.py:1"""Deterministic worst-case delay corners for specific timing races."""
sim/corners.py calls its corners "deterministic worst-case" (line 1), but read_window_trailing_edge (lines 4-21) and read_window_six_state_fix (lines 24-27) fix only some of the delays on the racing paths: the clock-to-output delays of the phase flip-flops U6 and U45 and the skew between their Q and /Q outputs (keys ("q", i, False) and ("qn_skew", i, False), drawn at sim/parts.py lines 203-205) are still drawn at random from the seed, and brownout_write_corner sets the skew to 0.0 at line 37 although the model allows plus or minus QQN_SKEW (sim/timing.py line 33). The owner must choose. Either make the corners complete: for every part on the two racing paths set each delay key to the extreme that lengthens the overlap, including the U6 and U45 keys above and the adverse skew sign, working out the direction per path; or keep the partial corners, change the docstrings to say which delays are fixed and which stay random, and run the tests that use them (tests/test_bus.py lines 125-136, which use seed 1 only) over a range of seeds, describing the result as statistical. To confirm the first option, run the corner tests over at least twenty seeds and assert that the measured overlaps are identical for every seed; to confirm the second, the tests must loop over the seeds and the documents must state the number of seeds. Not compiled or run.
sim/corners.py:13 p["U10"]._delays[("tpd", 8)] = 30.0 # HCT00 max
The corner functions in sim/corners.py set delays by writing keys into a part's delay table, and nothing checks that a key is ever used. One of them is not: line 13 sets the delay of U10 output pin 8, but in the default (six-state) build that pin is unconnected (sim/board.py lines 153-154) and the gate model skips outputs without a net (sim/parts.py line 121), so in read_window_six_state_fix the override does nothing and the corner rests on the U18 key at line 27 alone. Record in Part.dly (sim/parts.py lines 42-48) which keys are requested, add a helper that, after a run, reports every overridden key that was never requested, and call it from the tests that apply a corner (tests/test_bus.py lines 125-136 and tests/test_brownout.py). In read_window_six_state_fix apply only the overrides that exist in that build instead of inheriting the U10 pin 8 one. To confirm, first add the helper and the check alone and observe that the six-state corner test fails naming U10 and key ("tpd", 8); then correct the corner and observe that the same test passes. Not compiled or run.
sim/parts.py:550en = (ce == 0 and oe == 0 and we == 1)
The SRAM model decides whether it drives the data bus with en = (ce == 0 and oe == 0 and we == 1) at sim/parts.py line 550, so an unknown level on chip enable, output enable or write enable counts as "not driving" and the outputs are released, while the EPROM model in the same file treats an unknown enable as driving (lines 601-603). A bus fight hidden behind an undetermined RAM enable is therefore never reported. In SRAM62256.evaluate distinguish three cases: definitely driving (the present condition), definitely not driving (ce is 1, or oe is 1, or we is 0), and possibly driving (anything else, which means at least one of the three is unknown). In the third case drive unknown data on all eight data pins, so the contention check in sim/engine.py (lines 113-120) sees the RAM as a possible driver, and include that third state in the remembered signature at line 551 so that a change from unknown to known is not skipped. To confirm, add a test with a small simulator in which the RAM chip enable is left unknown while another part drives the data lines and assert that a contention violation is recorded, and that none is recorded when chip enable is a definite 1. Not compiled or run.
sim/analog.py:202q1_base_ma=ib, q1_beta_forced=peak / ib)
display_interface in sim/analog.py (lines 194-202) computes q1_beta_forced, the ratio of the display peak current to the base current of the supply switch Q1, but never compares it with anything, and the only test of it, tests/test_static.py line 146, asserts that it is greater than zero, which cannot fail. Turn the figure into a check: add to the DATASHEET table (line 12) the minimum current gain of the fitted transistor at this collector current, taken from the BC327-25 datasheet named at spec.md line 139, choose the overdrive factor the design wants for saturation, and return a pass flag and the remaining margin (forced gain against minimum gain divided by the overdrive factor). The values are for the owner to read from the datasheet; this fix names none. Then change the test to assert the pass flag, and add a second assertion that the flag turns false when display_interface is called with a much larger r_base, which shows the check can fail. Review the tests of power() and supervisor_margin() at tests/test_static.py lines 123-136 in the same way, because they compare the code with the same constants it was written from. Not compiled or run.
wiring/WIRING.md:16- Physical connectivity vs schematic: 0 shorts, 0 opens.
wiring/WIRING.md is a generated file that is committed together with its own verification verdict (lines 14-20, for example "0 shorts, 0 opens" at line 16), and nothing checks that the committed text still matches what the generator produces from the current spec and layout code: no test refers to WIRING.md, wiring.csv or the function that writes them. Add a test, for example in tests/test_breadboard.py, that calls layout.generate() and layout.write_docs with a temporary directory as the output (the way cmd_wiring does at sim/__main__.py lines 143-144) and compares the two files it writes byte for byte with the committed wiring/WIRING.md and wiring/wiring.csv, failing with a message that tells the reader to run python3 -m sim wiring and commit the result. An alternative is to write a hash of the generator's inputs into the header of WIRING.md and have a test compare it with the current inputs. To confirm, change one digit in the committed WIRING.md and observe that the new test fails, then restore it; grep -rn 'write_docs' tests in the repository root prints nothing today and must list the new test. Not compiled or run.
sim/layout.py:699a(f"- Section 3.2 / 6.5 limits (PHI2 segment ≤50 mm, P_D ≤320 pF, C_D ≤150 pF): "
The three layout limits are typed twice in sim/layout.py: as numbers in the checks of harness_checks (50 mm at line 638, 320 pF at line 640, 150 pF at line 642) and again as text in the report line that write_docs emits at line 699. The wire-length formula has the same split: the factor 1.15 and the 10.0 mm in wire_mm at line 80 are restated in prose as "15 % slack + 10 mm" at line 692. Define each value once as a named constant beside the other layout constants at line 37, use the constants in the comparisons and in their messages, and build the two report sentences from the same constants with f-strings, so the report always states the limits that were applied. To confirm, run grep -c '320' sim/layout.py in the repository root: it prints 3 today and must print 1 (the constant); then change one constant temporarily and check that both the verdict and the wording of the generated WIRING.md follow it. Not compiled or run.
U4 stays on for one remaining master period, Section 5.5 and the 6.5 table imply two.spec.md:438RWB is stable from the PHI2-low phase before the window and does not change inside it, so U4 enables cleanly at the PHI2 rise and disables at the fall. The CPU's write data appears at C_D within tMDS of the rise and is passed to P_D; RAM_WE_N and the port strobes end one master period later with that data valid, and U4 stays on for the remaining master period.
The closing sentence of Section 6.3 at spec.md line 438 says that the write strobes end one master period after the PHI2 rise "and U4 stays on for the remaining master period". With the six-state generator PHI2 is high for three master periods (EARLY, MID and LATE): Section 5.5 states at line 354 that the write strobes end two master periods before Q_A falls, and the table in Section 6.5 shows U4 driving P_D through both MID and LATE (lines 482-483). The sentence still carries the count of the earlier four-state design. Change it to say that U4 stays on for the remaining two master periods, MID and LATE. To confirm, run grep -c 'for the remaining master period' spec.md in the repository root: it prints 1 today and must print 0, and the corrected sentence must agree with line 354 and with the table rows at lines 481-483. Not compiled or run.
U18, the only source of RD_WIN_N, so its own checks cannot pass at that stage.spec.md:10463. CPU, ROM and bus interface. Fit U1/U3/U4/U44/U8–U13, both sets of pull-ups and bypasses. Program/read back the diagnostic image. Check reset-vector reads at $FFFC/$FFFD and fetches at $8000. Then run the bus-handoff checks of Section 11.2 before adding SRAM.
Step 3 of the wiring sequence at spec.md line 1046 fits U1, U3, U4, U44 and U8-U13 and then asks for the bus-handoff checks of Section 11.2, whose first item measures RD_WIN_N at U18 pin 6 (line 1059). U18 is the only source of RD_WIN_N (line 660; line 526 says gate 3 of U10 no longer produces it), and the sequence does not fit U18 until step 5, "Populate U14-U19" (line 1048). At step 3 the output enables of ROM and RAM and an input of U11 therefore have no driver, and the step's own checks cannot pass. Add U18 to step 3, say how the inputs of its display gate are to be held at a defined level while U16 and the lock board are still absent (line 655 already gives the strap for pin 13) and that those straps are removed in the later step, and change step 5 to the parts that remain. Then walk every step of the sequence against the netlist in the same way: for the set of parts fitted at each step, every input must have a fitted source or a named temporary strap. To confirm, check that U18 is named in step 3, and run the electrical rule check of the simulator on a netlist reduced to the parts of each step, which must report no input without a source. Not compiled or run.
README.md:42Requires Python 3.9 or later and a C compiler (`cc`) for the fast emulator. `python3 -m sim sign` and its tests also need the `openssl` CLI.
README.md line 42 gives "Python 3.9 or later" as the minimum interpreter, and that sentence is the only place in the repository where a Python version is stated. Check the status of that release line on the Python project's own release page and, if it is no longer supported there, raise the stated minimum to a line that is; change the sentence at line 42, and add a version check at the top of main() in sim/__main__.py (line 212) that compares sys.version_info with the same minimum and exits with a clear message, so the README and the program cannot disagree. This audit read only the documented minimum: it did not read the Python project's support page and did not observe which interpreter, C compiler or openssl is installed where the simulator runs. To confirm, run python3 --version on the machine that runs the simulator and the test suite and check that it is at or above the minimum now written at line 42. Not compiled or run.
FINDINGS.md:99This was verified in simulation: the fault latch still works with the split clock (`test_phi2_buffer_variant_keeps_fault_latch_working`).
FINDINGS.md line 99 supports the F10 fix with a test named test_phi2_buffer_variant_keeps_fault_latch_working, and no file under tests/ defines a test of that name. Replace the name with the tests that do exercise the separate fault clock on the current netlist, which are test_result_lock_fault_on_separate_fault_clock (tests/test_breadboard.py line 110) and test_finding_phi2_stub_rev03_fixed_in_rev04 (tests/test_breadboard.py line 61), after reading both to check that they assert what the sentence claims (the fault latch still sets when U38 is clocked from PHI2_FAULT). If neither asserts that, add a test under the cited name instead and keep the sentence. To confirm, run grep -rn 'test_phi2_buffer_variant' . in the repository root: it lists one line today (FINDINGS.md line 99) and afterwards must list either nothing or the sentence plus a definition under tests/. Not compiled or run.
FINDINGS.md:219The test ROM is test firmware only. No signing firmware exists to verify.
FINDINGS.md line 219 states "No signing firmware exists to verify", which the section "Signing firmware verification" of the same file (lines 147-159) and tests/test_signer.py contradict. Delete that sentence, or replace it with one that keeps the intended limit, for example that the boot and scenario ROM is test firmware only and that the signing firmware in sim/signer_fw.py is covered in its own section, with the items listed at line 159 not covered. To confirm, run grep -c 'No signing firmware exists' FINDINGS.md in the repository root: it prints 1 today and must print 0 afterwards. Not compiled or run.
FINDINGS.md:1342. Use a table-based multiply for verification only, which handles only public data.
The options list at FINDINGS.md lines 132-136 still offers work the same section reports as done: option 2 (a table multiply for verification only, line 134) is described as implemented at line 112, and option 3 (a dedicated squaring routine, line 135) at line 111. Remove lines 134 and 135; the two options that remain (a faster clock and dropping the duplicate signature) already appear in the list at lines 119-123, so the second list can be deleted entirely and line 119 left as the single list of open decisions. In the same edit make the multiplication figure agree within the section: line 126 says about 155k cycles and line 115 says 133k. To confirm, run grep -c 'Add a dedicated squaring routine' FINDINGS.md in the repository root: it prints 1 today and must print 0, and each remaining option must describe something not listed under lines 110-115. Not compiled or run.
FINDINGS.md:117`derive` and `sign` produce identical traces and cycle counts for different seeds (`TestConstantTime`), which demonstrates no secret-dependent branches or memory addresses.
FINDINGS.md line 117 says the identical traces "demonstrate" that there are no secret-dependent branches or memory addresses, but the test behind it, test_derive_and_sign_traces_independent_of_seed in tests/test_signer.py (lines 155-160), compares two seeds on one message for the routines derive and sign only. Choose one. Narrow the sentence to what was run: for two seeds and one message, derive and sign gave the same bus-address trace and cycle count, and no difference was observed. Or widen the test first: loop over many seeds including edge values (all zero bytes, all 0xFF bytes, random ones) and over several message lengths, keep the equality assertion, and then state the number of seeds and messages in the sentence. Either way the sentence must name the routines, the seeds and the messages it rests on and must not use an absolute word. To confirm a widened test, insert a deliberate seed-dependent branch into derive in a scratch copy and observe that the test fails; to confirm the wording, run grep -c 'which demonstrates no secret-dependent' FINDINGS.md in the repository root, which prints 1 today and must print 0. Not compiled or run.
tests/test_io_hygiene.py:45m.run(stop=syms["done"], max_cycles=20_000_000)
test_test_firmware_scenarios_write_only_canonical_ports in tests/test_io_hygiene.py runs each scenario with m.run(stop=syms["done"], max_cycles=20_000_000) at line 45 and ignores the value run returns. A scenario that hangs, traps or runs out of cycles before reaching done has then written only some of its I/O addresses, and the subset assertion at line 47 passes on that partial set. Assert the reason for stopping: wrap the call in self.assertEqual(..., Machine.STOP), the value the emulator returns when the stop address is reached, in the same way test_mirror_store_is_detected checks for Machine.STP at line 55. To confirm, temporarily lower max_cycles to 10 and observe that every sub-test now fails on the new assertion, then restore the value. Not compiled or run.
tests/test_bus.py:60cls.r = measure(dict(seed=11), scenario="ram")
FINDINGS.md line 204 says the bus-handoff results were "checked across Monte Carlo seeds at 127, 380 and 890 kHz", but TestHandoff in tests/test_bus.py takes all its measurements from one call, measure(dict(seed=11), scenario="ram") at line 60, which is one seed at the default clock; the Monte Carlo test at lines 43-52 checks only that no violation occurs and that one byte is copied. Choose one. Widen the test: run measure for every clock corner and for several seeds, passing master_hz and seed in the keyword dictionary, and apply the same assertions to each result inside a sub-test; the hold assertion at line 84 compares with a fixed 2000 ns and must become a multiple of the master period so it holds at every clock. Or narrow the sentence in FINDINGS.md to what was measured: gaps and windows for one seed at 380 kHz, violations for eight seeds at three clocks. To confirm the first option, run the widened class with the wiring mutation oe_from_rwb and observe that it fails at every corner, then without it and observe that every sub-test passes. Not compiled or run.
tests/test_signer.py:170for sig in (good, bytes(64)): # pass and fail paths
FINDINGS.md line 112 says the multiply dispatch vector is switched back to the constant-time routine "on every exit path" of verification, and test_verify_restores_constant_time_multiply in tests/test_signer.py checks two of those paths (line 170): a valid signature and an all-zero signature. The verify routine has further exits that the test does not take: the rejection of an S value that is not below the group order (sim/signer_fw.py lines 1123-1124) and the rejection of a public key that does not decode to a curve point (line 1151). Add both to the loop: a signature whose S half has the group order added, as line 132 of the same file already constructs, and a run in which the public-key bytes are replaced by a value with no valid x coordinate, found once with the reference implementation and kept as a constant; after each, assert that the vector equals the address of fe_mul_ct. Or narrow the sentence in FINDINGS.md to the paths tested. To confirm, change one exit in a scratch copy of the generator so that it returns without restoring the vector and observe that the corresponding new case fails. Not compiled or run.
sim/firmware.py:34 r = bytearray(256)
r[0:8] = b"DTS02OUT"
The formats shared between the firmware and the host code are written out separately on each side. The result record with its DTS02OUT magic, version and offsets is built field by field in result_record (sim/firmware.py lines 31-45) and again in expected_record in sim/signer_fw.py (line 1403), and the magic is typed a third time for the firmware at sim/signer_fw.py line 1353; the envelope magic appears at sim/signer_fw.py lines 1351 and 1396; the simulation mailbox (magic and address $3F80) at sim/firmware.py lines 69 and 676, sim/runner.py lines 35-37 and tests/test_io_hygiene.py line 43; and the CRC-32 polynomial at sim/firmware.py line 53 and sim/signer_fw.py line 1312. Create one small module that neither firmware file owns, holding the magics, the version, the field offsets, the mailbox address and the polynomial, together with the one Python builder of the result record; have both generators import it and substitute the values into their assembly text, and make result_record a call to that builder with the public test vector. To confirm, first add a test that result_record() equals expected_record(b"", RFC_A, RFC_SIG), which should pass today and guards against drift; after the change grep -rn 'DTS02OUT' sim in the repository root, which lists 3 lines today, must list 1. Not compiled or run.
sim/runner.py:27 self.cpu_period = self.sim.master_per_cpu * 1e9 / kw.get("master_hz", 380e3)
The default master clock of 380 kHz is typed in three places: as the default of build in sim/board.py (line 36), as the fallback kw.get("master_hz", 380e3) that Bench uses to compute its clock period in sim/runner.py (line 27), and as the default of --freq in sim/__main__.py (line 237). The value in sim/board.py is the one the simulated oscillator really runs at (line 122), so it governs; the other two only agree with it by being typed the same. Give the value one owner: define one named constant for the default in sim/board.py, use it as the default of build and of the --freq option, have build record the frequency actually used on the simulator object it returns, and let Bench compute cpu_period from that recorded value instead of looking in its keyword arguments. To confirm, run grep -rnE '380e3|default=380' sim in the repository root: it lists 3 lines today and must list 1 (the constant); and add a test that changes the constant temporarily and asserts that a Bench built without master_hz reports a clock period that follows it. Not compiled or run.
sim/solana.py:21 raw = n.to_bytes((n.bit_length() + 7) // 8, "big") if n else b""
return bytes(len(s) - len(s.lstrip("1"))) + raw
b58decode in sim/solana.py (lines 17-22) returns however many bytes the text decodes to and states no expectation about the length, yet all three callers need exactly 32 bytes: the constant at sim/solana.py line 34 and the --to and --blockhash options at sim/__main__.py lines 165-166, which carry text typed by the operator. A wrong-length value from those options is built into the message and signed without any error. Give the helper the check: add an optional length parameter to b58decode and raise ValueError, stating the decoded and the expected length, when it is given and the result differs; raise ValueError naming the character for a character outside the alphabet instead of the generic error from B58.index at line 20; and pass length=32 at the three call sites. To confirm, add tests that b58decode of a 31-byte value with length=32 raises ValueError, that b58decode(b58encode(bytes(32)), length=32) returns 32 zero bytes, and that a text containing the character 0 raises ValueError naming it; grep -rn 'b58decode(' sim in the repository root lists the definition and three calls today, and each call must then carry the length argument. Not compiled or run.
sim/__main__.py:201 with open(os.path.join(a.out, name), "wb") as f:
f.write(img)
h = hashlib.sha256(img).hexdigest()
cmd_roms (sim/__main__.py lines 188-209) writes the images that will be burned and their SHA256SUMS without checking what it writes: the hash at line 203 is computed from the bytes in memory, not from the file, and the diagnostic image is not compared with the hash the spec publishes. Before the loop at line 200, compare specdoc.sha256(specdoc.diagnostic_rom()) with specdoc.expected_diagnostic_hash(), as cmd_check already does at line 49, and return a non-zero exit code without writing anything when they differ. After each file is written, reopen it, hash the bytes read back, and refuse to list it in SHA256SUMS unless that hash equals the one computed from memory and the length is 32,768. Also print with the test ROM that it is built with zero_end_page=0x40 (line 196), because the simulated scenarios use the default build from sim/runner.py line 13, so the image burned is not byte-identical to the image simulated. To confirm, add a test that replaces specdoc.expected_diagnostic_hash with a function returning a wrong value and asserts that cmd_roms returns non-zero and leaves the output directory empty, and after a normal run check the files with sha256sum -c SHA256SUMS inside the output directory. Not compiled or run.
sim/firmware.py:651CMP #3 ; accept a key after 3 identical scans, once
The two key-debounce loops in the boot ROM source say that a key is accepted "after 3 identical scans, once" (sim/firmware.py lines 240 and 651), but the counter KSTAB is a single byte that is incremented on every identical scan (INC KSTAB at lines 238 and 649) and compared with 3, so while a key is held the counter wraps and reaches 3 again after 256 further scans, and the key is accepted a second time. Make the code keep the promise: in both loops stop counting once the key has been accepted, for example by incrementing KSTAB only while it is below 4, so that it passes through 3 once and then stays at 4 until the scanned value changes and the existing STZ KSTAB at lines 236 and 647 re-arms it. Widening the counter would only move the repeat later. The number of scans is a count, not a time: the debounce time it gives depends on the measured clock and must be calibrated on the hardware. To confirm, add a test to the keypad tests in tests/test_system.py that holds one key for more than 256 scan passes in the keypad-echo scenario and asserts that exactly one digit has been shifted into the display. Not compiled or run.
sim/emu.py:92on = self.m.st[c] & 1
The MAX7219 display driver is modelled twice and the two models differ. The gate-level model in sim/parts.py (class MAX7219, lines 746-858) handles the decode, intensity, scan-limit, shutdown and display-test registers; the fast emulator's model, gpio_write in sim/emu65.c (lines 62-86) with Machine.display_masks in sim/emu.py (lines 87-105), handles only the digit, shutdown and decode registers, and display_masks ignores even the decode bit it stores. The conversion from register bits to segment bits is written out in both sim/parts.py (lines 853-856) and sim/emu.py (lines 100-103). The owner must choose. Either remove the second model: delete display_masks and the fields sr, st, prev_gpio and mxdig from both declarations of the shared structure (sim/emu.py lines 13-28 and sim/emu65.c lines 15-33) together with mx_reset and the shifting code in gpio_write, keeping only gpio and gpio_writes. Or keep it and give the register meaning one owner: one shared Python function for the segment conversion used by both MAX7219.lit and display_masks, the same registers handled in the C code, and a test that runs the font scenario on both models and compares the sixteen digits. To confirm removal, run grep -rn 'mxdig' sim in the repository root: it lists 5 lines today and must list none; to confirm the second option, the comparison test must pass and must fail when one model's handling of the shutdown register is altered. Not compiled or run.
sim/emu.py:44assert _lib.emu_sizeof() == ctypes.sizeof(M), "struct layout mismatch"
The emulator state is one record declared in two languages, the ctypes structure M in sim/emu.py (lines 13-28) and typedef struct M in sim/emu65.c (lines 15-33), and the only guard that they agree is a comparison of total size in an assert at sim/emu.py line 44. Two fields of equal size swapped, or two changes that cancel out, pass that check, and the assert vanishes under python -O. Export from the C file a function that reports the offset of every field (offsetof from stddef.h, in the order of the declaration), and in lib() compare each reported offset with the offset attribute of the matching ctypes field for every name in M._fields_; raise a RuntimeError that names the first field that differs, and keep the size comparison as a second explicit check instead of an assert. A longer-term alternative is to generate one declaration from the other. To confirm, add a test that builds a copy of the ctypes structure with two same-sized fields exchanged (for example a and x), runs the comparison against it and expects the error naming that field; the size-only check passes such a copy. Not compiled or run.
tests/test_io_hygiene.py:43m.load(0x3F80, b"DTS02SIM" + bytes([num]))
The simulation mailbox that tells the test ROM which scenario to run (the eight magic bytes at $3F80 followed by the scenario number) is assembled by hand in two places: Bench.set_scenario writes it byte by byte in sim/runner.py lines 35-37, and tests/test_io_hygiene.py line 43 builds the same bytes inline for the fast emulator. The format belongs to the test ROM, which reads it at sim/firmware.py lines 216-223. Add one function next to SCENARIOS in sim/firmware.py that takes a scenario name and returns the mailbox address and the bytes to store there, and use it at both sites; if more tests need it on the fast emulator, give Machine a set_scenario method that calls the same function. To confirm, run grep -rn 'DTS02SIM' sim tests in the repository root: it lists 4 lines today and afterwards must list only lines inside sim/firmware.py; add a test that the bytes returned for each scenario make the ROM reach that scenario's code on the emulator. Not compiled or run.
sim/parts.py:839 if not self.powered or self.shutdown:
return [0] * 8
if self.test:
MAX7219.lit in sim/parts.py tests shutdown before display test: line 839 returns a dark panel when the part is unpowered or in shutdown, and only then does line 841 look at the test flag, so a driver that is in shutdown with display test set is shown dark. Check the display-test section of the MAX7219 datasheet for which of the two has priority; if display test overrides shutdown, reorder the method to test power first, then self.test, then self.shutdown, and keep that order in this one method only. The second display model, in the C emulator, does not know the display-test register at all: gpio_write in sim/emu65.c handles register addresses 1-8, 0xC and 0x9 only (lines 80-82), and display_masks in sim/emu.py (lines 87-105) reads only the shutdown bit; either add register 0xF there with the same priority or say in the comment at sim/emu65.c line 51 that display test is not modelled. To confirm, add a unit test that powers a MAX7219, leaves it in shutdown, latches the display-test register with bit 0 set and asserts that lit() returns eight values of 0xFF, and a second that clears the test bit and asserts eight zeros. Not compiled or run.
sim/signer_fw.py:1327 g(" .byte " + ", ".join(f"${x:02X}" for x in b[i:i + 16]))
The helper that turns a byte string into .byte lines of assembly text is written twice: as bytes_ inside gen_data in sim/signer_fw.py (lines 1325-1327) and as _bytes in sim/firmware.py (lines 58-60), with the same formatting of sixteen values per line. Put one such function next to the assembler in sim/asm.py, which both generators already import, have it return the text, and call it from both places; delete the two local copies in the same edit. To confirm, run grep -rnF 'join(f"${x:02X}"' sim in the repository root: it lists 2 lines today and must list 1, and the SHA-256 of the signing image and of the boot image must be the same before and after. Not compiled or run.
sim/emu.py:38 if not os.path.exists(LIB) or os.path.getmtime(LIB) < os.path.getmtime(SRC):
subprocess.check_call(["cc", "-O2", "-shared", "-fPIC", "-o", LIB, SRC])
lib() in sim/emu.py rebuilds the emulator library only when _build/_emu65.so is missing or older than emu65.c (line 38), and the compiler writes straight to the final file name (line 39). The decision ignores everything else the library depends on: the compiler flags in that command, the compiler and machine it was built with, and a build that another process is writing at the same moment; a checkout copied from another host or a changed flag therefore loads a stale library, and two parallel test runs can load a half-written one. Derive a key from the contents of emu65.c and the full compiler command (a SHA-256 of both), build only when no library for that key exists, for example by putting the key in the file name, and always compile to a temporary name in the same directory and move it into place with os.replace so that the final name only ever refers to a complete file. To confirm, change only the optimisation flag in the command and observe that a new build happens; run twice unchanged and observe that the second run does not compile; and start two processes at once on an empty _build directory and check that both load and run the same short program. Not compiled or run.
sim/parts.py:601 if ce == X or oe == X:
# unknown enable: conservatively drive unknown data
en = True
EPROM27256.evaluate in sim/parts.py turns an unknown chip enable or output enable into en = True at lines 601-603 and then remembers only (en, addr) as its signature at line 604. Two things follow. The comment says unknown data is driven, but the code schedules real ROM data at t_valid (lines 615-617), so an unknown enable ends as valid data after the access time. And when the enable later changes from unknown to a definite 0, the enable time is updated at lines 593-596 but the signature is unchanged, so the early return at lines 605-606 skips the rescheduling and the data timing still refers to the old moment. Make the signature cover every input that the skipped work depends on: store the enable as one of three states (off, on, unknown) together with the address; while the state is unknown drive X on all data pins and schedule no valid data; when it becomes on, recompute t_valid from the new enable times. To confirm, add a unit test with an EPROM whose chip enable starts unknown: the data pins must still be X after the access time has passed, and after chip enable goes to 0 they must become valid one chip-enable access time after that edge and not before. Not compiled or run.
sim/layout.py:328 L.sim_hole[("QSW", 1)] = L.items[-5]["leads"][0][0] # R_Q2B lead on DISPLAY_ON
generate in sim/layout.py finds the hole of the display switch input with L.items[-5]["leads"][0][0] at line 328, that is by counting five entries back from the end of the item list to reach the resistor R_Q2B placed at line 321. If a part is added, removed or reordered between lines 321 and 326, the index silently points at another part and the simulator input QSW pin 1 is mapped to the wrong hole. Select the part by what it is: keep the value returned by the L.part call for R_Q2B at line 321 in a variable, as line 326 already does for Q1, and take the first lead from it at line 328. To confirm, run grep -cF 'L.items[-5]' sim/layout.py in the repository root: it prints 1 today and must print 0, and add a test asserting that in the netlist returned by physical_netlist(generate()) the entry for ("QSW", 1) is the net DISPLAY_ON. Not compiled or run.
sim/layout.py:386 L.sim_hole[("RESET_RC_MODEL", 1)] = L.pin_hole[("U5", 6)]
Names that tie the modules together are typed as string literals wherever they are needed. The simulator-only part RESET_RC_MODEL, for example, is named in sim/board.py line 308 and again three times in sim/layout.py lines 386-388; the same holds for OSC, OSC_RC_NODE, U42, RESET_BTN and QSW (sim/layout.py lines 328-329 and 384-390), for net names used by sim/brownout.py, sim/handoff.py, sim/vcd.py and sim/__main__.py, and for the violation kinds created in sim/engine.py and matched in the tests. A part renamed in sim/board.py alone is not noticed: its entries in the layout table no longer match and Part.__init__ falls back to the schematic net (sim/parts.py line 30). Declare each shared name once, the part and net names in sim/board.py beside VCC and GND at line 22 and the violation kinds in sim/engine.py, and import the constants at every use; add a check that every part named in the layout table exists, so a mismatch is an error. To confirm, run grep -rn '"RESET_RC_MODEL"' sim in the repository root: it lists 4 lines today and must list 1, and repeat the search for each name that is moved. Not compiled or run.
sim/signer_fw.py:1041def gen_ed25519(g):
sim/signer_fw.py implements the whole signature scheme itself: field, group and scalar arithmetic, SHA-512 and the Ed25519 sign and verify flow (gen_field at line 220, gen_group at 594, gen_scalar at 768, gen_sha512 at 856, gen_ed25519 at 1041 and gen_verify at 1097). On this processor the hand-written code is the product, so replacing it with a library is not the remedy; the direction is to treat it as unreviewed cryptographic code until shown otherwise. Say so in the module docstring and in the README. Keep and extend the comparisons against independent implementations that the tests already make (the RFC 8032 vectors and the OpenSSL cross-check) with further published vectors and edge cases. State exactly which side-channel property is claimed, namely equal bus-address traces and cycle counts on the emulator for the inputs tested, and that nothing is claimed about power or electromagnetic leakage. Before any key that holds value is used, obtain an independent review of the generated code and record the SHA-256 of the reviewed ROM image so that the image burned can be shown to be the image reviewed. To confirm, the docstring and README must carry the statement, and the release notes must name the reviewed image hash; this cannot be confirmed by a test alone. Not compiled or run.
sim/__main__.py:168fw = Fw(double_sign=not a.single, verify=not a.no_verify)
cmd_sign builds the firmware with the second signature and the on-device verification switched off when --single or --no-verify is given (sim/__main__.py line 168, options at lines 224-225), and then prints the same summary as a full run, ending in "matches ...: True" at line 181, so output from a reduced build cannot be told from output of the full flow. Make the reduced state visible in cmd_sign: print one line per control stating whether it ran or was skipped, include the two states in the summary line at line 181, and return a distinct non-zero exit code when either control was switched off so that a script cannot take a reduced run for a full pass. As a stronger measure the owner can have the firmware built by F.build without a control mark that in its status byte or result record; that changes the record format and needs a decision against the spec. To confirm, add a test that captures the output of main(["sign", "--single"]) and of main(["sign"]) and asserts that the first contains the skipped line and returns the distinct code and the second does neither. Not compiled or run.
sim/firmware.py:706def boot_rom(zero_end_page=0x04):
boot_rom in sim/firmware.py defaults to zero_end_page=0x04 (line 706), which clears only $0000-$03FF at a fresh start, while its own docstring says the spec requires all of $0000-$3FFF to be cleared (0x40). A caller that does not think about the parameter gets the weakened image without saying so: the simulation bench (sim/runner.py line 13) and tests/test_io_hygiene.py line 36; only cmd_roms (sim/__main__.py line 196) and tests/test_cpu_core.py line 99 ask for the full clearing. Simply changing the default to 0x40 would break those two default callers, because both select a scenario through the mailbox at $3F80 (sim/runner.py lines 32-37 and tests/test_io_hygiene.py line 43) and the full clearing loop (sim/firmware.py lines 198-214) erases that mailbox before it is read at lines 216-223, so the ROM would fall through to the keypad menu, as the comment at tests/test_cpu_core.py line 107 records. Remove the default instead, so that every caller has to state which image it builds: make zero_end_page a required argument, pass 0x04 explicitly at sim/runner.py line 13 and tests/test_io_hygiene.py line 36 with a comment that the reduced clearing is what keeps the simulation mailbox alive and is not the image that is burned, and leave the two 0x40 callers as they are. Have the bench report that it runs the reduced image, and say in the docstring that scenario selection through the mailbox works only with the reduced image, while the burned image selects by keypad. To confirm, run grep -rn 'boot_rom()' sim tests in the repository root: it lists 3 lines today (two calls and the module docstring) and afterwards must list no call without an argument; add a test that calling boot_rom with no argument raises TypeError; and the scenario tests in tests/test_io_hygiene.py must still reach their stop address. Not compiled or run.
FINDINGS.md:177every net is routed as point-to-point jumpers (669 wires, 285 between boards)
FINDINGS.md line 177 restates the wiring totals as "669 wires, 285 between boards", which are the revision 0.4 numbers; the generated list wiring/WIRING.md line 14 now reads 28 DIP ICs, 439 wires and 169 between boards, and lines 200 and 201 of FINDINGS.md still say 43 DIPs and 43 rows although tests/test_static.py line 64 asserts 28. Stop retyping the counts: at line 177 refer the reader to the "Verification of this list" block of wiring/WIRING.md, which python3 -m sim wiring regenerates, or copy the figures from that block and name the command beside them; treat lines 200 and 201 the same way or mark them as revision 0.4 figures. To confirm, run grep -c '669 wires' FINDINGS.md in the repository root (prints 1 today, must print 0) and check that any count left in FINDINGS.md equals the one printed at wiring/WIRING.md line 14 after regenerating. Not compiled or run.
sim/emu.py:87def display_masks(self):
Machine.display_masks in sim/emu.py (lines 87-105) is the only way to read the display model of the fast emulator and nothing calls it, while FINDINGS.md line 171 states that this model "renders the same page as the gate-level board". No test in the repository makes that comparison. Either add it: a test that builds the boot ROM, writes the scenario mailbox for the font scenario into a Machine the way Bench.set_scenario does (sim/runner.py lines 32-37), runs it to the end of the scenario and asserts that display_masks() equals the list returned by Harness.display() for Bench(scenario="font"); or delete display_masks together with the sentence at FINDINGS.md line 171. If both display models stay, the conversion from register bits to segments should exist once and be used by both. To confirm, run grep -rn 'display_masks' sim tests in the repository root: it lists one line today (the definition) and must list at least two once the test exists, or none after deletion together with the corrected FINDINGS.md. Not compiled or run.
sim/cpu65c02.py:123def compare(self, reg, v):
Many methods carry a public name although only their own class calls them: in Core (sim/cpu65c02.py) the helpers rd, wr, nz, fetch, abs_, push, pull, ea, compare, adc, sbc, shift, branch_to and implied (lines 38-190 and 335-382), in Assembler (sim/asm.py) atom, try_eval and mode (lines 107, 122 and 129), and likewise Layout.landing in sim/layout.py and Net.tau_ns in sim/engine.py (line 89). Give each a leading underscore at its definition and at every call in one edit, as the repository already does for other internal helpers, so that the public surface of Core is run and step, which the tests call. Before renaming a name, search for it across sim and tests and report any use outside the defining class; methods of the same name on other classes, such as the out and inp methods of the part models, are not callers. To confirm, run grep -rnE '\.(compare|adc|sbc|shift|implied|branch_to|abs_)\(' sim tests in the repository root: it lists 13 lines today, all in sim/cpu65c02.py, and must list none after the rename; the test suite must still pass. Not compiled or run.
sim/parts.py:601 if ce == X or oe == X:
# unknown enable: conservatively drive unknown data
en = True
The read path of the two memory models in sim/parts.py is written twice: recording when chip enable and output enable went low, the remembered signature with its early return, the changed-address test and the computation of t_valid appear in SRAM62256.evaluate at lines 512-516 and 550-570 and again in EPROM27256.evaluate at lines 593-597 and 600-617, and the copies already disagree on unknown enables (the SRAM releases the bus at line 550, the EPROM drives at lines 601-603). First decide the one behaviour for an unknown enable; driving unknown data is the conservative choice because it lets the contention check see a possible driver. Then move the shared read path into the common base class _Memory (line 453) as one method that takes the enable state, the address and the part's timing figures, call it from both models, and delete both originals in the same edit, leaving in each subclass only what really differs (the write tracking of the SRAM, the VPP check of the EPROM). To confirm, run grep -c 'if sig == self.sig' sim/parts.py in the repository root: it prints 2 today and must print 1, and add a test that applies the same unknown chip enable to both models and asserts the same behaviour on the data pins. Not compiled or run.
sim/__main__.py:30kw["vcd"] = VCD(a.vcd)
The waveform file is opened in _bench_kw (sim/__main__.py line 30) for every sub-command that accepts --vcd, but it is closed in two separate places only, at line 95 in cmd_run and line 109 in cmd_diag; cmd_handoff (lines 114-122) opens it and never closes it, and cmd_race (lines 125-138) accepts --vcd, --freq and --rev03 and uses none of them. Give the file one owner: add __enter__ and __exit__ to the VCD class in sim/vcd.py (its close method is at line 48), or keep the opened writer on the parsed arguments and close it in a try/finally around the call fn(a) at line 245 in main; then delete the two close calls at lines 95 and 109 and keep only their "waveform written" messages. Add --vcd, --freq and --rev03 in the loop at lines 228-240 only for the sub-commands that read them, or pass _bench_kw(a) into cmd_race. To confirm, run grep -cF 'vcd.close()' sim/__main__.py in the repository root: it prints 2 today and must print at most 1 (the single owner) afterwards; add a test that runs handoff with --vcd into a temporary file and asserts the underlying file object is closed when main returns. Not compiled or run.
sim/cpu65c02.py:329self.stopped = True
Stopping is represented in several unconnected ways. In sim/cpu65c02.py the core sets self.stopped at line 329, which nothing reads, and then reports STP or WAI by raising UnknownOpcode at line 330; the CPU part catches that at lines 562-566 and records it as a cpu-halt violation, whereas the C emulator treats STP as a clean stop (halted = 2 at sim/emu65.c line 367). In sim/engine.py the cancelled flag of an Event is written directly by Simulator.drive at line 229. Give stopping one path: remove Core.stopped; raise a dedicated exception for STP and WAI instead of UnknownOpcode; and let the CPU part catch it separately and record a normal stop, with the reason, without adding a violation. Whether a STP executed on the board model should count as a violation is the owner's decision; the two models must give the same answer. For Event add a cancel() method on the class (sim/engine.py line 161) and call it at line 229. To confirm, add a test that runs a ROM ending in STP on the bench and asserts the chosen outcome (stop reason set, and a cpu-halt violation present or absent as decided), and check that the same ROM gives the matching halt reason on the C emulator. Not compiled or run.
README.md:42`python3 -m sim sign` and its tests also need the `openssl` CLI.
README.md line 42 lists the openssl command-line tool as a prerequisite without a version, although sim/solana.py calls openssl pkeyutl with the -rawin option at lines 84 and 100 and FINDINGS.md line 153 records OpenSSL 3.0 as the version the results were obtained with. Find in the OpenSSL documentation the first release whose pkeyutl accepts -rawin for Ed25519 keys and state that minimum at README.md line 42, consistent with FINDINGS.md line 153. In sim/solana.py put both subprocess calls behind one helper that fails with a clear error when the tool is missing or rejects the options, and change openssl_verify (lines 90-102) so that it returns False only for the outcome openssl reports for a bad signature and raises, with the captured error text, for every other non-zero exit; today any failure at line 102 is read as a bad signature. To confirm, put a stub named openssl first on PATH that prints an unknown-option error and exits with a failure code, then call openssl_verify: it must raise instead of returning False; and grep -n 'openssl' README.md in the repository root must show the minimum version on the prerequisite line. Not compiled or run.
sim/signer_fw.py:1254 g(f"{l}: LDA {ENV + 12},X", f"STA {META + 3},X", f"STA {S['EXPECT']},X", "DEX", f"BPL {l}")
In gen_main in sim/signer_fw.py the key that the derived public key is checked against is copied out of the input envelope (line 1254 stores the bytes at ENV+12 into EXPECT), and the comparison at line 1261 then tests the derived key against that copy. The expected key thus arrives over the same unauthenticated channel as the message, so the check only detects a wrong seed; spec.md line 982 requires an independently configured expected key that takes precedence over the envelope's copy. This is a design change: keep the envelope checks and the comparison at line 1261, and replace the source of EXPECT. Take the expected key from configuration that does not travel with the message, for example 32 bytes assembled into the ROM at build time or entered locally once that mechanism exists; refuse when the envelope's copy differs from the configured key; and refuse, without falling back to the envelope's copy, when no key is configured. To confirm, add a test in which the ROM is configured for one key while the envelope names a second key and the seed in RAM derives that second key: signing must be refused with no RESULT_LOCK, although today it would succeed; also re-run the existing wrong-key case and check every other path that reads EXPECT. Not compiled or run.
sim/parts.py:696self.period = 1e9 / freq_hz
Several constructors of the simulation accept values that cannot be valid. Oscillator.__init__ in sim/parts.py divides by freq_hz at line 696 with no check, and the value comes straight from the --freq option (sim/__main__.py line 237), so --freq 0 ends in a ZeroDivisionError and a negative value in an unrelated timeout. Net.tau_ns (sim/engine.py line 90) needs both the pull resistor and the capacitance but they are set separately. Assembler.__init__ (sim/asm.py line 51) does not bound org, size and fill. Machine.__init__ and Machine.load (sim/emu.py lines 56 and 70) copy into the 64 KiB memory with unchecked lengths. Validate at construction so an invalid object cannot exist: in Oscillator require freq_hz > 0 and 0 < duty < 1; set the pull resistor and capacitance of a net together and require both positive; in Assembler require org >= 0, size > 0, org + size <= 65536 and fill in 0..255; in Machine require an image of exactly 65,536 bytes and, in load, 0 <= addr and addr + len(data) <= 65536; raise ValueError naming the value in each case, and give --freq an argparse type that rejects values that are not positive. To confirm, add one test per invalid combination expecting ValueError, and a test that main(["run", "idle", "--freq", "0"]) ends in SystemExit with code 2. Not compiled or run.
tests/test_io_hygiene.py:25fw = Fw(double_sign=False, verify=False)
The signing firmware can be built in four variants through the options double_sign and verify, but the tests build only two of them: the default with both on (Fw() at tests/test_signer.py line 22 and in the flow tests) and the variant with both off (tests/test_signer.py line 231 and tests/test_io_hygiene.py line 25). The command line reaches the other two through --single and --no-verify (sim/__main__.py line 168), and the check that a valid envelope writes only canonical ports runs on the variant with both controls off, not on the default build. Run the checks on every variant that can be built: in test_signing_writes_only_canonical_ports loop over the four combinations with sub-tests, and add a flow test that, for each combination, signs one message and asserts the status, the lock bits and that the signature equals the reference implementation. If a variant is not meant to be supported, remove its option from the command line instead and say so. To confirm, the test output must list four sub-tests per check, named by the two option values, and breaking one variant on purpose in a scratch copy of the generator must make exactly its sub-tests fail. Not compiled or run.
Info after review (37)
sim/emu65.c:28uint64_t trace;
In the state structure of sim/emu65.c the comment that explains the trace value (FNV-1a over every bus address, lines 30-32) is attached to the end of the io_writes field at line 30, two fields below the trace field it describes at line 28, so it reads as a description of io_writes. Move the three comment lines to the trace field, either directly above line 28 or beside it, and leave the io_writes field with only its own comment about the bitmap. To confirm, run grep -n 'FNV-1a' sim/emu65.c in the repository root: it reports line 30 today and must afterwards report the line of, or the line directly above, the declaration uint64_t trace. Not compiled or run.
sim/signer_fw.py:86assert self.next <= SHA, "field-element area overflow"
The allocator of field-element slots in sim/signer_fw.py guards the end of its memory area with an assert at line 86. Python drops assert statements under -O, and an allocation that runs past the area would then silently overlap the SHA-512 buffers that start at the address SHA. Replace the assert with an explicit test that raises an error naming the slot and the address reached. The allocator also hands out the same slot to every caller that uses the same name: the test harness asks for TA, TB and TC (sim/signer_harness.py line 43), which the firmware itself uses as temporaries. Give the harness slots of its own, registered beside the others at lines 92-101, or state in a comment at the harness why sharing them between calls is safe. To confirm, add a test that requests slots from a fresh allocator until the area is exceeded and expects the error, and run it once with python3 -O. Not compiled or run.
sim/signer_harness.py:23self.m.load(F.ZP[zp] if isinstance(zp, str) else zp, bytes([addr & 0xFF, addr >> 8]))
No change is needed for the present callers: Fw.setp in sim/signer_harness.py (line 23) accepts either the name of a zero-page pointer or a raw address, and Bench.run_to in sim/runner.py (line 79) accepts either a label or an address, but every caller is test or harness code in the repository and passes a value it has just built, so nothing from outside can be read as the other kind. If the helpers are ever reached from input, separate the two kinds at the entry: make setp accept only a name and raise KeyError with the list of known names for anything else, add a second method for a raw address that rejects values outside 0 to 0xFF, and do the same split for run_to. To confirm that the present state still holds, run grep -rn 'setp(' sim tests in the repository root and check that every call passes a quoted name as its first argument; if the split is made, add a test that passes a 16-bit number to the name-only method and expects the error. Not compiled or run.
sim/signer_fw.py:4Spec contract (Section 10): plain Ed25519 over raw message bytes; no
The signing firmware generated by sim/signer_fw.py checks the envelope magic, profile, reserved byte, length and CRC and that the derived public key equals the expected key (gen_main, lines 1230-1261), and then signs the message bytes as they arrived. It never parses the transaction and never shows an amount or a recipient; FINDINGS.md line 159 and README.md line 87 list the review screens and the policy parser as not built. Keep that limit where a reader of the code and of the documents meets it first: add a sentence to the contract paragraph of the module docstring (lines 4-8) and to the signing-firmware item of README.md (line 32) saying that this firmware signs any well-formed message of up to 4,096 bytes for the matching key without parsing or displaying it. In the host helper envelope (lines 1395-1398) check the message length against the firmware limit and raise ValueError for a longer message, instead of building an envelope the device will refuse or failing with an overflow error for very long input. To confirm, add a test that envelope(bytes(4097), key) raises ValueError, and read the two added sentences beside FINDINGS.md line 159. Not compiled or run.
sim/signer_fw.py:1368 g(f"t_{name}: JSR set_ct", f"JSR {name}", "STP")
source() in sim/signer_fw.py always emits a block of test entry points into the ROM image: one stub t_<name> for each routine in the list at lines 1364-1367 (line 1368), plus t_verify and t_sha at lines 1369-1370. The reset vector never reaches them, but they occupy ROM and are part of any image built from this generator, including one that would be burned. Give source() and build() a parameter that controls whether the stubs are emitted, keep them on for the test harness, which enters routines through these labels (sim/signer_harness.py line 28), and build any image meant for hardware without them. To confirm, add a test that builds without the stubs and asserts that no symbol name starts with t_, and that the same message signed from the reset vector on that image gives the same signature and result record as the test build. Not compiled or run.
sim/engine.py:251if len(self.violations) < self.max_violations:
Simulator.violation in sim/engine.py (lines 248-252) stores a violation only while fewer than max_violations (10,000, line 180) are held and drops every later one without a trace, so a run that hit the cap looks the same as a run with exactly that many violations. Add a counter field in Simulator.__init__, for example violations_dropped starting at 0, and increment it in an else branch at line 251. Show it wherever the total is reported: the summary line printed by _summary in sim/__main__.py (line 41) should add the dropped count when it is not zero. To confirm, add a test that sets max_violations to 2 on a fresh Simulator, reports five violations at a time after check_from, and asserts that two are stored and the dropped counter reads 3. Not compiled or run.
sim/parts.py:582assert len(image) == 32768
EPROM27256.__init__ in sim/parts.py checks the size of the ROM image with assert len(image) == 32768 (line 582). Python removes assert statements when run with -O, and a short image would then be accepted and fail later with an IndexError during a read. Replace the assert with an explicit test that raises ValueError stating the length received and the 32,768 bytes expected. Do the same for the other asserts in sim/ that guard real input: the duplicate part name check in Simulator.add_part (sim/engine.py line 195) and the ROM length check in Machine.__init__ (sim/emu.py line 58); list them with grep -rnE '^[[:space:]]*assert ' sim --include=*.py, run in the repository root, which prints 5 lines today, and decide for each whether it guards input (replace it) or an internal invariant (it may stay). To confirm, add a test that constructs EPROM27256 with a 100-byte image and expects ValueError, and run that test once with python3 -O to show the check no longer disappears. Not compiled or run.
sim/layout.py:139opts.sort(key=lambda o: math.dist(hole_xy(near_hole, self.grid),
sim/layout.py uses math.dist at lines 139 and 194, a standard-library function that sets a lower bound on the Python version the simulator can run on, and the only statement of a required version in the repository is the sentence at README.md line 42. Keep that sentence at or above what the code needs, and check on the Python project's own release page whether the release line it names is still supported; if it is not, raise the stated minimum to a supported line and change README.md line 42. This audit read only the source and the README: it did not read the Python project's support page and did not observe which interpreter runs the simulator. To confirm, run python3 --version on the machine that runs the simulator and the tests and compare it with the minimum written in the README; a version check at the start of main() in sim/__main__.py that reads the same minimum would keep the two from drifting apart. Not compiled or run.
sim/layout.py:52return (b, "pad", r) # panel pad: r is the net name
A hole in sim/layout.py is a three-part tuple whose third part is a row number for breadboard holes and rails but a net name for panel pads (strip_key, line 52), and the code tells the two apart by looking at the second part in several places (hole_xy at lines 60-66, the sort key at line 404, _dist at lines 436-437). All values are produced by the generator itself, so nothing outside can mix them, but nothing checks it either: a rail key passed to _dist would be read as a row. As a small hardening, validate the shape where keys are made: in strip_key require an integer row for strips and rails and a string for pads and raise ValueError otherwise, and in _dist reject a key whose second part is a rail name. A fuller alternative is two small named tuple types, one for holes and one for pads. To confirm, add tests that strip_key raises for a pad whose third part is a number and that _dist raises for a rail key; the regenerated wiring files must be unchanged. Not compiled or run.
U42, OSC, KEYSW_*, QSW, RSER and digit names).sim/layout.py:249L.sim_hole[(u, pin)] = h
The table sim_hole in sim/layout.py is keyed by (part name, pin) and mixes three kinds of names: real IC references (line 249), layout items given a sim_part (line 199) and parts that exist only in the simulator, written at lines 328-329, 346 and 384-392. The table is consumed by name in Part.__init__ (sim/parts.py lines 25-30), where a key that matches no part is simply never used and the part keeps its schematic net. Uniqueness is checked only among simulator parts (Simulator.add_part). Add a check at the end of generate: every part name used as a key of sim_hole must be a part of the schematic returned by schematic() at line 230, and setting a key a second time with a different hole must be an error; report both through L.errors, which the wiring command and the tests already treat as failures. To confirm, add a test that inserts a key with a misspelt part name into a generated layout, runs the check and expects an error naming that key, and check that the unmodified layout still reports no errors. Not compiled or run.
sim/layout.py:673with open(os.path.join(outdir, "wiring.csv"), "w", newline="") as f:
write_docs in sim/layout.py overwrites wiring.csv at line 673 and WIRING.md at line 740 in place. The CSV is written first, before harness_checks and physical_netlist run at lines 678-679, so if either of those raises, the directory is left with a new CSV beside the old WIRING.md. The files are tracked, so git can restore them, but the pair should never be half updated. Build both texts completely first, write each to a temporary name in the output directory, and move both into place with os.replace only when both are complete. In the waveform writer, sim/vcd.py line 16, close the file if writing the header at lines 18-24 fails. To confirm, add a test that makes harness_checks raise while write_docs runs on a temporary copy of the wiring directory and asserts that both files still have their previous content; on the present code the CSV has already changed at that point. Not compiled or run.
sim/layout.py:370vcc_pins = [p for p in range(1, n + 1) if terms.get((u, p)) == VCC
Several leftovers can be removed. In sim/layout.py the list vcc_pins is computed at lines 370-371 and never used. In sim/checks.py the assignment j = 0 at line 160 is never read. In sim/parts.py the class HC595 (lines 401-441) models a part the board no longer places, and sim/board.py does not import it; delete it together with its entries in sim/timing.py (lines 29-30 and 37) after a search shows no other user. Finally the name SW has two meanings: in sim/board.py it is the list of U14 input nets (line 28), which sim/layout.py imports at line 21, while in sim/layout.py the string "SW" also names the switch panel; rename the list to say what it holds at its declaration and at every use in one edit. To confirm, run grep -c 'vcc_pins' sim/layout.py in the repository root: it prints 1 today and must print 0; grep -rn 'HC595' sim must list nothing after the deletion; and the regenerated wiring files and the test suite must be unchanged. Not compiled or run.
sim/analog.py:17"HC14_tpd_ns": (8, 31),
The propagation delay of the same HC14 part is stated twice with different minimums: sim/analog.py line 17 uses (8, 31) ns for the oscillator analysis and sim/timing.py line 13 uses (4, 31) ns for the simulator, and nothing explains the difference. Keep one statement: delete the HC14_tpd_ns entry at sim/analog.py line 17 and let oscillator() (line 50) read the range from the TPD table in sim/timing.py, whose header already says nothing else should hard-code timing; or, if the oscillator analysis needs a different minimum on purpose, keep both and write the reason and the datasheet source beside each. Which minimum is right is a datasheet question for the owner; the header of sim/timing.py says the minimums there are estimates. Changing the minimum moves the upper end of the oscillator range, so re-run python3 -m sim check and update the frequency ranges quoted in the documents. To confirm, run grep -rn 'HC14_tpd_ns' sim in the repository root: it lists 2 lines today and must list none if the single-table option is taken. Not compiled or run.
sim/parts.py:182if clr == 0 and pre == 0:
qv, qnv = 1, 1
async_ = True
In HCT74.evaluate (sim/parts.py lines 175-207) the branch for clear and preset both low (lines 182-184) forces both outputs high but leaves the stored state q at its previous value, so when the two inputs are released the model carries on from the old state, whereas the function table of the part gives no defined state after both are released together. In that branch set q to X, so that line 199 stores an unknown state while lines 200-201 still drive both outputs high for as long as both inputs are low; after release the outputs then read unknown until a clock edge or a single asynchronous input defines them. The present netlist ties the preset pins to the supply, so no current test reaches this branch. To confirm, add a unit test that builds one HCT74 with its clear and preset driven by two sources, holds both low, releases both at the same time and asserts that Q is X until the next clock edge loads a known value. Not compiled or run.
README.md:12The spec covers the circuit, the breadboard layout, the bring-up plan and the firmware contract. It does not include signing firmware.
README.md line 12 ends with "It does not include signing firmware", while line 32 of the same file describes sim/signer_fw.py as an Ed25519 signer that is checked against OpenSSL, so a reader meets both statements with nothing to reconcile them. Rewrite the second sentence of line 12 to separate the two things, for example: the spec itself contains no firmware; sim/signer_fw.py is a reference signing implementation used for verification and is not yet a burnable ROM (line 87 already says so). To confirm, run grep -c 'It does not include signing firmware' README.md in the repository root: it prints 1 today and must print 0, and lines 12, 32 and 87 must then read consistently. Not compiled or run.
tests/test_bus.py:148 b = Bench(scenario="mirrors", seed=2, cap_pf={"P_D": 400})
spec.md line 497 and FINDINGS.md line 54 state that unmapped reads still return $FF with up to roughly 1,000 pF on a P_D line at the default 380 kHz clock, but the only test of this, test_unmapped_reads_tolerate_large_p_d_capacitance in tests/test_bus.py (lines 147-151), runs with 400 pF, which is the figure FINDINGS.md gives for the fast 890 kHz corner. Add a second case to the test that builds the bench with cap_pf={"P_D": 1000} at the default clock and makes the same three assertions, and keep the 400 pF case but run it at the fast clock it belongs to. If the 1,000 pF case fails, find the largest value that passes and correct the figure in spec.md line 497 and FINDINGS.md line 54 to it. To confirm, the test must contain both cases as sub-tests naming capacitance and clock, and the two documents must quote only values that a sub-test exercises. Not compiled or run.
tests/test_bus.py:121ov.append((e - s, s - max(f for f in falls if f <= s), o))
The helper TestReadWindowRace.overlaps in tests/test_bus.py computes, for each overlap interval, the time since the latest PHI2 fall with max(f for f in falls if f <= s) at line 121. If an overlap starts before the first recorded PHI2 fall, the generator is empty and max raises ValueError, so the test ends with an unexplained error instead of reporting the overlap it found. Give max a default of None, and when the result is None fail the test with a message that states the start time of the overlap and that no PHI2 fall precedes it. To confirm, move the three lines that build one result entry into a small function and add a test that calls it with an overlap start earlier than every entry of the falls list, expecting an AssertionError with that message and not a ValueError. Not compiled or run.
tests/test_signer.py:12(value omitted by rule: a signing seed derived from a text string, type: public test-fixture seed)
The text from which the public test seed is derived is typed three times: in tests/test_signer.py line 12, in tests/test_io_hygiene.py line 14 and as the default of the --seed-text option in sim/__main__.py line 220. It is a published fixture and not a secret, but three copies can drift apart and a changed copy would silently test a different key. Define the fixture once, as a constant for the text and one for the derived seed, in a module that tests and command line can both import (the test harness module is a natural place), mark it there in a comment as public test material for a key that must never hold funds, and import it at the three sites. To confirm, run grep -c '^SEED = ' tests/test_signer.py and grep -c '^SEED = ' tests/test_io_hygiene.py in the repository root: each prints 1 today and must print 0 once the constant is imported, and the signer tests must give the same signatures as before. Not compiled or run.
README.md:51python3 -m sim wiring # regenerate wiring/WIRING.md + wiring.csv (hole-level build list) and check it
Several commands in the "Running it" block of README.md write files and the README does not say which or how to undo them: python3 -m sim wiring (line 51) overwrites the tracked files wiring/WIRING.md and wiring/wiring.csv (cmd_wiring in sim/__main__.py line 144, default --out at line 227); python3 -m sim roms (line 53) creates roms/ (sim/__main__.py lines 192-207); the first use of the fast emulator compiles sim/emu65.c into sim/_build/ (sim/emu.py lines 9-10 and 37-39); and tools/fetch_klaus.sh deletes and recreates third_party/klaus (lines 6-7). Add a short list under the command block naming each written path, noting that --out redirects the wiring and ROM output, and giving the clean-up: delete sim/_build, roms and third_party, and restore wiring/ with git checkout if the regenerated list is not wanted. As a further step, give the wiring command a mode that compares the generated text with the tracked files and reports differences without writing. To confirm, run grep -c '_build' README.md in the repository root: it prints 0 today and must print at least 1, and every path in the new list must match the code lines cited above. Not compiled or run.
spec.md:228| Core control | RWB, nRWB, PHI2, Q_A, /Q_A, Q_B, /Q_B, Q_C, /Q_C, EARLY, RD_WIN_N, RWB_CYCLE, HOLD_N, LATCH_OE_N, COLD_CLEAR_N, CPU_RESET_N | Keep clocks and window strobes away from LED-current loops |
spec.md Section 4.1 defines one convention at line 239, "_N means active low", but inverted nets are written in two further ways in the same document: with an n prefix (nRWB, nA15) and with a slash (/Q_A, /Q_B, /Q_C, for example in the harness table at line 228). The generated wiring list names the inverted counter outputs differently: QA_N and QC_N appear in the harness row at wiring/WIRING.md line 26 and QB_N in the row at line 28, so a reader cannot find the spec's /Q_A in the build list by searching for the name. Choose one spelling for inverted nets and use it in the tables, or keep the present spellings and add a short alias table to Section 4.1 that maps every spec name to the name used in the wiring list (/Q_A is QA_N, and so on). The names in the simulator's netlist (sim/board.py) are what the wiring list prints, so the table must match them. To confirm, run grep -c 'QA_N' spec.md in the repository root: it prints 0 today and must print at least 1, and every net named in the harness table at line 228 must be findable in wiring/WIRING.md either directly or through the alias table. Not compiled or run.
spec.md:905Connect Y3_N from U13 pin 12 as PORT3_N; Y4_N from U13 pin 11 as PORT4_N.
No design change is needed: the document uses two names for the same two nets, and both are fixed, one-to-one aliases. The decoder outputs are called Y3_N and Y4_N in the harness table (spec.md line 229) and PORT3_N and PORT4_N in the protection equations and the U41 table (lines 830-831 and 899-900), and the only statement that they are the same nets comes afterwards, in the closing paragraph at line 905. State each alias once where names are defined, in Section 4.1 beside the list of local aliases at line 243, and refer to that place from line 905; treat the pair CPU PHI2 and PHI2_FAULT the same way, since line 905 also has to explain that they are different nets. To confirm, run grep -n 'PORT3_N' spec.md in the repository root: it lists lines 830, 899 and 905 today and must afterwards also list a line inside Section 4.1. Not compiled or run.
tests/test_io_hygiene.py:46 allowed = CANONICAL_WRITES | ({0x7F05} if name == "res_fault" else set())
The module docstring of tests/test_io_hygiene.py (lines 1-3) and the name of test_test_firmware_scenarios_write_only_canonical_ports say that firmware stores only to the canonical ports $7F02-$7F04, but line 46 also allows $7F05 for the res_fault scenario, an address spec.md line 273 lists as reserved, so what the test really checks is "canonical ports plus one known probe". Say so: name the exception in the docstring and in the test name, and hold it in a named table of deliberate probes per scenario instead of an inline condition, so a new exception has to be added visibly. Two further gaps belong to the same edit. The emulator records only writes, so reads of non-canonical I/O addresses are not checked; state that in the docstring or add read logging. And the bad-CRC envelope at line 23 replaces the last byte with zero, which leaves the envelope valid whenever that byte already was zero; flip a bit of the last byte instead. To confirm, run grep -cF '[:-1] + b"\x00"' tests/test_io_hygiene.py in the repository root: it prints 1 today and must print 0, and the docstring and the test name must mention the $7F05 probe. Not compiled or run.
tests/test_signer.py:158 a = self.trace(routine, hashlib.sha256(b"seed one").digest())
b = self.trace(routine, hashlib.sha256(b"seed two").digest())
test_derive_and_sign_traces_independent_of_seed in tests/test_signer.py compares the bus trace of the routines derive and sign for two seeds only, both hashes of short texts (lines 158-159), with one message. Seeds of that kind do not exercise the carry and borrow chains at their extremes. Widen the set while keeping the single equality assertion: add structured seeds (all bytes zero, all bytes 0xFF, a single set bit in the lowest and in the highest position) and a handful of random ones, and repeat the comparison for a second message of a different length, comparing seeds only with each other for the same message because the trace legitimately depends on the public length. For the full sign_main flow, compare the trace over the secret-handling stage (derivation and both signatures); the verification stage works on public data with table lookups and is expected to differ between keys, so say in the test that it is excluded. To confirm, insert a seed-dependent branch into derive in a scratch copy of the generator and observe that the widened test fails, then remove it and observe that all seeds give one trace per message. Not compiled or run.
sim/firmware.py:63BOOT_SRC = r"""
sim/firmware.py (719 lines) keeps several independent pieces in one file and largely in one assembly string, BOOT_SRC, which starts at line 63: the boot and reset state machine (lines 88-223), the keypad menu (226-272), the test scenarios (274-459 and 634-671), the MAX7219 display driver (462-582), the keypad scanner (585-631), and on the Python side the result-record and CRC table builders (lines 31-60) and the RAM probe list (700-703). Plan the split before the next feature is added: keep each cluster as its own assembly text in its own module (for example boot, display and keypad drivers, scenarios), move the record and table builders into a host-side module, and let boot_rom join the texts and assemble them as it does today. Move the text without changing it. To confirm, record the SHA-256 of boot_rom()[0] and of boot_rom(zero_end_page=0x40)[0] before the split and check that both are identical afterwards, and that the symbols done, hold, idle and mn_loop used by the tests keep their addresses. Not compiled or run.
sim/cpu65c02.py:473class W65C02S(Part):
sim/cpu65c02.py holds two separate things in 581 lines: the instruction-set model (class Core with OPTABLE and NOP_SHAPE, lines 22-460) and the pin-level bus-timing part (class W65C02S with _halted, ADDR_PINS and DATA_PINS, lines 463-581). They share no state; the part only creates a Core and drives it, and the imports of the timing table, the engine and the part base class at lines 11-13 are needed by the part alone. Plan the split now and make it before the next feature is added to the part, such as interrupt or RDY handling: move W65C02S and its three helpers into a module of their own that imports Core, leave the instruction model in sim/cpu65c02.py without the simulator imports, and update the one importer of the part, sim/board.py line 14. Change no behaviour in the same edit. To confirm, run grep -c '^class W65C02S' sim/cpu65c02.py in the repository root: it prints 1 today and must print 0, each of the two modules must import on its own, and the unchanged test suite must pass. Not compiled or run.
sim/parts.py:648v = net.value if net else 0
SC56Digit.lit in sim/parts.py (lines 643-653) reads the levels of the digit's segment nets, but nothing in the model ever drives those nets: the MAX7219 model drives only its serial output, pin 24 (lines 788 and 810), so the method can only ever report a dark digit, and it has no caller; the display is read through MAX7219.lit from Harness.display (sim/board.py line 360), which matches net names and not levels. Either delete SC56Digit.lit, or make it meaningful by having the MAX7219 model drive its segment and digit pins and reading the panel from the digits; the second is a larger change to the display model and the owner should decide whether level checking is wanted. If the method is deleted, also note in the docstring of Harness.display that the check is by connectivity. To confirm deletion, run grep -rn '\.lit()' sim tests in the repository root: it lists one line today (the MAX7219 call at sim/board.py line 360) and must still list exactly that line, and grep -c 'def lit' sim/parts.py must drop from 2 to 1. Not compiled or run.
sim/layout.py:1"""Hole-level breadboard layout, jumper list and physical connectivity.
sim/layout.py is 742 lines long and holds clusters that depend on each other in one direction only: geometry helpers (lines 42-89), the Layout class that allocates holes (92-203), the generator (210-444), physical connectivity and the derived netlist (451-570), the harness and length checks (577-656) and the document writer (663-742). Record the split now and carry it out before the next feature is added: move write_docs into a module of its own, move wire_report, harness_checks and summary into a second one, and leave allocation, generation and connectivity in sim/layout.py; then update the callers (cmd_check and cmd_wiring in sim/__main__.py, tests/test_breadboard.py and tests/test_static.py) to import from the new places. Move the code without changing it. To confirm, regenerate wiring/WIRING.md and wiring/wiring.csv before and after the split and check that both are byte-identical, and run the unchanged tests. Not compiled or run.
spec.md:8This is a self-contained specification for a small computer using a modern 6502-family CPU, ordinary SRAM, fixed program ROM, keypad input, and seven-segment LED output.
spec.md describes the signer section by section (input and display in Section 8, the locks in Section 9, the boot states in 10.1, the envelope in 10.3, the result record in 10.4 and the Solana binding in 10.5), but nowhere follows one signing session from start to finish, so a reader has to assemble the sequence of operator actions and memory states alone. Add one worked session as its own subsection of Section 10: start from the public test material already in the document (the empty-message vector of Section 10.6, lines 1030-1034), give the exact envelope bytes including the CRC, the boot state entered, the point at which MESSAGE_LOCK is set, what the operator sees and presses as far as Section 8 defines it, the signing steps, the complete result record with every field value, the setting of RESULT_LOCK and the code shown after a CPU reset. Mark each step the design has not yet defined, such as the review pages, as not specified instead of inventing it, and refer to the example from the sections it passes through. Every value in it must agree with the tables it quotes. To confirm, add a test that reads the example's envelope and record bytes from spec.md and compares them with the output of the envelope and result-record helpers in sim/signer_fw.py for the same vector. Not compiled or run.
sim/cpu65c02.py:563self.halted = str(e)
The CPU part in sim/cpu65c02.py records a halt in self.halted at line 563 and never clears it, so after a reset restarts the processor the part still reports the old halt (Bench.run_to prints it at sim/runner.py line 85); the flag Core.stopped is set at lines 35 and 329 and read nowhere; and the handler at line 562 catches every Exception, so a programming error inside the simulator is reported as a cpu-halt violation of the design under test. In the reset branch of _fall (lines 546-550) set self.halted back to None, so a reset clears what it owns. Delete Core.stopped, or give it a reader. Narrow the handler at line 562 to the UnknownOpcode exception defined at line 18, so that any other exception stops the run with its traceback. To confirm, add a test that runs a ROM ending in STP until halted is set, presses reset through the bench and asserts that halted is None and instructions execute again; grep -c 'except Exception' sim/cpu65c02.py in the repository root prints 1 today and must print 0, and grep -c 'stopped' sim/cpu65c02.py prints 2 today and must print 0 if the flag is deleted. Not compiled or run.
sim/asm.py:32from .cpu65c02 import OPTABLE
sim/asm.py takes the opcode table from the CPU model (from .cpu65c02 import OPTABLE, line 32), and sim/cpu65c02.py in turn imports the simulation engine and the part models (its lines 12-13), so building firmware through sim/firmware.py or sim/signer_fw.py loads the gate-level simulator only to obtain a table. Move OPTABLE and its builder (sim/cpu65c02.py line 449) and NOP_SHAPE (lines 451-460) into a small module of their own that imports nothing from the package, import them from there in both sim/asm.py and sim/cpu65c02.py, and correct the sentence in the docstring at sim/asm.py line 3. Do not re-export the names from cpu65c02.py. The C emulator sim/emu65.c holds its own copy of the opcode table; keep the existing cross-check tests in tests/test_emu.py as the guard that the two stay equal. To confirm, run grep -c 'cpu65c02' sim/asm.py in the repository root: it prints 2 today and must print 0, and python3 -c "import sys, sim.asm; print('sim.engine' in sys.modules)" must print False. Not compiled or run.
sim/board.py:51 sim.net(VCC).value = 1
sim.net(VCC).supply = True
Code outside sim/engine.py sets fields of Net and Simulator directly: build in sim/board.py writes value and supply at lines 51-54, pullup_ohms, cap_pf and pull_value at lines 58-59, 64 and 74, vcd and pin_remap at lines 43 and 45, and master_per_cpu at line 291, a field Simulator.__init__ (sim/engine.py lines 169-184) does not declare; Harness writes pull-up fields and check_from at lines 306-307 and 313; and sim/runner.py line 53, sim/brownout.py line 37, sim/__main__.py line 132 and sim/handoff.py line 10 append to watchers or update driver_watch. Give the owner the operations: on Net a method that marks a supply at a level, a method that sets the pull resistor, capacitance and pull level together, and a method that adds a watcher; on Simulator a method that adds nets to the driver log, and constructor arguments for the waveform writer, the pin remap, the start time of checking and the clock ratio, with master_per_cpu declared in __init__. Replace the direct writes listed above with these calls. To confirm, run grep -cE '\.(pullup_ohms|cap_pf|pull_value|supply) = ' sim/board.py in the repository root: it prints 8 today and must print 0, and python3 -m sim check must print the same result as before. Not compiled or run.
sim/corners.py:13p["U10"]._delays[("tpd", 8)] = 30.0
Several modules write the internal state of simulation objects they do not own: sim/corners.py writes the underscore-named _delays table of parts throughout lines 13-44, sim/runner.py writes the SRAM model's mem list at lines 36-37 and the CPU core's fetch_pc at line 97, and sim/signer_harness.py writes the emulator's register fields at lines 20 and 27-28. Give each owner a method for the operation: a set_delay(key, ns) method on Part in sim/parts.py (next to dly at line 42) that the corner functions call, a load method on the SRAM model for placing bytes at an address, a method on the CPU model for the resynchronisation that Bench.cold_clear needs, and methods on Machine in sim/emu.py for setting the stack pointer and the start address. Then replace the direct writes with those calls; re-count the sites with grep first and report the number changed. To confirm, run grep -c '_delays' sim/corners.py in the repository root: it prints 16 today and must print 0, and the corner tests in tests/test_bus.py must give the same results as before. Not compiled or run.
sim/layout.py:227 L.grid = dict(grid or GRID)
L.variant = dict(grid=grid, moves=moves, cd_pullups_at_cpu=cd_pullups_at_cpu,
The module function generate in sim/layout.py fills in the Layout object by writing its fields directly instead of going through the class: it replaces grid and adds variant, a field Layout.__init__ (lines 93-103) does not declare, at lines 227-229, sets terminals at line 231, writes pin_hole, sim_hole and strip_net at lines 248-255, 328-329, 346 and 384-392, and appends to items at lines 377 and 381, although the class already offers take, attach, part and wire for the other steps. Give the class the missing operations: let the constructor take the grid and the variant, add a method that seats one IC pin (the work of lines 244-255), a method that records the hole of a simulator part pin and refuses a conflicting second entry, and a method that adds an item with fixed leads; then call these from generate. To confirm, run grep -cE 'L\.(sim_hole|pin_hole|strip_net)\[.*\] = ' sim/layout.py in the repository root: it prints 14 today and must print 0, and the regenerated wiring files must be byte-identical. Not compiled or run.
sim/__main__.py:111return 0 if b.ram.mem[0x200] == want and not b.violations() else 1
Code outside the Bench class reads the bench's inner objects directly: sim/__main__.py at lines 36-40, 65, 106, 111 and 135 (b.cpu.core registers, b.cpu.cycles, b.ram.mem, b.sim.now, b.sim.driver_log), sim/handoff.py throughout measure (lines 13-83) and sim/brownout.py in the same way. Bench (sim/runner.py line 17) already offers net(), violations() and display_text(); add read methods for the remaining questions callers ask, for example one that returns a RAM byte, one that returns the CPU registers, one that returns the recorded bus cycles, and one that returns the driver intervals of a net between two times, and replace the direct reads with them. Re-count the direct reads with grep before editing and report the number changed; tests that write b.ram.mem to preload memory should get a matching load method instead of writing the list. To confirm, run grep -cE 'b\.ram\.mem|b\.cpu\.core' sim/__main__.py in the repository root: it prints 4 today and must print 0 afterwards, and the output of python3 -m sim diag must be unchanged. Not compiled or run.
sim/__main__.py:116 kw = _bench_kw(a)
r = measure(kw, scenario="ram")
Three sub-commands open a waveform file through _bench_kw (sim/__main__.py line 30) and only two release it, and only when nothing fails: cmd_run closes it at line 95 and cmd_diag at line 109, after the simulation has finished, while cmd_handoff (lines 114-122) never closes it; if b.run_to raises its TimeoutError before those lines, the file is left to interpreter shutdown and the waveform that would explain the failure may be incomplete. Release the file on every exit path from one place: wrap the body of each of the three commands, or the single call fn(a) at line 245 in main, in try/finally and close the writer there, or make VCD (sim/vcd.py line 14) a context manager and open it in a with block. Count the result: one place that opens, one place that closes. To confirm, add a test that makes Bench.run_to raise while --vcd points at a temporary file and asserts that the file object is closed afterwards and the file ends with a complete line; grep -c 'finally' sim/__main__.py in the repository root prints 0 today and must print at least 1. Not compiled or run.
sim/parts.py:474 self._out[p] = None # force scheduling
self.out(p, X, t_x, 0)
self._out[p] = None
Part.out in sim/parts.py drops a write that equals the last value written to the pin (lines 61-62). Three models need to schedule a repeated value and get round the filter by editing the private _out table directly: _Memory._drive_outputs sets the entry to None at lines 474 and 476, and Source.set and Oscillator._tick pop it at lines 684 and 703. Make the filter a choice of the caller: give Part.out (line 57) a keyword parameter force that defaults to False and, when True, skips the comparison at line 61, and replace the four edits of _out with calls that pass force=True. The reads of _out inside the buffer and latch models, which decide which delay applies, are not affected. To confirm, run grep -cE '_out\[p\] = None|_out\.pop' sim/parts.py in the repository root: it prints 4 today and must print 0, and the existing test suite must give the same results, which shows the forced writes still reach the simulator. Not compiled or run.
sim/firmware.py:17GLYPH_C = 0x39
sim/firmware.py defines GLYPH_C = 0x39 at line 17 and never uses it; the same value is typed as a literal in the assembly text at line 550 (LDA #$39 in show_code), and the glyphs for 0, 2 and 1 are typed likewise at lines 134, 190 and 193, although all four are entries of the FONT table at lines 15-16. Either delete line 17, or give the glyphs one owner: pass them to the assembler as symbols taken from FONT in the assemble call at line 718, next to ZERO_END, and write the symbol names in place of the four literals. To confirm, run grep -c 'GLYPH_C' sim/firmware.py in the repository root: it prints 1 today and must print 0 after deletion, or at least 3 when the constant is defined, passed and used; in both cases the SHA-256 of boot_rom()[0] must be the same before and after. Not compiled or run.
Excluded on review (3)
Findings that were reported and then set aside, each with the reason. They are not counted above.
- 5007. The key file header written by openssl_sign (
sim/solana.py:81) (first rated Info): Excluded: in the copy we read, this line had been replaced by a placeholder, so the finding described the placeholder and not the code of the repository. The line in the repository is correct. - 5224. Package width of the MAX7219CNG LED driver (
spec.md:107) (first rated Low): Excluded: could not be verified. The claim rests on the manufacturer's package drawing, which could not be fetched. Without that evidence it is not a finding. - 5501. Order of pins 6 and 7 in the HCT273 pin table (
spec.md:623) (first rated Medium): Excluded: the claimed pin swap could not be confirmed against a readable data-sheet page; whether the repository's table is right or wrong is unknown. Without that confirmation it is not a finding.