fix: harden LoRa OTA chain and storage

This commit is contained in:
mikecarper committed 2026-08-29 06:58:48 -07:00
1 parent 400aa710a2
commit b40d2e6cb2
29 files changed
+7497 -528

No files matched your search

File diff suppressed because it is too large. Load diff
+788 -105
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+638
View File
@@ -0,0 +1,638 @@
#!/usr/bin/env python3
"""Exhaustively select a compact legacy-ceiling RAK3401 mOTA route.
Cache entries are keyed by source SHA, target SHA, and workspace size rather
than inventory indices. A cache generated for an older inventory can therefore
be migrated safely when new candidate images are inserted.
"""
from __future__ import annotations
import argparse
import csv
from concurrent.futures import ProcessPoolExecutor, as_completed
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
import sys
import tempfile
SCRIPT_DIR = Path(__file__).resolve().parent
REPO_ROOT = SCRIPT_DIR.parent.parent
sys.path.insert(0, str(REPO_ROOT / "tools" / "mota"))
import motalib # noqa: E402
APP_BASE = 0x26000
STAGE_CEILING = 0xD4000
PAGE = 4096
SEGMENT = PAGE
FIXED_MEMORY = 0x98000
AVAILABLE_PAGES = (STAGE_CEILING - APP_BASE) // PAGE
EXPECTED_TARGET_ID = 0x2FA509C1
EXPECTED_HARDWARE = "RAK_3401"
FIELDS = [
"source", "target", "source_sha256", "target_sha256", "memory",
"payload", "container", "stage_start", "margin", "feasible", "error",
]
class RouteSearchError(RuntimeError):
"""An invalid input or internally inconsistent cache."""
def align_up(value: int, unit: int = PAGE) -> int:
return (value + unit - 1) // unit * unit
def align_down(value: int, unit: int = PAGE) -> int:
return value // unit * unit
def container_size(payload_size: int) -> int:
return payload_size + 210 + 4 * ((payload_size + 1023) // 1024)
def truth(value: object) -> bool:
return value is True or str(value).lower() == "true"
def sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as source:
while chunk := source.read(1024 * 1024):
digest.update(chunk)
return digest.hexdigest()
def _integer(value: object, label: str) -> int:
if isinstance(value, int) and not isinstance(value, bool):
result = value
elif isinstance(value, str) and re.fullmatch(r"[0-9]+", value):
result = int(value)
else:
raise RouteSearchError(f"{label} must be an integer")
if result < 0:
raise RouteSearchError(f"{label} cannot be negative")
return result
def load_inventory(path: Path) -> list[dict[str, object]]:
try:
document = json.loads(path.read_text(encoding="ascii"))
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
raise RouteSearchError(f"cannot read image inventory {path}: {exc}") from exc
images = document.get("images") if isinstance(document, dict) else None
if not isinstance(images, list) or len(images) < 2:
raise RouteSearchError(f"invalid image inventory: {path}")
result: list[dict[str, object]] = []
seen: set[str] = set()
for index, raw in enumerate(images):
if not isinstance(raw, dict):
raise RouteSearchError(f"inventory image {index} is not an object")
record = dict(raw)
if _integer(record.get("node", index), f"inventory node {index}") != index:
raise RouteSearchError(
"inventory nodes must be ordered, contiguous, and zero-based"
)
raw_path = record.get("path")
if not isinstance(raw_path, str) or not raw_path:
raise RouteSearchError(f"inventory image {index} has no path")
image_path = Path(raw_path)
if not image_path.is_absolute():
image_path = path.parent / image_path
image_path = image_path.resolve()
if not image_path.is_file():
raise RouteSearchError(f"missing inventory image: {image_path}")
try:
image = image_path.read_bytes()
except OSError as exc:
raise RouteSearchError(f"cannot read inventory image: {image_path}") from exc
actual_sha = hashlib.sha256(image).hexdigest()
expected_sha = record.get("sha256")
if not isinstance(expected_sha, str) or len(expected_sha) != 64 or any(
character not in "0123456789abcdefABCDEF" for character in expected_sha
):
raise RouteSearchError(f"image {index} SHA-256 is invalid")
expected_sha = expected_sha.lower()
if actual_sha != expected_sha:
raise RouteSearchError(f"image {index} SHA mismatch")
if expected_sha in seen:
raise RouteSearchError(f"duplicate image SHA at node {index}")
seen.add(expected_sha)
actual_size = len(image)
if _integer(record.get("size"), f"image {index} size") != actual_size:
raise RouteSearchError(f"image {index} size mismatch")
if not motalib.has_endf(image):
raise RouteSearchError(f"image {index} has no valid EndF")
ident = motalib.parse_endf_ident(image)
if (
ident is None
or ident.target_id != EXPECTED_TARGET_ID
or ident.hw_id != EXPECTED_HARDWARE
):
raise RouteSearchError(f"image {index} has the wrong RAK3401 identity")
_body, body_hash = motalib.parse_endf(image)
declared_body_hash = record.get("body_hash")
if (
not isinstance(declared_body_hash, str)
or not re.fullmatch(r"[0-9a-f]{16}", declared_body_hash)
or declared_body_hash != body_hash.hex()
):
raise RouteSearchError(f"image {index} body hash mismatch")
version = motalib.unpack_version(ident.fw_version)
if record.get("version") != version:
raise RouteSearchError(f"image {index} version mismatch")
source_commit = record.get("source_commit")
if source_commit is not None and (
not isinstance(source_commit, str)
or not re.fullmatch(r"[0-9a-f]{40}", source_commit)
):
raise RouteSearchError(f"image {index} source commit is invalid")
if index == 1 and _integer(
record.get("baseline_container_size"),
"node 1 baseline_container_size",
) <= 0:
raise RouteSearchError("node 1 baseline_container_size must be positive")
record.update(node=index, path=str(image_path), sha256=expected_sha, size=actual_size)
result.append(record)
return result
def snapshot_inventory(source: Path, destination: Path) -> Path:
"""Copy an inventory and its images before starting parallel patch work."""
try:
document = json.loads(source.read_text(encoding="ascii"))
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
raise RouteSearchError(f"cannot read image inventory {source}: {exc}") from exc
images = document.get("images") if isinstance(document, dict) else None
if not isinstance(images, list) or len(images) < 2:
raise RouteSearchError(f"invalid image inventory: {source}")
image_directory = destination.parent / "images"
image_directory.mkdir(parents=True, exist_ok=False)
for index, raw in enumerate(images):
if not isinstance(raw, dict):
raise RouteSearchError(f"inventory image {index} is not an object")
raw_path = raw.get("path")
if not isinstance(raw_path, str) or not raw_path:
raise RouteSearchError(f"inventory image {index} has no path")
image_source = Path(raw_path)
if not image_source.is_absolute():
image_source = source.parent / image_source
image_destination = image_directory / f"image-{index:03d}.bin"
try:
shutil.copy2(image_source, image_destination, follow_symlinks=True)
except OSError as exc:
raise RouteSearchError(
f"cannot snapshot inventory image {index}: {image_source}: {exc}"
) from exc
raw["path"] = str(Path("images") / image_destination.name)
destination.parent.mkdir(parents=True, exist_ok=True)
destination.write_text(
json.dumps(document, indent=2, sort_keys=True) + "\n",
encoding="ascii",
)
# Validate the copied bytes against every declared content and EndF pin.
load_inventory(destination)
return destination
def insert_bridges_before_endpoint(
document: dict[str, object], bridges: list[dict[str, object]]
) -> dict[str, object]:
"""Insert ordered bridge records immediately before the existing endpoint."""
existing = document.get("images")
if (
not isinstance(existing, list)
or len(existing) < 2
or not all(isinstance(item, dict) for item in existing)
):
raise RouteSearchError("inventory document has no valid start and endpoint")
if not all(isinstance(item, dict) for item in bridges):
raise RouteSearchError("inventory bridges must be objects")
# Copy every record, preserving the last existing record as the endpoint.
ordered = [dict(item) for item in existing[:-1]]
ordered.extend(dict(item) for item in bridges)
ordered.append(dict(existing[-1]))
images = []
for node, record in enumerate(ordered):
record["node"] = node
images.append(record)
result = dict(document)
result["images"] = images
return result
def cache_key(source_sha: str, target_sha: str, memory: int) -> tuple[str, str, int]:
return source_sha.lower(), target_sha.lower(), memory
def migrate_csv(
inventory_path: Path, csv_path: Path
) -> dict[tuple[str, str, int], dict[str, object]]:
"""Migrate numeric CSV indices through the inventory that created them."""
images = load_inventory(inventory_path)
migrated: dict[tuple[str, str, int], dict[str, object]] = {}
try:
source = csv_path.open(newline="", encoding="ascii")
except OSError as exc:
raise RouteSearchError(f"cannot read geometry cache {csv_path}: {exc}") from exc
with source:
reader = csv.DictReader(source)
required_fields = {"source", "target", "memory"}
if reader.fieldnames is None or not required_fields.issubset(reader.fieldnames):
raise RouteSearchError(f"geometry cache has missing columns: {csv_path}")
for line, row in enumerate(reader, 2):
source_node = _integer(row["source"], f"source at {csv_path}:{line}")
target_node = _integer(row["target"], f"target at {csv_path}:{line}")
if not (0 <= source_node < target_node < len(images)):
raise RouteSearchError(f"bad nodes at {csv_path}:{line}")
source_sha = str(images[source_node]["sha256"])
target_sha = str(images[target_node]["sha256"])
memory = _integer(row["memory"], f"memory at {csv_path}:{line}")
for column, expected in (
("source_sha256", source_sha), ("target_sha256", target_sha)
):
raw_recorded = row.get(column, "")
if raw_recorded is None:
raw_recorded = ""
if not isinstance(raw_recorded, str):
raise RouteSearchError(
f"{column} is invalid at {csv_path}:{line}"
)
recorded = raw_recorded.lower()
if recorded and recorded != expected:
raise RouteSearchError(
f"{column} disagrees with inventory at {csv_path}:{line}"
)
try:
payload = int(row.get("payload", ""))
total = int(row.get("container", ""))
stage_start = int(row.get("stage_start", ""))
margin = int(row.get("margin", ""))
except (TypeError, ValueError) as exc:
raise RouteSearchError(
f"invalid numeric geometry at {csv_path}:{line}"
) from exc
if payload < 0:
raise RouteSearchError(
f"failed cached geometry cannot prove an exhaustive search at "
f"{csv_path}:{line}; regenerate it"
)
if row.get("error", ""):
raise RouteSearchError(
f"successful cached geometry carries an error at "
f"{csv_path}:{line}; regenerate it"
)
expected_total = container_size(payload)
expected_stage = align_down(STAGE_CEILING - expected_total)
expected_margin = expected_stage - (APP_BASE + memory)
if (total, stage_start, margin) != (
expected_total, expected_stage, expected_margin
):
raise RouteSearchError(
f"inconsistent cached geometry at {csv_path}:{line}"
)
if truth(row.get("feasible", False)) != (payload >= 0 and margin >= 0):
raise RouteSearchError(
f"cached feasibility is inconsistent at {csv_path}:{line}"
)
key = cache_key(source_sha, target_sha, memory)
normalized = {field: row.get(field, "") for field in FIELDS}
normalized.update(source=source_node, target=target_node,
source_sha256=source_sha, target_sha256=target_sha,
memory=memory)
previous = migrated.get(key)
comparable = ("payload", "container", "stage_start", "margin", "feasible", "error")
if previous is not None and any(
str(previous.get(item, "")) != str(normalized.get(item, ""))
for item in comparable
):
raise RouteSearchError(f"conflicting cached geometry for {key}")
migrated[key] = normalized
return migrated
Job = tuple[int, int, int, str, str, str, str]
def all_jobs(images: list[dict[str, object]]) -> list[Job]:
"""Enumerate every valid page-aligned workspace for every forward edge."""
jobs: list[Job] = []
endpoint = len(images) - 1
# Node 0 may only use the byte-identical, physically qualified 0->1 package.
# Node 1 still runs the fixed-workspace receiver, so measure each of its
# possible forward transitions at exactly that legacy workspace.
for target in range(2, endpoint + 1):
jobs.append((1, target, FIXED_MEMORY, str(images[1]["path"]),
str(images[target]["path"]), str(images[1]["sha256"]),
str(images[target]["sha256"])))
for source in range(2, endpoint):
source_size = int(images[source]["size"])
for target in range(source + 1, endpoint + 1):
target_size = int(images[target]["size"])
first_page = align_up(max(source_size + 2 * PAGE, target_size)) // PAGE
for memory_page in range(first_page, AVAILABLE_PAGES):
jobs.append((source, target, memory_page * PAGE,
str(images[source]["path"]), str(images[target]["path"]),
str(images[source]["sha256"]), str(images[target]["sha256"])))
return jobs
def geometry_job(args: tuple[int, int, int, str, str, str, str, str]) -> dict[str, object]:
try:
import detools
except ImportError as exc:
raise RouteSearchError(
"detools is required to generate geometry; run this tool in the "
"detools pipx environment"
) from exc
source, target, memory, from_raw, to_raw, source_sha, target_sha, patches_raw = args
patch = Path(patches_raw) / f"{source_sha}-{target_sha}-{memory // PAGE:03d}.patch"
try:
detools.create_patch_filenames(
from_raw, to_raw, str(patch), compression="crle", patch_type="in-place",
algorithm="bsdiff", suffix_array_algorithm="divsufsort",
memory_size=memory, segment_size=SEGMENT, use_mmap=True,
)
payload = patch.stat().st_size
total = container_size(payload)
stage_start = align_down(STAGE_CEILING - total)
margin = stage_start - (APP_BASE + memory)
error = ""
except Exception as exc: # detools reports several backend exception types
detail = f"{type(exc).__name__}: {exc}"[-500:].replace("\n", " ")
raise RouteSearchError(
f"detools geometry failed for {source}->{target} at 0x{memory:X}: {detail}"
) from exc
finally:
patch.unlink(missing_ok=True)
return {"source": source, "target": target, "source_sha256": source_sha,
"target_sha256": target_sha, "memory": memory, "payload": payload,
"container": total, "stage_start": stage_start, "margin": margin,
"feasible": payload >= 0 and margin >= 0, "error": error}
def project_cache(cache: dict[tuple[str, str, int], dict[str, object]],
images: list[dict[str, object]],
required: set[tuple[str, str, int]]) -> list[dict[str, object]]:
index = {str(record["sha256"]): int(record["node"]) for record in images}
rows: list[dict[str, object]] = []
for key in sorted(required, key=lambda item: (index[item[0]], index[item[1]], item[2])):
if key not in cache:
raise RouteSearchError(f"required cache geometry is missing: {key}")
row = dict(cache[key])
if int(row.get("payload", -1)) < 0 or str(row.get("error", "")):
raise RouteSearchError(
f"required cache geometry is not a successful measurement: {key}"
)
row.update(source=index[key[0]], target=index[key[1]],
source_sha256=key[0], target_sha256=key[1], memory=key[2])
rows.append(row)
return rows
def write_atomic_text(path: Path, contents: str) -> None:
"""Replace one regular output without ever following its pathname symlink."""
if path.is_symlink() or (path.exists() and not path.is_file()):
raise RouteSearchError(f"output path is not a regular file: {path}")
path.parent.mkdir(parents=True, exist_ok=True)
descriptor, temporary_name = tempfile.mkstemp(
prefix=f".{path.name}.", dir=path.parent
)
temporary = Path(temporary_name)
descriptor_open = True
try:
with os.fdopen(
descriptor, "w", encoding="ascii", newline="\n"
) as output:
descriptor_open = False
output.write(contents)
output.flush()
os.fsync(output.fileno())
temporary.chmod(0o600)
os.replace(temporary, path)
except BaseException:
if descriptor_open:
try:
os.close(descriptor)
except OSError:
pass
temporary.unlink(missing_ok=True)
raise
def write_csv(path: Path, rows: list[dict[str, object]]) -> None:
if path.is_symlink() or (path.exists() and not path.is_file()):
raise RouteSearchError(f"output path is not a regular file: {path}")
path.parent.mkdir(parents=True, exist_ok=True)
descriptor, temporary_name = tempfile.mkstemp(
prefix=f".{path.name}.", dir=path.parent
)
temporary = Path(temporary_name)
descriptor_open = True
try:
with os.fdopen(descriptor, "w", newline="", encoding="ascii") as output:
descriptor_open = False
writer = csv.DictWriter(
output, fieldnames=FIELDS, lineterminator="\n", extrasaction="ignore"
)
writer.writeheader()
writer.writerows(rows)
output.flush()
os.fsync(output.fileno())
temporary.chmod(0o600)
os.replace(temporary, path)
except BaseException:
if descriptor_open:
try:
os.close(descriptor)
except OSError:
pass
temporary.unlink(missing_ok=True)
raise
def select_route(rows: list[dict[str, object]], images: list[dict[str, object]],
baseline_size: int, output: Path, complete: bool) -> dict[str, object]:
endpoint = len(images) - 1
baseline_stage = align_down(STAGE_CEILING - baseline_size)
baseline_margin = baseline_stage - (APP_BASE + FIXED_MEMORY)
if baseline_margin < 0:
raise RouteSearchError("pinned first package does not fit")
edges: dict[tuple[int, int], dict[str, object]] = {
(0, 1): {"source": 0, "target": 1, "memory": FIXED_MEMORY,
"container": baseline_size, "stage_start": baseline_stage,
"margin": baseline_margin, "feasible": True}
}
for row in rows:
if int(row["source"]) == 0:
# Older evidence tables measured these irrelevant shortcuts. Keep
# them countable for archive verification, but never admit them to
# the route graph; node 0 is pinned unconditionally to node 1.
continue
if not truth(row.get("feasible", False)):
continue
key = int(row["source"]), int(row["target"])
rank = (int(row["container"]), -int(row["margin"]), int(row["memory"]))
old = edges.get(key)
if old is None or rank < (int(old["container"]), -int(old["margin"]), int(old["memory"])):
edges[key] = row
best: dict[int, tuple[int, int, list[int]]] = {0: (0, 0, [0])}
hop_distance = [sys.maxsize] * len(images)
route_count = [0] * len(images)
hop_distance[0], route_count[0] = 0, 1
outgoing: dict[int, list[tuple[int, dict[str, object]]]] = {}
for (source, target), row in edges.items():
outgoing.setdefault(source, []).append((target, row))
for source in range(endpoint):
if source not in best:
continue
for target, row in outgoing.get(source, []):
candidate = (best[source][0] + 1,
best[source][1] + int(row["container"]),
best[source][2] + [target])
if target not in best or candidate < best[target]:
best[target] = candidate
distance = hop_distance[source] + 1
if distance < hop_distance[target]:
hop_distance[target], route_count[target] = distance, route_count[source]
elif distance == hop_distance[target]:
route_count[target] += route_count[source]
common = {"schema": 2, "app_base": f"0x{APP_BASE:X}",
"stage_ceiling": f"0x{STAGE_CEILING:X}", "node_count": len(images),
"search_complete": complete, "candidate_geometries": len(rows),
"feasible_edges": len(edges),
"objective": "minimum packages, then minimum total container bytes"}
if endpoint not in best:
result = {**common, "status": "unreachable", "reachable_nodes": sorted(best),
"endpoint_node": endpoint,
"endpoint_incoming_feasible": sorted(
source for source, target in edges if target == endpoint
)}
else:
nodes = best[endpoint][2]
steps = []
for source, target in zip(nodes, nodes[1:]):
row = edges[source, target]
steps.append({"source_node": source, "target_node": target,
"inplace_memory": f"0x{int(row['memory']):X}",
"reuse_baseline_package": source == 0 and target == 1,
"expected_container_size": int(row["container"]),
"expected_staging_margin": int(row["margin"]),
"expected_target_sha256": images[target]["sha256"],
"expected_target_version": images[target].get("version", "unknown")})
result = {**common, "status": "reachable", "nodes": nodes,
"shortest_package_count": hop_distance[endpoint],
"shortest_route_count": route_count[endpoint],
"selected_total_bytes": best[endpoint][1], "steps": steps}
write_atomic_text(
output, json.dumps(result, indent=2, sort_keys=True) + "\n"
)
return result
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--inventory", type=Path, required=True)
parser.add_argument("--reuse", action="append", default=[], metavar="IMAGES_JSON=GEOMETRY_CSV")
parser.add_argument("--work-dir", type=Path, required=True)
parser.add_argument("--workers", type=int, default=min(8, os.cpu_count() or 1))
parser.add_argument("--no-generate", action="store_true")
args = parser.parse_args(argv)
if args.workers < 1:
parser.error("--workers must be positive")
args.work_dir.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(
prefix=".frozen-inventory-", dir=args.work_dir
) as frozen_raw:
frozen = Path(frozen_raw)
inventory_path = snapshot_inventory(
args.inventory, frozen / "current" / "images.json"
)
images = load_inventory(inventory_path)
baseline_size = _integer(
images[1].get("baseline_container_size"),
"node 1 baseline_container_size",
)
cache: dict[tuple[str, str, int], dict[str, object]] = {}
comparable = (
"payload", "container", "stage_start", "margin", "feasible", "error"
)
for reuse_number, value in enumerate(args.reuse, 1):
left, separator, right = value.partition("=")
if not separator:
parser.error("--reuse requires IMAGES_JSON=GEOMETRY_CSV")
reuse_root = frozen / f"reuse-{reuse_number:03d}"
reuse_inventory = snapshot_inventory(
Path(left), reuse_root / "images.json"
)
reuse_csv = reuse_root / "geometry.csv"
try:
shutil.copy2(Path(right), reuse_csv, follow_symlinks=True)
except OSError as exc:
raise RouteSearchError(
f"cannot snapshot geometry cache {right}: {exc}"
) from exc
for key, row in migrate_csv(reuse_inventory, reuse_csv).items():
old = cache.get(key)
if old is not None and any(
str(old.get(field, "")) != str(row.get(field, ""))
for field in comparable
):
raise RouteSearchError(f"conflicting reuse inputs for {key}")
cache[key] = row
jobs = all_jobs(images)
required = {cache_key(job[5], job[6], job[2]) for job in jobs}
remaining = [
job for job in jobs
if cache_key(job[5], job[6], job[2]) not in cache
]
print(
f"nodes={len(images)} geometries={len(jobs)} "
f"reused={len(required & cache.keys())} remaining={len(remaining)}"
)
if remaining and not args.no_generate:
# Patch payloads are disposable worker scratch. Keep them in a
# uniquely owned directory so cleanup can never remove a caller's
# pre-existing `work-dir/patches` tree.
with tempfile.TemporaryDirectory(
prefix=".route-patches-", dir=args.work_dir
) as patches_raw:
patches = Path(patches_raw)
with ProcessPoolExecutor(max_workers=args.workers) as pool:
futures = [
pool.submit(geometry_job, (*job, str(patches)))
for job in remaining
]
for done, future in enumerate(as_completed(futures), 1):
row = future.result()
key = cache_key(
str(row["source_sha256"]),
str(row["target_sha256"]),
int(row["memory"]),
)
cache[key] = row
if done % 100 == 0 or done == len(futures):
print(f"measured={done}/{len(remaining)}", flush=True)
completed = required & cache.keys()
rows = project_cache(cache, images, completed)
write_csv(args.work_dir / "geometry.csv", rows)
complete = completed == required
result = select_route(
rows, images, baseline_size, args.work_dir / "route.json",
complete=complete,
)
print(json.dumps(result, indent=2, sort_keys=True))
return 0 if complete else 3
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,688 @@
#!/usr/bin/env python3
"""Focused tests for variable-node compact RAK3401 bundle inputs."""
from __future__ import annotations
import hashlib
import json
import os
from pathlib import Path
import struct
import sys
import tempfile
import unittest
from unittest import mock
sys.path.insert(0, str(Path(__file__).resolve().parent))
import build_rak3401_compact_bundle as compact
def firmware(body: bytes, version: str) -> bytes:
hardware = compact.EXPECTED_HARDWARE.encode("ascii").ljust(32, b"\0")
return (
body
+ b"EndF"
+ struct.pack("<I", len(body))
+ hashlib.sha256(body).digest()[:8]
+ struct.pack(
"<II", compact.motalib.pack_version(version), compact.EXPECTED_TARGET_ID
)
+ hardware
)
def uf2(image: bytes, payload_size: int = 256) -> bytes:
padded_size = compact.align_up(len(image), payload_size)
encoded = image + b"\xFF" * (padded_size - len(image))
block_count = len(encoded) // payload_size
blocks = []
for number in range(block_count):
block = bytearray(compact.UF2_BLOCK_SIZE)
struct.pack_into(
"<IIIIIIII", block, 0,
compact.UF2_MAGIC_START0,
compact.UF2_MAGIC_START1,
compact.UF2_FLAG_FAMILY_ID,
compact.APP_BASE + number * payload_size,
payload_size,
number,
block_count,
compact.UF2_NRF52840_FAMILY_ID,
)
block[compact.UF2_DATA_OFFSET:compact.UF2_DATA_OFFSET + payload_size] = (
encoded[number * payload_size:(number + 1) * payload_size]
)
struct.pack_into(
"<I", block, compact.UF2_BLOCK_SIZE - 4, compact.UF2_MAGIC_END
)
blocks.append(bytes(block))
return b"".join(blocks)
class CompactRouteInputTests(unittest.TestCase):
def schema2_route(self) -> dict[str, object]:
return {
"schema": 2,
"status": "reachable",
"search_complete": True,
"app_base": "0x26000",
"stage_ceiling": "0xD4000",
"node_count": 4,
"objective": "minimum packages, then minimum total container bytes",
"candidate_geometries": 100,
"feasible_edges": 4,
"shortest_package_count": 2,
"shortest_route_count": 1,
"selected_total_bytes": 300,
"steps": [
{
"source_node": 0,
"target_node": 1,
"inplace_memory": "0x98000",
"reuse_baseline_package": True,
"expected_container_size": 100,
"expected_staging_margin": 1,
"expected_target_sha256": "1" * 64,
"expected_target_version": "1.16.7.9",
},
{
"source_node": 1,
"target_node": 3,
"inplace_memory": "0x98000",
"reuse_baseline_package": False,
"expected_container_size": 200,
"expected_staging_margin": 2,
"expected_target_sha256": "2" * 64,
"expected_target_version": "1.17.1.5",
},
],
}
def test_existing_schema1_route_remains_accepted(self) -> None:
route = Path(__file__).with_name("rak3401_compact_route.json")
steps, document = compact.read_route(route)
self.assertEqual(document["schema"], 1)
self.assertEqual(document["endpoint_node"], 30)
self.assertEqual(len(steps), 9)
def test_schema2_route_is_normalized_for_bundle_provenance(self) -> None:
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "route.json"
path.write_text(json.dumps(self.schema2_route()), encoding="ascii")
steps, document = compact.read_route(path)
self.assertEqual([step["target_node"] for step in steps], [1, 3])
self.assertEqual(document["endpoint_node"], 3)
self.assertTrue(document["search"]["search_complete"])
self.assertEqual(document["search"]["selected_total_bytes"], 300)
def test_public_route_search_drops_schema1_private_fields(self) -> None:
route = Path(__file__).with_name("rak3401_compact_route.json")
_steps, document = compact.read_route(route)
document["search"].update({
"password": "must-not-be-archived",
"local_path": "/tmp/private/route.json",
"nested": {"api_token": "must-not-be-archived"},
})
public = compact.public_route_search(1, document)
self.assertNotIn("password", public)
self.assertNotIn("local_path", public)
self.assertNotIn("nested", public)
self.assertEqual(
set(public),
{
"objective", "shortest_package_count", "selected_total_bytes",
"page_size", "candidate_pairs", "candidate_geometries",
"feasible_edges", "shortest_route_count",
},
)
def test_schema2_route_must_be_a_complete_reachable_search(self) -> None:
for field, value, message in (
("status", "unreachable", "does not reach"),
("search_complete", False, "incomplete"),
):
with self.subTest(field=field), tempfile.TemporaryDirectory() as directory:
document = self.schema2_route()
document[field] = value
path = Path(directory) / "route.json"
path.write_text(json.dumps(document), encoding="ascii")
with self.assertRaisesRegex(compact.CompactBuildError, message):
compact.read_route(path)
class CompactImageInventoryTests(unittest.TestCase):
def test_schema2_snapshot_freezes_manifest_and_referenced_images(self) -> None:
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
source = root / "source"
source.mkdir()
image = firmware(b"frozen body", "1.17.1.5")
image_path = source / "image.bin"
image_path.write_bytes(image)
record = {
"node": 0,
"path": image_path.name,
"size": len(image),
"sha256": hashlib.sha256(image).hexdigest(),
"body_hash": hashlib.sha256(image[:-56]).digest()[:8].hex(),
"version": "1.17.1.5",
}
manifest = source / "images.json"
manifest.write_text(json.dumps({"images": [record]}), encoding="ascii")
frozen = compact.snapshot_schema2_inventory(
manifest, root / "frozen" / "images.json"
)
image_path.write_bytes(b"changed")
manifest.write_text("{}", encoding="ascii")
images, _sources = compact.read_image_inventory(frozen, 1)
self.assertEqual(images[0], image)
def test_schema1_snapshot_freezes_manifest_sibling_zips(self) -> None:
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
source = root / "source"
source.mkdir()
archive = source / "bridge.zip"
archive.write_bytes(b"frozen zip")
manifest = source / "bridges.json"
manifest.write_text(
json.dumps({"targets": [{"zip": archive.name}]}),
encoding="ascii",
)
frozen = compact.snapshot_schema1_manifest(
manifest, root / "frozen" / manifest.name
)
archive.write_bytes(b"changed")
manifest.write_text("{}", encoding="ascii")
self.assertEqual(
json.loads(frozen.read_text(encoding="ascii")),
{"targets": [{"zip": "bridge.zip"}]},
)
self.assertEqual(
(frozen.parent / "bridge.zip").read_bytes(), b"frozen zip"
)
def test_inventory_validates_order_hash_size_identity_and_version(self) -> None:
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
records = []
expected = {}
for node, version in enumerate(("1.16.7.0", "1.16.7.9", "1.17.1.5")):
image = firmware(bytes([node + 1]) * (128 + node), version)
image_path = root / f"image-{node:02d}.bin"
image_path.write_bytes(image)
expected[node] = image
records.append({
"node": node,
"path": image_path.name,
"size": len(image),
"sha256": hashlib.sha256(image).hexdigest(),
"body_hash": hashlib.sha256(image[:-56]).digest()[:8].hex(),
"version": version,
})
manifest = root / "images.json"
manifest.write_text(json.dumps({"images": records}), encoding="ascii")
images, sources = compact.read_image_inventory(manifest, 3)
self.assertEqual(images, expected)
self.assertTrue(sources[1].startswith("image-sha256:"))
def test_inventory_rejects_a_stale_image_pin(self) -> None:
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
image = firmware(b"body", "1.17.1.5")
(root / "image-00.bin").write_bytes(image)
record = {
"node": 0,
"path": "image-00.bin",
"size": len(image),
"sha256": "0" * 64,
"body_hash": hashlib.sha256(b"body").digest()[:8].hex(),
"version": "1.17.1.5",
}
manifest = root / "images.json"
manifest.write_text(
json.dumps({"images": [record, record, record]}), encoding="ascii"
)
with self.assertRaisesRegex(compact.CompactBuildError, "SHA-256 mismatch"):
compact.read_image_inventory(manifest, 3)
def test_bundled_inventory_drops_machine_local_paths(self) -> None:
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
source = root / "source.json"
destination = root / "bundled.json"
source.write_text(
json.dumps({
"baseline_mota": "/tmp/private/step.mota",
"admin_password": "must-not-be-archived",
"api_token": "must-not-be-archived",
"notes": "must-not-be-archived",
"images": [{
"node": 0,
"path": "/tmp/private/image.bin",
"size": 123,
"sha256": "1" * 64,
"body_hash": "2" * 16,
"version": "1.16.7.0",
"latitude": 47.0,
"nested": {
"source_path": "/tmp/private/source.bin",
"private_key": "must-not-be-archived",
"keep": 1,
},
}],
}),
encoding="ascii",
)
compact.write_inventory_provenance(source, destination)
bundled = json.loads(destination.read_text(encoding="ascii"))
self.assertNotIn("path", bundled["images"][0])
self.assertNotIn("baseline_mota", bundled)
self.assertNotIn("admin_password", bundled)
self.assertNotIn("api_token", bundled)
self.assertNotIn("notes", bundled)
self.assertEqual(
bundled,
{
"schema": 2,
"images": [{
"node": 0,
"size": 123,
"sha256": "1" * 64,
"body_hash": "2" * 16,
"version": "1.16.7.0",
}],
},
)
def test_inventory_rejects_wrong_declared_body_hash(self) -> None:
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
records = []
for node in range(3):
image = firmware(bytes([node + 1]) * 32, f"1.16.7.{node}")
image_path = root / f"image-{node}.bin"
image_path.write_bytes(image)
records.append({
"node": node, "path": image_path.name, "size": len(image),
"sha256": hashlib.sha256(image).hexdigest(),
"body_hash": "0" * 16, "version": f"1.16.7.{node}",
})
manifest = root / "images.json"
manifest.write_text(json.dumps({"images": records}), encoding="ascii")
with self.assertRaisesRegex(compact.CompactBuildError, "body hash mismatch"):
compact.read_image_inventory(manifest, 3)
class CompactSimulatorTests(unittest.TestCase):
def test_exact_required_simulators_are_accepted(self) -> None:
with tempfile.TemporaryDirectory() as directory:
preview5 = Path(directory) / "preview5"
current = Path(directory) / "current"
preview5.write_bytes(b"p5")
current.write_bytes(b"current")
hashes = {
preview5: compact.REQUIRED_SIMULATORS["preview5"]["sha256"],
current: compact.REQUIRED_SIMULATORS["current"]["sha256"],
}
with mock.patch.object(compact.common, "sha256_file", side_effect=hashes.get):
result = compact.parse_simulators([
f"preview5={preview5}", f"current={current}"
])
self.assertEqual([label for label, _path in result], ["preview5", "current"])
def test_missing_or_wrong_simulator_is_rejected(self) -> None:
with tempfile.TemporaryDirectory() as directory:
simulator = Path(directory) / "sim"
simulator.write_bytes(b"wrong")
for values, digest in (([], None), ([f"preview5={simulator}"], "0" * 64)):
with self.subTest(values=values), mock.patch.object(
compact.common, "sha256_file", return_value=digest
):
with self.assertRaisesRegex(compact.CompactBuildError, "require exactly"):
compact.parse_simulators(values)
class CompactUf2Tests(unittest.TestCase):
def test_exact_app_only_uf2_is_accepted(self) -> None:
with tempfile.TemporaryDirectory() as directory:
image = firmware(b"endpoint" * 41, "1.17.1.5")
path = Path(directory) / "endpoint.uf2"
path.write_bytes(uf2(image))
compact.validate_uf2_firmware(path, image, "test UF2")
def test_wrong_family_and_non_app_address_are_rejected(self) -> None:
image = firmware(b"endpoint", "1.17.1.5")
for label, offset, value, message in (
("family", 28, 0xDEADBEEF, "nRF52840"),
("address", 12, compact.APP_BASE - 256, "app-only"),
):
with self.subTest(label=label), tempfile.TemporaryDirectory() as directory:
raw = bytearray(uf2(image))
struct.pack_into("<I", raw, offset, value)
path = Path(directory) / "endpoint.uf2"
path.write_bytes(raw)
with self.assertRaisesRegex(compact.CompactBuildError, message):
compact.validate_uf2_firmware(path, image, "test UF2")
def test_duplicate_block_and_firmware_mismatch_are_rejected(self) -> None:
image = firmware(b"x" * 600, "1.17.1.5")
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
duplicate = bytearray(uf2(image))
struct.pack_into("<I", duplicate, compact.UF2_BLOCK_SIZE + 20, 0)
duplicate_path = root / "duplicate.uf2"
duplicate_path.write_bytes(duplicate)
with self.assertRaisesRegex(compact.CompactBuildError, "repeats"):
compact.validate_uf2_firmware(duplicate_path, image, "test UF2")
mismatch = bytearray(uf2(image))
mismatch[compact.UF2_DATA_OFFSET] ^= 1
mismatch_path = root / "mismatch.uf2"
mismatch_path.write_bytes(mismatch)
with self.assertRaisesRegex(compact.CompactBuildError, "does not match"):
compact.validate_uf2_firmware(mismatch_path, image, "test UF2")
def test_non_erased_final_padding_is_rejected(self) -> None:
image = firmware(b"odd", "1.17.1.5")
with tempfile.TemporaryDirectory() as directory:
raw = bytearray(uf2(image))
raw[compact.UF2_DATA_OFFSET + len(image)] = 0
path = Path(directory) / "padding.uf2"
path.write_bytes(raw)
with self.assertRaisesRegex(compact.CompactBuildError, "non-erased"):
compact.validate_uf2_firmware(path, image, "test UF2")
class CompactToolProvenanceTests(unittest.TestCase):
def test_required_versions_and_actual_launcher_hashes_are_recorded(self) -> None:
motatool = Path("/tools/motatool")
detools = Path("/tools/detools")
hashes = {motatool: "1" * 64, detools: "2" * 64}
with mock.patch.object(
compact, "run", side_effect=["motatool 0.1.0\n", "0.53.0\n"]
), mock.patch.object(compact.common, "sha256_file", side_effect=hashes.get):
result = compact.tool_provenance(motatool, detools)
self.assertEqual(result["motatool"]["version"], "0.1.0")
self.assertEqual(
result["motatool"]["asserted_source_commit"], compact.MOTATOOL_COMMIT
)
self.assertEqual(result["motatool"]["executable_sha256"], "1" * 64)
self.assertEqual(result["detools"]["launcher_sha256"], "2" * 64)
def test_wrong_tool_versions_fail_closed(self) -> None:
for outputs, message in (
(["motatool 0.2.0\n"], "motatool version"),
(["motatool 0.1.0\n", "0.54.0\n"], "detools version"),
):
with self.subTest(outputs=outputs), mock.patch.object(
compact, "run", side_effect=outputs
):
with self.assertRaisesRegex(compact.CompactBuildError, message):
compact.tool_provenance(Path("motatool"), Path("detools"))
class CompactGeometryEvidenceTests(unittest.TestCase):
def make_evidence(self, root: Path) -> tuple[Path, Path, list[dict[str, object]]]:
records = []
for node, version in enumerate(("1.16.7.0", "1.16.7.9", "1.17.1.3", "1.17.1.5")):
image = firmware(bytes([node + 1]) * (64 + node), version)
image_path = root / f"image-{node:02d}.bin"
image_path.write_bytes(image)
records.append({
"node": node, "path": image_path.name, "size": len(image),
"sha256": hashlib.sha256(image).hexdigest(),
"body_hash": hashlib.sha256(image[:-56]).digest()[:8].hex(),
"version": version,
**({"baseline_container_size": 100} if node == 1 else {}),
})
inventory_path = root / "inventory.json"
inventory_path.write_text(json.dumps({"images": records}), encoding="ascii")
inventory = compact.route_search.load_inventory(inventory_path)
rows = []
for job in compact.route_search.all_jobs(inventory):
source, target, memory, _from, _to, source_sha, target_sha = job
if source == 1 and target == 3:
payload = 10
else:
# A successfully generated patch may be too large for staging;
# that is valid infeasible evidence. A tool exception is not.
payload = 700_000
container = compact.route_search.container_size(payload)
stage_start = compact.route_search.align_down(
compact.STAGE_CEILING - container
)
margin = stage_start - (compact.APP_BASE + memory)
feasible, error = margin >= 0, ""
rows.append({
"source": source, "target": target, "source_sha256": source_sha,
"target_sha256": target_sha, "memory": memory, "payload": payload,
"container": container, "stage_start": stage_start, "margin": margin,
"feasible": feasible, "error": error,
})
geometry_path = root / "geometry.csv"
compact.route_search.write_csv(geometry_path, rows)
route_path = root / "route.json"
compact.route_search.select_route(rows, inventory, 100, route_path, complete=True)
return inventory_path, route_path, rows
def test_complete_geometry_reproduces_declared_route(self) -> None:
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
inventory, route, _rows = self.make_evidence(root)
result = compact.validate_geometry_results(root / "geometry.csv", inventory, route)
self.assertEqual(result["nodes"], [0, 1, 3])
def test_legacy_source_zero_measurement_is_accepted_but_not_routed(self) -> None:
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
inventory_path, route_path, rows = self.make_evidence(root)
inventory = compact.route_search.load_inventory(inventory_path)
payload = 10
container = compact.route_search.container_size(payload)
stage_start = compact.route_search.align_down(
compact.STAGE_CEILING - container
)
margin = stage_start - (compact.APP_BASE + compact.FIXED_WORKSPACE)
rows.append({
"source": 0,
"target": 2,
"source_sha256": inventory[0]["sha256"],
"target_sha256": inventory[2]["sha256"],
"memory": compact.FIXED_WORKSPACE,
"payload": payload,
"container": container,
"stage_start": stage_start,
"margin": margin,
"feasible": margin >= 0,
"error": "",
})
compact.route_search.write_csv(root / "geometry.csv", rows)
compact.route_search.select_route(
rows, inventory, 100, route_path, complete=True
)
result = compact.validate_geometry_results(
root / "geometry.csv", inventory_path, route_path
)
self.assertEqual(result["nodes"], [0, 1, 3])
self.assertEqual(result["candidate_geometries"], len(rows))
def test_geometry_tamper_is_rejected(self) -> None:
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
inventory, route, rows = self.make_evidence(root)
rows[0]["container"] = 123
compact.route_search.write_csv(root / "geometry.csv", rows)
with self.assertRaisesRegex(compact.CompactBuildError, "inconsistent"):
compact.validate_geometry_results(root / "geometry.csv", inventory, route)
def test_missing_and_extra_geometry_are_rejected(self) -> None:
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
inventory, route, rows = self.make_evidence(root)
for label, altered, message in (
("missing", rows[:-1], "missing"),
("extra", rows + [{**rows[0], "memory": int(rows[0]["memory"]) + 1}], "extra"),
):
with self.subTest(label=label):
compact.route_search.write_csv(root / "geometry.csv", altered)
with self.assertRaisesRegex(compact.CompactBuildError, message):
compact.validate_geometry_results(root / "geometry.csv", inventory, route)
def test_route_metric_or_step_mismatch_is_rejected(self) -> None:
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
inventory, route, _rows = self.make_evidence(root)
document = json.loads(route.read_text(encoding="ascii"))
document["selected_total_bytes"] += 1
route.write_text(json.dumps(document), encoding="ascii")
with self.assertRaisesRegex(compact.CompactBuildError, "selected_total_bytes"):
compact.validate_geometry_results(root / "geometry.csv", inventory, route)
def test_failed_patch_job_cannot_be_exhaustive_evidence(self) -> None:
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
inventory, route, rows = self.make_evidence(root)
rows[0].update(
payload=-1, container=-1, stage_start=-1, margin=-1,
feasible=False, error="MemoryError: test",
)
compact.route_search.write_csv(root / "geometry.csv", rows)
with self.assertRaisesRegex(
compact.CompactBuildError, "cannot prove an exhaustive route search"
):
compact.validate_geometry_results(root / "geometry.csv", inventory, route)
def test_short_geometry_row_fails_cleanly(self) -> None:
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
inventory, route, _rows = self.make_evidence(root)
(root / "geometry.csv").write_text(
",".join(compact.route_search.FIELDS) + "\n1,2\n",
encoding="ascii",
)
with self.assertRaisesRegex(
compact.CompactBuildError, "integer|malformed|invalid"
):
compact.validate_geometry_results(root / "geometry.csv", inventory, route)
class CompactPhysicalValidationTests(unittest.TestCase):
def evidence(self) -> tuple[dict[str, object], dict[str, object]]:
expected = {
"chain_sha256": "1" * 64,
"start_sha256": "2" * 64,
"endpoint_sha256": "3" * 64,
"endpoint_body_hash": "a" * 16,
"endpoint_version": "1.17.1.5",
"output_rows": [{"target_body_hash": "5" * 16}],
"validation_steps": [{
"mota_sha256": "6" * 64,
"target_sha256": "7" * 64,
}],
}
document: dict[str, object] = {
"schema": 1,
"kind": compact.PHYSICAL_VALIDATION_KIND,
"status": "passed",
"chain_sha256": expected["chain_sha256"],
"start_sha256": expected["start_sha256"],
"endpoint_sha256": expected["endpoint_sha256"],
"endpoint_body_hash": expected["endpoint_body_hash"],
"endpoint_version": expected["endpoint_version"],
"step_count": 1,
"steps": [{
"step": 1,
"status": "passed",
"mota_sha256": "6" * 64,
"target_sha256": "7" * 64,
"target_body_hash": "5" * 16,
}],
"final_swd": {"status": "passed", "app_sha256": "3" * 64},
}
return document, expected
def test_exact_record_is_accepted_and_canonicalized(self) -> None:
document, expected = self.evidence()
document["endpoint_body_hash"] = str(document["endpoint_body_hash"]).upper()
result = compact.validate_physical_validation_record(document, **expected)
self.assertEqual(result["status"], "passed")
self.assertEqual(result["endpoint_body_hash"], "a" * 16)
def test_stale_package_or_incomplete_step_list_is_rejected(self) -> None:
for label, mutate, message in (
(
"stale",
lambda document: document["steps"][0].__setitem__(
"mota_sha256", "8" * 64
),
"does not match",
),
(
"incomplete",
lambda document: document.__setitem__("steps", []),
"every chain step",
),
):
with self.subTest(label=label):
document, expected = self.evidence()
mutate(document)
with self.assertRaisesRegex(compact.CompactBuildError, message):
compact.validate_physical_validation_record(document, **expected)
def test_extra_transcript_or_secret_fields_are_rejected(self) -> None:
document, expected = self.evidence()
document["admin_password"] = "must-not-be-archived"
with self.assertRaisesRegex(compact.CompactBuildError, "unexpected"):
compact.validate_physical_validation_record(document, **expected)
class CompactReproducibilityTests(unittest.TestCase):
def test_zip_metadata_does_not_depend_on_source_mtime(self) -> None:
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
archives = []
for number in (1, 2):
tree = root / f"tree-{number}" / "same-root"
tree.mkdir(parents=True)
item = tree / "payload.bin"
item.write_bytes(b"identical")
os.utime(item, (946684800 + number, 946684800 + number))
output = root / f"archive-{number}.zip"
compact.make_reproducible_zip(tree, output)
archives.append(output.read_bytes())
self.assertEqual(archives[0], archives[1])
def test_zip_output_inside_archived_tree_is_rejected(self) -> None:
with tempfile.TemporaryDirectory() as directory:
tree = Path(directory) / "tree"
tree.mkdir()
(tree / "payload.bin").write_bytes(b"payload")
with self.assertRaisesRegex(
compact.CompactBuildError, "outside the archived tree"
):
compact.make_reproducible_zip(tree, tree / "bundle.zip")
def test_zip_output_symlinked_inside_archived_tree_is_rejected(self) -> None:
with tempfile.TemporaryDirectory() as directory:
parent = Path(directory)
tree = parent / "tree"
tree.mkdir()
(tree / "payload.bin").write_bytes(b"payload")
alias = parent / "output-alias"
alias.symlink_to(tree, target_is_directory=True)
with self.assertRaisesRegex(
compact.CompactBuildError, "outside the archived tree"
):
compact.make_reproducible_zip(tree, alias / "bundle.zip")
if __name__ == "__main__":
unittest.main()
File diff suppressed because it is too large. Load diff
+381
View File
@@ -0,0 +1,381 @@
from __future__ import annotations
import csv
import hashlib
import json
from pathlib import Path
import struct
import sys
import tempfile
import unittest
from unittest import mock
sys.path.insert(0, str(Path(__file__).resolve().parent))
import rak3401_route_search as search
def firmware(body: bytes, version: str) -> bytes:
hardware = search.EXPECTED_HARDWARE.encode("ascii").ljust(32, b"\0")
return (
body
+ b"EndF"
+ struct.pack("<I", len(body))
+ hashlib.sha256(body).digest()[:8]
+ struct.pack(
"<II", search.motalib.pack_version(version), search.EXPECTED_TARGET_ID
)
+ hardware
)
class RouteSearchTests(unittest.TestCase):
def write_inventory(
self, root: Path, payloads: list[bytes], *, baseline_size: int = 100,
versions: list[str] | None = None,
) -> tuple[Path, list[dict[str, object]]]:
records = []
for node, payload in enumerate(payloads):
version = versions[node] if versions is not None else f"1.0.0.{node}"
encoded = firmware(payload, version)
image = root / f"image-{node:02d}.bin"
image.write_bytes(encoded)
record: dict[str, object] = {
"node": node,
"path": image.name,
"size": len(encoded),
"sha256": hashlib.sha256(encoded).hexdigest(),
"body_hash": hashlib.sha256(payload).digest()[:8].hex(),
"version": version,
}
if node == 1:
record["baseline_container_size"] = baseline_size
records.append(record)
manifest = root / "images.json"
manifest.write_text(json.dumps({"images": records}), encoding="ascii")
return manifest, records
def test_cache_migration_survives_inserted_node_and_remaps_indices(self) -> None:
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
old_dir, new_dir = root / "old", root / "new"
old_dir.mkdir()
new_dir.mkdir()
old_manifest, old = self.write_inventory(
old_dir, [b"A", b"B", b"C"],
versions=["1.0.0.0", "1.0.0.1", "1.0.0.2"],
)
cache = old_dir / "geometry.csv"
with cache.open("w", newline="", encoding="ascii") as output:
writer = csv.DictWriter(output, fieldnames=search.FIELDS)
writer.writeheader()
writer.writerow({
"source": 1, "target": 2, "memory": search.FIXED_MEMORY,
"payload": 7,
"container": search.container_size(7),
"stage_start": search.align_down(
search.STAGE_CEILING - search.container_size(7)
),
"margin": search.align_down(
search.STAGE_CEILING - search.container_size(7)
) - (search.APP_BASE + search.FIXED_MEMORY),
"feasible": True, "error": "",
})
new_manifest, _ = self.write_inventory(
new_dir, [b"A", b"X", b"B", b"C"],
versions=["1.0.0.0", "1.0.0.99", "1.0.0.1", "1.0.0.2"],
)
migrated = search.migrate_csv(old_manifest, cache)
key = search.cache_key(str(old[1]["sha256"]), str(old[2]["sha256"]),
search.FIXED_MEMORY)
self.assertIn(key, migrated)
projected = search.project_cache(
migrated, search.load_inventory(new_manifest), {key}
)
self.assertEqual((projected[0]["source"], projected[0]["target"]), (2, 3))
def test_all_jobs_covers_every_valid_page_workspace(self) -> None:
with tempfile.TemporaryDirectory() as directory:
manifest, _ = self.write_inventory(
Path(directory), [b"a", b"b", b"c" * 10000, b"d" * 12000]
)
jobs = search.all_jobs(search.load_inventory(manifest))
fixed = [job for job in jobs if job[0] < 2]
dynamic = [job for job in jobs if job[0] >= 2]
self.assertEqual(len(fixed), 2)
self.assertTrue(all(job[2] == search.FIXED_MEMORY for job in fixed))
self.assertTrue(all(job[0] == 1 for job in fixed))
inventory = search.load_inventory(manifest)
first_page = search.align_up(
max(
int(inventory[2]["size"]) + 2 * search.PAGE,
int(inventory[3]["size"]),
)
) // search.PAGE
self.assertEqual(
[job[2] for job in dynamic],
[page * search.PAGE for page in range(first_page, search.AVAILABLE_PAGES)],
)
self.assertEqual(len(jobs), 2 + search.AVAILABLE_PAGES - first_page)
def test_route_ignores_geometry_that_bypasses_pinned_first_bridge(self) -> None:
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
manifest, _ = self.write_inventory(root, [b"0", b"1", b"2"])
images = search.load_inventory(manifest)
result = search.select_route(
[
{
"source": 0, "target": 2, "memory": search.FIXED_MEMORY,
"container": 1, "stage_start": 0xC0000,
"margin": 10, "feasible": True,
},
{
"source": 1, "target": 2, "memory": search.FIXED_MEMORY,
"container": 10, "stage_start": 0xC0000,
"margin": 10, "feasible": True,
},
],
images, 100, root / "route.json", True,
)
self.assertEqual(result["nodes"], [0, 1, 2])
def test_cache_migration_rejects_inconsistent_numeric_geometry(self) -> None:
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
manifest, _ = self.write_inventory(root, [b"A", b"B", b"C"])
cache = root / "geometry.csv"
with cache.open("w", newline="", encoding="ascii") as output:
writer = csv.DictWriter(output, fieldnames=search.FIELDS)
writer.writeheader()
writer.writerow({
"source": 1, "target": 2, "memory": search.FIXED_MEMORY,
"payload": 7, "container": 999, "stage_start": 800000,
"margin": 1, "feasible": True, "error": "",
})
with self.assertRaisesRegex(
search.RouteSearchError, "inconsistent cached geometry"
):
search.migrate_csv(manifest, cache)
def test_cache_migration_rejects_failed_geometry(self) -> None:
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
manifest, _ = self.write_inventory(root, [b"A", b"B", b"C"])
cache = root / "geometry.csv"
with cache.open("w", newline="", encoding="ascii") as output:
writer = csv.DictWriter(output, fieldnames=search.FIELDS)
writer.writeheader()
writer.writerow({
"source": 1, "target": 2, "memory": search.FIXED_MEMORY,
"payload": -1, "container": -1, "stage_start": -1,
"margin": -1, "feasible": False, "error": "out of memory",
})
with self.assertRaisesRegex(
search.RouteSearchError, "cannot prove an exhaustive search"
):
search.migrate_csv(manifest, cache)
def test_geometry_tool_error_aborts_instead_of_becoming_infeasible(self) -> None:
class BrokenDetools:
@staticmethod
def create_patch_filenames(*_args: object, **_kwargs: object) -> None:
raise OSError("disk full")
with tempfile.TemporaryDirectory() as directory, mock.patch.dict(
sys.modules, {"detools": BrokenDetools}
):
with self.assertRaisesRegex(search.RouteSearchError, "disk full"):
search.geometry_job((
1, 2, search.FIXED_MEMORY,
str(Path(directory) / "from.bin"),
str(Path(directory) / "to.bin"),
"1" * 64, "2" * 64, directory,
))
def test_snapshot_inventory_is_immune_to_later_source_mutation(self) -> None:
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
source = root / "source"
source.mkdir()
manifest, _ = self.write_inventory(source, [b"A", b"B", b"C"])
frozen = search.snapshot_inventory(
manifest, root / "frozen" / "images.json"
)
source_image = source / "image-02.bin"
source_image.write_bytes(b"changed")
images = search.load_inventory(frozen)
self.assertNotEqual(Path(images[2]["path"]).read_bytes(), b"changed")
def test_generation_never_removes_a_preexisting_patches_directory(self) -> None:
class ImmediateFuture:
def __init__(self, value: dict[str, object]):
self._value = value
def result(self) -> dict[str, object]:
return self._value
class ImmediatePool:
def __init__(self, **_kwargs: object):
pass
def __enter__(self) -> "ImmediatePool":
return self
def __exit__(self, *_args: object) -> None:
pass
def submit(self, function: object, *args: object) -> ImmediateFuture:
return ImmediateFuture(function(*args)) # type: ignore[operator]
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
inventory_root = root / "inventory"
inventory_root.mkdir()
manifest, records = self.write_inventory(
inventory_root, [b"start", b"bridge", b"endpoint"]
)
work = root / "work"
existing = work / "patches"
existing.mkdir(parents=True)
sentinel = existing / "keep.txt"
sentinel.write_text("caller-owned", encoding="ascii")
source_sha = str(records[1]["sha256"])
target_sha = str(records[2]["sha256"])
job = (
1, 2, search.FIXED_MEMORY,
str(inventory_root / str(records[1]["path"])),
str(inventory_root / str(records[2]["path"])),
source_sha, target_sha,
)
def measured(args: tuple[object, ...]) -> dict[str, object]:
source, target, memory, *_rest = args
payload = 7
total = search.container_size(payload)
stage = search.align_down(search.STAGE_CEILING - total)
return {
"source": source, "target": target,
"source_sha256": source_sha,
"target_sha256": target_sha,
"memory": memory, "payload": payload,
"container": total, "stage_start": stage,
"margin": stage - (search.APP_BASE + int(memory)),
"feasible": True, "error": "",
}
with (
mock.patch.object(search, "all_jobs", return_value=[job]),
mock.patch.object(search, "geometry_job", side_effect=measured),
mock.patch.object(search, "ProcessPoolExecutor", ImmediatePool),
mock.patch.object(search, "as_completed", side_effect=lambda values: values),
):
self.assertEqual(
search.main([
"--inventory", str(manifest),
"--work-dir", str(work),
"--workers", "1",
]),
0,
)
self.assertEqual(sentinel.read_text(encoding="ascii"), "caller-owned")
def test_route_minimizes_hops_then_bytes(self) -> None:
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
manifest, _ = self.write_inventory(root, [b"0", b"1", b"2", b"3", b"4"])
images = search.load_inventory(manifest)
def edge(source: int, target: int, size: int) -> dict[str, object]:
return {
"source": source, "target": target, "memory": 0x1000,
"container": size, "stage_start": 0xC0000,
"margin": 100, "feasible": True,
}
# Both endpoint routes have three hops including the pinned 0->1.
# The path through node 3 is smaller and must win even though it is
# encountered after the path through node 2.
rows = [edge(1, 2, 100), edge(2, 4, 100),
edge(1, 3, 40), edge(3, 4, 50)]
result = search.select_route(rows, images, 100, root / "route.json", True)
self.assertEqual(result["nodes"], [0, 1, 3, 4])
self.assertEqual(result["shortest_package_count"], 3)
self.assertEqual(result["shortest_route_count"], 2)
self.assertEqual(result["selected_total_bytes"], 190)
# A direct 1->4 edge wins on hop count even when it costs more.
rows.append(edge(1, 4, 1000))
result = search.select_route(rows, images, 100, root / "route2.json", True)
self.assertEqual(result["nodes"], [0, 1, 4])
self.assertEqual(result["selected_total_bytes"], 1100)
def test_fixed_outputs_never_follow_preexisting_symlinks(self) -> None:
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
victim = root / "victim.txt"
victim.write_text("caller-owned", encoding="ascii")
geometry = root / "geometry.csv"
geometry.symlink_to(victim)
with self.assertRaisesRegex(search.RouteSearchError, "regular file"):
search.write_csv(geometry, [])
self.assertEqual(victim.read_text(encoding="ascii"), "caller-owned")
manifest, _ = self.write_inventory(
root, [b"start", b"bridge", b"endpoint"]
)
route = root / "route.json"
route.symlink_to(victim)
with self.assertRaisesRegex(search.RouteSearchError, "regular file"):
search.select_route(
[], search.load_inventory(manifest), 100, route, True
)
self.assertEqual(victim.read_text(encoding="ascii"), "caller-owned")
def test_invalid_inventory_is_rejected(self) -> None:
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
manifest, records = self.write_inventory(root, [b"one", b"two"])
cases = []
bad = json.loads(manifest.read_text())
bad["images"][1]["node"] = 3
cases.append((bad, "contiguous"))
bad = json.loads(manifest.read_text())
bad["images"][1]["sha256"] = bad["images"][0]["sha256"]
cases.append((bad, "SHA mismatch"))
bad = json.loads(manifest.read_text())
bad["images"][1]["path"] = "missing.bin"
cases.append((bad, "missing inventory image"))
for number, (document, message) in enumerate(cases):
candidate = root / f"bad-{number}.json"
candidate.write_text(json.dumps(document), encoding="ascii")
with self.subTest(message=message), self.assertRaisesRegex(
search.RouteSearchError, message
):
search.load_inventory(candidate)
def test_bridges_are_inserted_before_preserved_endpoint(self) -> None:
original = {
"schema": 1,
"images": [
{"node": 0, "kind": "start"},
{"node": 1, "kind": "old-bridge"},
{"node": 2, "kind": "endpoint", "path": "endpoint.bin"},
],
}
result = search.insert_bridges_before_endpoint(
original,
[{"node": 99, "kind": "new-bridge-1"}, {"kind": "new-bridge-2"}],
)
self.assertEqual(
[record["node"] for record in result["images"]], [0, 1, 2, 3, 4]
)
self.assertEqual(
[record["kind"] for record in result["images"]],
["start", "old-bridge", "new-bridge-1", "new-bridge-2", "endpoint"],
)
self.assertEqual(result["images"][-1]["path"], "endpoint.bin")
self.assertEqual(len(original["images"]), 3)
if __name__ == "__main__":
unittest.main()