#!/usr/bin/env python3 """Run pinned G2 emulator scenarios using a Docker asset volume.""" import argparse import copy import hashlib import http.server import json import os from pathlib import Path import shutil import stat import subprocess import sys import tempfile from datetime import datetime from uuid import uuid4 ROOT = Path(__file__).resolve().parent sys.path.insert(0, str(ROOT / 'tools')) from run_original_boot_screen import checked_asset from volume_storage import IMAGE, extract_volume, import_volume, pinned_inputs, select_profile, volume_name DEFAULT_VOLUME = 'blackwall-assets' SCENARIOS = { 'normal': 'Stock 2.4 bootloader -> main -> virtual touch and screen', 'unknown-boot-marker': 'Expected rejection at the virtual boot metadata boundary', 'post-screen-touch': 'Untouched stock baseline, matched no-input control, and post-screen virtual touch', 'imu-stock': 'Fresh stock boot, naturally ready IMU FIFO input, and matched no-input control', } def show_assets(profile): print('Docker image:', profile['image_id']) for group in ('assets', 'components'): for name, spec in profile[group].items(): print(f"{group}/{name}: {spec['path']} sha256={spec['sha256']}") def apply_images(workspace, profile, boot, main): for key, override in (('boot', boot), ('main', main)): if override: spec = profile['assets'][key] source = checked_asset(workspace, spec, override) target = workspace / spec['path'] if source != target: shutil.copyfile(source, target) def setup(args): source = args.source.expanduser().resolve() profile_file = select_profile(source, args.profile) if not profile_file: raise ValueError('Selected profile was not found in the supplied source directory') profile, entries = pinned_inputs(source, profile_file, args.boot_image, args.main_image) import_volume(args.volume, entries) print('Created Docker volume:', args.volume) show_assets(profile) return 0 def inspect_volume(args): with tempfile.TemporaryDirectory(prefix='blackwall-inspect-') as folder: root = Path(folder) profile_file = extract_volume(args.volume, root) profile = json.loads(profile_file.read_text()) apply_images(root, profile, args.boot_image, args.main_image) pinned_inputs(root, profile_file) print('Verified Docker volume:', args.volume) show_assets(profile) try: validate_post_screen_source(profile, root) except ValueError: print('Stock comparison scenarios: unavailable for this profile; see docs/architecture/docker-volume-workflow.md') else: print('Stock comparison scenarios: compatible (post-screen-touch, imu-stock)') return 0 def report(args): if args.scenario == 'post-screen-touch' and (args.capture or args.scenario_file): raise ValueError('post-screen-touch requires a fresh pinned volume, not --capture or --scenario-file') if args.scenario == 'imu-stock' and (args.capture or args.scenario_file): raise ValueError('imu-stock requires a fresh pinned volume, not --capture or --scenario-file') if args.capture and (args.scenario or args.scenario_file or args.boot_image or args.main_image): raise ValueError('--capture cannot be combined with a new scenario or firmware input') if args.scenario and args.scenario_file: raise ValueError('--scenario and --scenario-file cannot be combined') if not 1 <= args.port <= 65535: raise ValueError('--port must be 1..65535') if args.scenario == 'imu-stock': from imu_stock_scenario import require_private_workspace_owner_support require_private_workspace_owner_support() output = args.output.expanduser().resolve() if args.output else Path(tempfile.gettempdir()) / ('blackwall-report-' + datetime.now().strftime('%Y%m%d-%H%M%S') + '-' + uuid4().hex[:8]) if output.exists() or output.is_relative_to(ROOT): raise ValueError('Output must be a new directory outside the repository') output.mkdir(mode=0o700, parents=True) if args.scenario == 'imu-stock': try: profile_file = extract_volume(args.volume, output) profile = json.loads(profile_file.read_text()) apply_images(output, profile, args.boot_image, args.main_image) pinned_inputs(output, profile_file) from run_original_boot_screen import write_json write_json(profile_file, profile) validate_post_screen_source(profile, output) except (OSError, ValueError, RuntimeError, subprocess.SubprocessError, KeyError, TypeError, AttributeError): shutil.rmtree(output) raise status = run_imu_stock_report(output, profile_file) if status == 0 and args.serve: serve_report(output / 'run' / 'report', args.port) return status if args.scenario == 'post-screen-touch' and not args.capture: try: profile_file = extract_volume(args.volume, output) profile = json.loads(profile_file.read_text()) apply_images(output, profile, args.boot_image, args.main_image) pinned_inputs(output, profile_file) from run_original_boot_screen import write_json write_json(profile_file, profile) validate_post_screen_source(profile, output) from run_original_boot_screen import effective_stock_profile profile_file = effective_stock_profile(profile, output) or profile_file except (OSError, ValueError, RuntimeError, subprocess.SubprocessError, KeyError, TypeError, AttributeError): shutil.rmtree(output) raise return run_post_screen_report(args, output, profile_file) command = [sys.executable, '-B', str(ROOT / 'tools/blackwall_report.py'), '--workspace', str(output), '--output', str(output / 'run')] try: if args.capture: command += ['--capture', str(args.capture.expanduser().resolve())] else: profile_file = extract_volume(args.volume, output) profile = json.loads(profile_file.read_text()) apply_images(output, profile, args.boot_image, args.main_image) pinned_inputs(output, profile_file) if args.scenario in (None, 'normal') and not args.scenario_file: from run_original_boot_screen import effective_stock_profile profile_file = effective_stock_profile(profile, output) or profile_file command += ['--profile', str(profile_file), '--scenario', args.scenario or 'normal'] if args.scenario_file: command += ['--scenario-file', str(args.scenario_file.expanduser().resolve())] except (OSError, ValueError, RuntimeError, subprocess.SubprocessError): # The output was created by this invocation and no emulator run has started. shutil.rmtree(output) raise print('Output:', output, flush=True) result = subprocess.run(command, cwd=ROOT) page = output / 'run/report/index.html' if page.is_file(): print('\nReport:', page, flush=True) if args.serve: serve_report(page.parent, args.port) return result.returncode def serve_report(directory, port): class Handler(http.server.SimpleHTTPRequestHandler): def __init__(self, *a, **kw): super().__init__(*a, directory=str(directory), **kw) try: server = http.server.ThreadingHTTPServer(('127.0.0.1', port), Handler) except OSError as exc: raise ValueError('Could not start local server: ' + str(exc)) from exc print(f'Open http://127.0.0.1:{port}/ (Ctrl-C to stop)', flush=True) try: server.serve_forever() except KeyboardInterrupt: pass finally: server.server_close() def validate_post_screen_source(profile, workspace): """Check all source pins and runner basenames before any emulator starts.""" from run_original_boot_screen import PROFILE, PINNED_IMAGES, checked_asset, validate_profile from volume_storage import INITIAL_MEMORY validate_profile(profile) canonical = json.loads(PROFILE.read_text()) # Docker volume paths may differ, but every other canonical profile field is pinned. canonical = copy.deepcopy(canonical) for key in ('boot', 'main', 'sram', 'itcm'): canonical['assets'][key]['path'] = profile['assets'][key]['path'] if profile != canonical: raise ValueError('Comparison scenarios require the canonical stock24 profile and component pins. Create a new volume with the current stock profile; see docs/architecture/docker-volume-workflow.md') if profile['assets']['main']['path'].split('/')[-1] != 'main.bin': raise ValueError('Pinned runner requires main.bin in the reference directory') for key, basename in (('sram', 'sram-fill.bin'), ('itcm', 'itcm-fill.bin')): if profile['assets'][key]['path'].split('/')[-1] != basename: raise ValueError('Pinned runner requires ' + basename + ' in the reference directory') pins = {**PINNED_IMAGES, **{key: dict(bytes=value[0], sha256=value[1]) for key, value in INITIAL_MEMORY.items()}} for key in ('boot', 'main', 'sram', 'itcm'): path = checked_asset(workspace, profile['assets'][key]) pin = pins[key] if path.stat().st_size != pin['bytes'] or hashlib.sha256(path.read_bytes()).hexdigest() != pin['sha256']: raise ValueError('Post-screen scenario source asset failed its hash/size pin: ' + key) return True def run_post_screen_report(args, workspace, profile_file): """Run the untouched baseline and paired variants, then securely render evidence.""" from run_original_boot_screen import derive, run as run_boot from probe_post_screen_touch import audit_pair, execute_pair from post_screen_report import render_post_screen_report baseline = workspace / 'run' / 'baseline' pair = workspace / 'run' / 'pair' report_dir = workspace / 'run' / 'report' baseline.parent.mkdir(mode=0o700, parents=True) derive(profile_file, workspace, baseline, 'normal') if not run_boot(baseline): raise RuntimeError('Untouched stock baseline failed; private evidence was preserved') pair.mkdir(mode=0o700) execute_pair(pair, profile_file, workspace) paired = audit_pair(pair, baseline) (pair / 'post-screen-touch-audit.json').write_text(json.dumps(paired, indent=2) + '\n') if paired.get('passed') is not True: raise ValueError('Post-screen paired audit failed; private evidence was preserved') from run_original_boot_screen import audit as audit_boot baseline_audit = workspace / 'run' / 'baseline-independent-audit' baseline_result = audit_boot(baseline, baseline_audit) if baseline_result.get('passed') is not True: raise ValueError('Untouched stock baseline independent audit failed; private evidence was preserved') touch_audit = workspace / 'run' / 'touch-independent-audit' touch_capture_audit = audit_boot(pair / 'touch', touch_audit) if touch_capture_audit.get('passed') is not True: raise ValueError('Touch boot independent audit failed; private evidence was preserved') model = render_post_screen_report(pair / 'touch', touch_audit, report_dir, paired) print('Output:', workspace, flush=True) print('Report:', report_dir / 'index.html', flush=True) print('Nearest / final changed pixels:', model['touch_comparison']['different_pixels'], '/', model['touch_comparison']['final_different_pixels'], flush=True) if args.serve: class Handler(http.server.SimpleHTTPRequestHandler): def __init__(self, *a, **kw): super().__init__(*a, directory=str(report_dir), **kw) server = http.server.ThreadingHTTPServer(('127.0.0.1', args.port), Handler) try: print(f'Open http://127.0.0.1:{args.port}/ (Ctrl-C to stop)', flush=True) server.serve_forever() except KeyboardInterrupt: pass finally: server.server_close() return 0 def run_imu_stock_report(workspace, profile_file): """Run both fresh original-boot lanes; retain every failed live capture.""" from imu_stock_scenario import execute, audit_pair pair = workspace / 'run' / 'pair' pair.mkdir(mode=0o700, parents=True) input_result = execute(profile_file, workspace, pair / 'input', 'input') if input_result.get('passed') is not True: raise ValueError('Stock IMU input lane did not pass; first evidence was preserved') control_result = execute(profile_file, workspace, pair / 'control', 'control') if control_result.get('passed') is not True: raise ValueError('Stock IMU control lane did not pass; pair evidence was preserved') paired = audit_pair(pair / 'input' / 'capture', pair / 'control' / 'capture', pair / 'independent-audit', workspace=workspace) if paired.get('passed') is not True: raise ValueError('Independent stock IMU paired audit failed; pair evidence was preserved') report = workspace / 'run' / 'report' report.mkdir(mode=0o700) checks = paired['checks'] rows = ''.join('
Independent paired audit passed.
Fresh stock 2.4 bootloader reset through the first complete virtual screen. Natural gate and FIFO readiness were checked again before any IMU enqueue in both lanes. The input lane enqueued ten 32-byte packets. The control lane enqueued none. Both observed twenty 5 ms slices.
This is bounded virtual evidence for one stock 2.4 profile. It does not validate physical sensor timing, numerical sensor-fusion accuracy, or a physical device. Firmware and raw captures are retained privately alongside this report and are not embedded here.
''' (report / 'index.html').write_text(document) (report / 'paired-summary.json').write_text(json.dumps(dict(passed=True, execution_passed=paired['execution_passed'], checks=checks, input_gate=before['gate'], input_ring=before['ring'], input_consumed=after['consumed']-before['consumed'], control_consumed=paired['control']['evidence']['after']['consumed']-paired['control']['evidence']['before']['consumed'], faults=0), indent=2) + '\n') print('Output:', workspace, flush=True) print('Report:', report / 'index.html', flush=True) return 0 MAX_IMU_CAPTURE_FILE_BYTES = 64 * 1024 * 1024 MAX_IMU_CAPTURE_TOTAL_BYTES = 512 * 1024 * 1024 def _validate_imu_capture_tree(capture): """Reject links, special files, and unreasonable input sizes before auditing.""" capture = Path(capture) root_stat = capture.lstat() if stat.S_ISLNK(root_stat.st_mode) or not stat.S_ISDIR(root_stat.st_mode): raise ValueError('Each IMU lane must contain a real capture directory') total = 0 def walk_error(error): raise ValueError('Could not inspect every IMU capture file safely') from error for directory, dirnames, filenames in os.walk(capture, followlinks=False, onerror=walk_error): base = Path(directory) for name in dirnames: child = base / name mode = child.lstat().st_mode if stat.S_ISLNK(mode) or not stat.S_ISDIR(mode): raise ValueError('IMU captures cannot contain symlinks or special files') for name in filenames: child = base / name metadata = child.lstat() if stat.S_ISLNK(metadata.st_mode) or not stat.S_ISREG(metadata.st_mode): raise ValueError('IMU captures can contain regular files only; symlinks and special files are rejected') if metadata.st_size > MAX_IMU_CAPTURE_FILE_BYTES: raise ValueError('IMU capture file exceeds the 64 MiB size limit') total += metadata.st_size return total def _validate_imu_capture_reference(capture, name): """Ensure manifest-derived filenames stay inside a captured lane.""" relative = Path(name) if isinstance(name, str) else None if (relative is None or not name or not relative.parts or relative.is_absolute() or '..' in relative.parts): raise ValueError('IMU capture manifest contains an unsafe relative file reference') current = capture for index, part in enumerate(relative.parts): current = current / part metadata = current.lstat() if stat.S_ISLNK(metadata.st_mode): raise ValueError('IMU capture manifest cannot reference symlinks') if index < len(relative.parts) - 1: if not stat.S_ISDIR(metadata.st_mode): raise ValueError('IMU capture manifest reference has a non-directory parent') elif not stat.S_ISREG(metadata.st_mode): raise ValueError('IMU capture manifest must reference regular files') elif metadata.st_size > MAX_IMU_CAPTURE_FILE_BYTES: raise ValueError('IMU capture manifest references a file above the 64 MiB size limit') def _validate_imu_manifest_references(capture, workspace): """Bound files opened through saved manifests to the private run workspace.""" import run_original_boot_screen as boot try: manifest = json.loads((capture / 'manifest.json').read_text()) boot.validate_profile(manifest['profile']) assets = manifest['assets'] if not isinstance(assets, dict) or set(assets) != set(manifest['profile']['assets']): raise ValueError('IMU manifest asset set differs from its reviewed profile') for spec in assets.values(): raw_path = spec['path'] if not isinstance(raw_path, str): raise ValueError('IMU manifest asset path must be text') path = Path(raw_path).expanduser() if (not path.is_absolute() or '..' in path.parts or not path.is_relative_to(workspace)): raise ValueError('IMU manifest assets must stay inside the private run workspace') current = path while current != workspace: metadata = current.lstat() if stat.S_ISLNK(metadata.st_mode): raise ValueError('IMU manifest assets cannot traverse symlinks') if current == path: if not stat.S_ISREG(metadata.st_mode): raise ValueError('IMU manifest assets must be regular files') if metadata.st_size > MAX_IMU_CAPTURE_FILE_BYTES: raise ValueError('IMU manifest asset exceeds the 64 MiB size limit') elif not stat.S_ISDIR(metadata.st_mode): raise ValueError('IMU manifest asset parent must be a real directory') current = current.parent components = manifest['components'] if not isinstance(components, dict) or set(components) != set(manifest['profile']['components']): raise ValueError('IMU manifest component set differs from its reviewed profile') for name in components: _validate_imu_capture_reference(capture, name) host_sources = manifest['host_sources'] expected_sources = {'runner-source.py', 'execute-source.py', 'process-source.py'} if not isinstance(host_sources, dict) or set(host_sources) != expected_sources: raise ValueError('IMU manifest host-source set is invalid') for name in host_sources: _validate_imu_capture_reference(capture, name) artifact_manifest = capture / 'artifacts.json' if artifact_manifest.exists(): artifacts = json.loads(artifact_manifest.read_text()) if not isinstance(artifacts, dict): raise ValueError('IMU artifact manifest must be an object') for name in artifacts: _validate_imu_capture_reference(capture, name) except (KeyError, TypeError, OSError, json.JSONDecodeError) as error: raise ValueError('Could not validate all IMU manifest file references safely') from error def audit_imu_stock_pair(pair, output): """Re-audit an existing private pair without launching the emulator.""" from imu_stock_scenario import audit_pair, private_report_workspace supplied_pair = Path(pair).expanduser().absolute() if supplied_pair.is_symlink(): raise ValueError('Pair directory cannot be a symlink') pair = private_report_workspace(supplied_pair) workspace = private_report_workspace(pair.parent.parent) captures = (pair / 'input' / 'capture', pair / 'control' / 'capture') total = 0 for lane, capture in zip(('input', 'control'), captures): lane_dir = pair / lane lane_mode = lane_dir.lstat().st_mode if stat.S_ISLNK(lane_mode) or not stat.S_ISDIR(lane_mode): raise ValueError('Each IMU lane must be a real directory') if not capture.is_relative_to(pair): raise ValueError('Both captures must be inside the pair directory') total += _validate_imu_capture_tree(capture) _validate_imu_manifest_references(capture, workspace) if total > MAX_IMU_CAPTURE_TOTAL_BYTES: raise ValueError('IMU pair exceeds the 512 MiB combined size limit') supplied_output = Path(output).expanduser().absolute() if supplied_output.is_symlink() or supplied_output.exists() or supplied_output.parent.resolve() != pair: raise ValueError('Use a new output directory directly inside the pair directory') result = audit_pair(captures[0], captures[1], supplied_output, workspace=pair) if result.get('passed') is not True: print('Stock IMU pair audit failed; the audit JSON was preserved.', file=sys.stderr) return 1 print('Audit:', supplied_output / 'imu-paired-audit.json', flush=True) return 0 def main(argv=None): parser = argparse.ArgumentParser(prog='blackwall', description=__doc__) sub = parser.add_subparsers(dest='command', required=True) sub.add_parser('scenarios', help='List built-in scenarios') environment = sub.add_parser('environment', help='Check Docker and a local container without firmware') environment.add_argument('--renode-image', help='Optional full local sha256 image ID; non-default images are unreviewed') assets = sub.add_parser('assets', help='Show required input hashes') assets.add_argument('--source', type=Path, help='Source directory containing a pinned profile') assets.add_argument('--profile', choices=['auto', 'imu', 'detailed', 'timed', 'stock'], default='auto') faceclaw = sub.add_parser('faceclaw38', help='Run the reviewed Faceclaw 38 main-reset-to-frame profile') faceclaw_input = faceclaw.add_mutually_exclusive_group(required=True) faceclaw_input.add_argument('--main-image', type=Path, help='Pinned Faceclaw 38 main firmware image') faceclaw_input.add_argument('--capture', type=Path, help='Audit a saved private Faceclaw 38 capture without rerunning') faceclaw.add_argument('--output', type=Path, required=True, help='New private output directory outside the repository') frame_report = sub.add_parser('frame-report', help='Render a retained frame scenario in the workbench dashboard') frame_report.add_argument('--capture', type=Path, required=True, help='Private frame scenario output directory') frame_report.add_argument('--output', type=Path, required=True, help='New private report directory') post_report = sub.add_parser('post-screen-report', help='Audit a paired post-screen touch experiment and render its report') post_report.add_argument('--pair', type=Path, required=True, help='Private paired experiment directory') post_report.add_argument('--baseline', type=Path, required=True, help='Untouched private stock boot capture') post_report.add_argument('--output', type=Path, required=True, help='New private report directory') imu_audit = sub.add_parser('imu-stock-audit', help='Re-audit a saved private stock IMU pair without rerunning') imu_audit.add_argument('--pair', type=Path, required=True, help='Existing private pair directory containing input/capture and control/capture') imu_audit.add_argument('--output', type=Path, required=True, help='New private audit directory directly inside the pair') init = sub.add_parser('setup', help='Import verified inputs into a new Docker volume') init.add_argument('--source', type=Path, required=True, help='Directory containing pinned model and snapshot inputs') init.add_argument('--profile', choices=['auto', 'imu', 'detailed', 'timed', 'stock'], default='auto') init.add_argument('--boot-image', type=Path) init.add_argument('--main-image', type=Path) init.add_argument('--volume', default=DEFAULT_VOLUME) doctor = sub.add_parser('doctor', help='Verify the Docker volume and pinned assets') doctor.add_argument('--volume', default=DEFAULT_VOLUME) doctor.add_argument('--boot-image', type=Path) doctor.add_argument('--main-image', type=Path) run = sub.add_parser('report', help='Run or audit a scenario and generate its HTML report') run.add_argument('--volume', default=DEFAULT_VOLUME) run.add_argument('--scenario', choices=SCENARIOS) run.add_argument('--scenario-file', type=Path) run.add_argument('--capture', type=Path) run.add_argument('--boot-image', type=Path) run.add_argument('--main-image', type=Path) run.add_argument('--output', type=Path, help='New output directory outside the repository') run.add_argument('--serve', action='store_true') run.add_argument('--port', type=int, default=8765) args = parser.parse_args(argv) try: if args.command == 'scenarios': for name, description in SCENARIOS.items(): print(f'{name:22} {description}') return 0 if args.command == 'environment': from environment_diagnostics import diagnose result = diagnose(args.renode_image) print(json.dumps(result, indent=2)) return 0 if result['status'] == 'ready' else 1 if args.command == 'assets': profile_file = select_profile(args.source or ROOT, args.profile) if not profile_file: raise ValueError('Selected profile is not available') show_assets(json.loads(profile_file.read_text())) return 0 if args.command == 'faceclaw38': from faceclaw_main import audit_report, run as run_faceclaw report_path = (audit_report(args.capture, args.output) if args.capture else run_faceclaw(args.main_image, args.output)) print('Report:', report_path, flush=True) return 0 if args.command == 'frame-report': from frame_workbench import build print('Report:', build(args.capture, args.output), flush=True) return 0 if args.command == 'post-screen-report': from post_screen_report import generate model = generate(args.pair, args.baseline, args.output) print('Report:', args.output / 'index.html', flush=True) print('Nearest / final changed pixels:', model['touch_comparison']['different_pixels'], '/', model['touch_comparison']['final_different_pixels'], flush=True) return 0 if args.command == 'imu-stock-audit': return audit_imu_stock_pair(args.pair, args.output) volume_name(args.volume) if args.command == 'setup': return setup(args) if args.command == 'doctor': return inspect_volume(args) return report(args) except (ValueError, OSError, RuntimeError, subprocess.SubprocessError) as exc: print('Blackwall:', exc, file=sys.stderr) return 2 if __name__ == '__main__': raise SystemExit(main())