Jelajahi Sumber

fix: harden offline package provenance evidence

Codex Resource Selftest 4 bulan lalu
induk
melakukan
3d9870df08
2 mengubah file dengan 421 tambahan dan 39 penghapusan
  1. 413 35
      tools/codex_harness.py
  2. 8 4
      tools/prod2u_p4_harness.py

+ 413 - 35
tools/codex_harness.py

@@ -33,9 +33,33 @@ VERIFICATION_TARGETS_PATH = Path("config/prod2u_p4_verification_targets_v1.json"
 PACKAGE_INFO_SCHEMA = "prod2u-p4-normal-v3-folder-package-info-v3"
 PACKAGE_INFO_SCHEMA = "prod2u-p4-normal-v3-folder-package-info-v3"
 PACKAGE_MANIFEST_SCHEMA = "prod2u-simple-package-manifest-v2"
 PACKAGE_MANIFEST_SCHEMA = "prod2u-simple-package-manifest-v2"
 RUNTIME_PROFILE = "prod2u-door-temp-115200-v1"
 RUNTIME_PROFILE = "prod2u-door-temp-115200-v1"
+PACKAGE_HASH_EXCLUSIONS = frozenset(
+    {
+        "package-info.json",
+        "package_manifest.json",
+        "evidence/package-selftest-result.json",
+    }
+)
+PACKAGE_RECEIPT_PATHS = (
+    "evidence/td-primary-receipt.json",
+    "evidence/td-confirmation-receipt.json",
+    "evidence/python-unit-receipt.json",
+    "evidence/icarus-receipt.json",
+    "evidence/verilator-receipt.json",
+    "evidence/cocotb-receipt.json",
+    "evidence/formal-receipt.json",
+)
 
 
 
 
-def _receipt_payload(*, name: str, run_id: str, commit: str, bitstream_sha256: str, project_config_sha256: str) -> dict[str, Any]:
+def _receipt_payload(
+    *,
+    name: str,
+    run_id: str,
+    commit: str,
+    bitstream_sha256: str,
+    project_config_sha256: str,
+    td_source_manifest_sha256: str | None = None,
+) -> dict[str, Any]:
     return {
     return {
         "schema": f"prod2u-p4-normal-v3-{name}-receipt-v1",
         "schema": f"prod2u-p4-normal-v3-{name}-receipt-v1",
         "status": "not_run",
         "status": "not_run",
@@ -43,7 +67,7 @@ def _receipt_payload(*, name: str, run_id: str, commit: str, bitstream_sha256: s
         "commit": commit,
         "commit": commit,
         "bitstream_sha256": bitstream_sha256,
         "bitstream_sha256": bitstream_sha256,
         "project_config_sha256": project_config_sha256,
         "project_config_sha256": project_config_sha256,
-        "td_source_manifest_sha256": None,
+        "td_source_manifest_sha256": td_source_manifest_sha256,
         "command": None,
         "command": None,
         "tool_version": None,
         "tool_version": None,
         "placeholder": True,
         "placeholder": True,
@@ -107,16 +131,214 @@ def _copy_bound_receipt(
 
 
 
 
 def _package_file_hashes(package: Path) -> dict[str, str]:
 def _package_file_hashes(package: Path) -> dict[str, str]:
-    excluded = {
-        "package-info.json",
-        "package_manifest.json",
-        "evidence/package-selftest-result.json",
-    }
     return {
     return {
         path.relative_to(package).as_posix(): sha256_file(path)
         path.relative_to(package).as_posix(): sha256_file(path)
         for path in sorted(package.rglob("*"))
         for path in sorted(package.rglob("*"))
-        if path.is_file() and path.relative_to(package).as_posix() not in excluded
+        if path.is_file()
+        and path.relative_to(package).as_posix() not in PACKAGE_HASH_EXCLUSIONS
+    }
+
+
+def _package_selftest_script() -> str:
+    return """$ErrorActionPreference = 'Stop'
+$excluded = @(
+  'package-info.json',
+  'package_manifest.json',
+  'evidence/package-selftest-result.json'
+)
+
+function Require-File([string]$Relative) {
+  $path = Join-Path $PSScriptRoot $Relative
+  if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { throw "missing file: $Relative" }
+  return $path
+}
+
+function Read-Json([string]$Relative) {
+  $path = Require-File $Relative
+  try { return (Get-Content -LiteralPath $path -Raw | ConvertFrom-Json) }
+  catch { throw "invalid JSON: $Relative" }
+}
+
+function Get-Value($Object, [string]$Name) {
+  if ($null -eq $Object) { return $null }
+  $property = $Object.PSObject.Properties[$Name]
+  if ($null -eq $property) { return $null }
+  return $property.Value
+}
+
+function Has-Value($Object, [string]$Name) {
+  if ($null -eq $Object) { return $false }
+  return $null -ne $Object.PSObject.Properties[$Name]
+}
+
+function Assert-Equal([string]$Name, $Actual, $Expected) {
+  if ($Actual -ne $Expected) { throw "$Name mismatch" }
+}
+
+function Assert-HashMap([string]$Name, $Actual, $Expected) {
+  $actualProperties = @($Actual.PSObject.Properties | Sort-Object Name)
+  $expectedProperties = @($Expected.PSObject.Properties | Sort-Object Name)
+  if ($actualProperties.Count -ne $expectedProperties.Count) { throw "$Name key count mismatch" }
+  for ($index = 0; $index -lt $actualProperties.Count; $index++) {
+    if ($actualProperties[$index].Name -ne $expectedProperties[$index].Name -or
+        $actualProperties[$index].Value -ne $expectedProperties[$index].Value) {
+      throw "$Name mismatch"
     }
     }
+  }
+}
+
+function Assert-Safety([string]$Name, $Object) {
+  Assert-Equal "$Name.verification_scope" (Get-Value $Object 'verification_scope') 'offline'
+  Assert-Equal "$Name.hardware_validation" (Get-Value $Object 'hardware_validation') 'not_run'
+  Assert-Equal "$Name.board_validation" (Get-Value $Object 'board_validation') 'not_run'
+  Assert-Equal "$Name.programming_validation" (Get-Value $Object 'programming_validation') 'not_run'
+  Assert-Equal "$Name.COM" (Get-Value $Object 'COM') $false
+  Assert-Equal "$Name.JTAG" (Get-Value $Object 'JTAG') $false
+}
+
+$info = Read-Json 'package-info.json'
+$manifest = Read-Json 'package_manifest.json'
+$sourceManifest = Read-Json 'source_manifest.json'
+$validation = Read-Json 'evidence/validation-summary.json'
+$selftestResult = Read-Json 'evidence/package-selftest-result.json'
+$projectHash = (Get-FileHash (Require-File 'project.json') -Algorithm SHA256).Hash.ToLowerInvariant()
+$bitstreamHash = (Get-FileHash (Require-File 'fw.bit') -Algorithm SHA256).Hash.ToLowerInvariant()
+$sourceManifestHash = (Get-FileHash (Require-File 'source_manifest.json') -Algorithm SHA256).Hash.ToLowerInvariant()
+$validationHash = (Get-FileHash (Require-File 'evidence/validation-summary.json') -Algorithm SHA256).Hash.ToLowerInvariant()
+$selftestHash = (Get-FileHash (Require-File 'evidence/package-selftest-result.json') -Algorithm SHA256).Hash.ToLowerInvariant()
+$runId = [string](Get-Value $info 'verification_run_id')
+$commit = [string](Get-Value $info 'commit')
+$commitFull = [string](Get-Value $info 'commit_full')
+$tdSourceManifestHash = [string](Get-Value $info 'td_source_manifest_sha256')
+if ($commitFull -notmatch '^[0-9a-f]{40}$') { throw 'invalid exact commit' }
+if ($runId -notmatch '^[0-9a-f]{32}$') { throw 'invalid exact run id' }
+if ($tdSourceManifestHash -notmatch '^[0-9a-f]{64}$') { throw 'invalid TD source manifest hash' }
+
+Assert-Equal 'package-info.schema' (Get-Value $info 'schema') 'prod2u-p4-normal-v3-folder-package-info-v3'
+Assert-Equal 'package-info.profile' (Get-Value $info 'profile') 'prod2u-door-temp-115200-v1'
+Assert-Equal 'package-info.project_id' (Get-Value $info 'project_id') 'prod2u-door-temp'
+Assert-Equal 'package-info.verification_run_id' (Get-Value $info 'verification_run_id') $runId
+Assert-Equal 'package-info.commit_full' (Get-Value $info 'commit_full') $commitFull
+Assert-Equal 'package-info.bitstream_sha256' (Get-Value $info 'bitstream_sha256') $bitstreamHash
+Assert-Equal 'package-info.project_sha256' (Get-Value $info 'project_sha256') $projectHash
+Assert-Equal 'package-info.project_config_sha256' (Get-Value $info 'project_config_sha256') $projectHash
+Assert-Equal 'package-info.source_manifest_sha256' (Get-Value $info 'source_manifest_sha256') $sourceManifestHash
+Assert-Equal 'package-info.td_source_manifest_sha256' (Get-Value $info 'td_source_manifest_sha256') $tdSourceManifestHash
+Assert-Equal 'package-info.validation_summary_sha256' (Get-Value $info 'validation_summary_sha256') $validationHash
+Assert-Equal 'package-info.package_selftest_result_sha256' (Get-Value $info 'package_selftest_result_sha256') $selftestHash
+Assert-Equal 'package-info.formal_trace_manifest_sha256' (Get-Value $info 'formal_trace_manifest_sha256') ((Get-FileHash (Require-File 'evidence/formal-trace-manifest.json') -Algorithm SHA256).Hash.ToLowerInvariant())
+Assert-Safety 'package-info' $info
+
+Assert-Equal 'package_manifest.schema' (Get-Value $manifest 'schema') 'prod2u-simple-package-manifest-v2'
+if (@('UNVERIFIED', 'VERIFIED_OFFLINE') -notcontains [string](Get-Value $manifest 'status')) {
+  throw "unsupported package status: $((Get-Value $manifest 'status'))"
+}
+Assert-Equal 'package_manifest.run_id' (Get-Value $manifest 'run_id') $runId
+Assert-Equal 'package_manifest.commit_full' (Get-Value $manifest 'commit_full') $commitFull
+Assert-Equal 'package_manifest.bitstream_sha256' (Get-Value $manifest 'bitstream_sha256') $bitstreamHash
+Assert-Equal 'package_manifest.project_sha256' (Get-Value $manifest 'project_sha256') $projectHash
+Assert-Equal 'package_manifest.source_manifest_sha256' (Get-Value $manifest 'source_manifest_sha256') $sourceManifestHash
+Assert-Equal 'package_manifest.td_source_manifest_sha256' (Get-Value $manifest 'td_source_manifest_sha256') $tdSourceManifestHash
+Assert-Equal 'package_manifest.package_info_sha256' (Get-Value $manifest 'package_info_sha256') ((Get-FileHash (Require-File 'package-info.json') -Algorithm SHA256).Hash.ToLowerInvariant())
+Assert-Safety 'package_manifest' $manifest
+
+Assert-Equal 'source_manifest.project_id' (Get-Value $sourceManifest 'project_id') 'prod2u-door-temp'
+Assert-Equal 'source_manifest.project_sha256' (Get-Value $sourceManifest 'project_sha256') $projectHash
+Assert-Equal 'source_manifest.generated_source_manifest_sha256' (Get-Value $sourceManifest 'generated_source_manifest_sha256') $tdSourceManifestHash
+Assert-Equal 'project_config_sha256.txt' ((Get-Content (Require-File 'project_config_sha256.txt') -Raw).Trim()) $projectHash
+Assert-Equal 'bitstream_sha256.txt' ((Get-Content (Require-File 'bitstream_sha256.txt') -Raw).Trim()) $bitstreamHash
+
+Assert-Equal 'validation.verification_run_id' (Get-Value $validation 'verification_run_id') $runId
+Assert-Equal 'validation.commit' (Get-Value $validation 'commit') $commit
+Assert-Equal 'validation.commit_full' (Get-Value $validation 'commit_full') $commitFull
+Assert-Equal 'validation.bitstream_sha256' (Get-Value $validation 'bitstream_sha256') $bitstreamHash
+Assert-Equal 'validation.project_config_sha256' (Get-Value $validation 'project_config_sha256') $projectHash
+Assert-Equal 'validation.td_source_manifest_sha256' (Get-Value $validation 'td_source_manifest_sha256') $tdSourceManifestHash
+Assert-Safety 'validation' $validation
+
+Assert-Equal 'package-selftest-result.verification_run_id' (Get-Value $selftestResult 'verification_run_id') $runId
+Assert-Equal 'package-selftest-result.commit_full' (Get-Value $selftestResult 'commit_full') $commitFull
+Assert-Equal 'package-selftest-result.bitstream_sha256' (Get-Value $selftestResult 'bitstream_sha256') $bitstreamHash
+Assert-Equal 'package-selftest-result.project_config_sha256' (Get-Value $selftestResult 'project_config_sha256') $projectHash
+Assert-Equal 'package-selftest-result.td_source_manifest_sha256' (Get-Value $selftestResult 'td_source_manifest_sha256') $tdSourceManifestHash
+Assert-Equal 'package-selftest-result.returncode' (Get-Value $selftestResult 'returncode') 0
+$selftestSafety = Get-Value $selftestResult 'safety'
+if ($null -eq $selftestSafety) { $selftestSafety = $selftestResult }
+Assert-Safety 'package-selftest-result' $selftestSafety
+if ((Has-Value $selftestResult 'package_info_sha256') -or
+    (Has-Value $selftestResult 'package_selftest_result_sha256')) {
+  throw 'package-selftest-result contains self-referential hashes'
+}
+
+$observedExclusions = @((Get-Value $info 'hash_exclusions') | ForEach-Object { [string]$_ } | Sort-Object)
+$expectedExclusions = @($excluded | Sort-Object)
+if (($observedExclusions -join '|') -ne ($expectedExclusions -join '|')) { throw 'package-info hash exclusions mismatch' }
+Assert-Equal 'package_manifest.hash_exclusions' (((Get-Value $manifest 'hash_exclusions') | ForEach-Object { [string]$_ } | Sort-Object) -join '|') ($expectedExclusions -join '|')
+Assert-Equal 'package-selftest-result.hash_exclusions' (((Get-Value $selftestResult 'hash_exclusions') | ForEach-Object { [string]$_ } | Sort-Object) -join '|') ($expectedExclusions -join '|')
+
+$actualFiles = [ordered]@{}
+Get-ChildItem -LiteralPath $PSScriptRoot -Recurse -File | ForEach-Object {
+  $relative = $_.FullName.Substring($PSScriptRoot.Length + 1).Replace([char]92, [char]47)
+  if ($excluded -notcontains $relative) {
+    $actualFiles[$relative] = (Get-FileHash -LiteralPath $_.FullName -Algorithm SHA256).Hash.ToLowerInvariant()
+  }
+}
+$actualFileMap = $actualFiles | ConvertTo-Json -Depth 100 | ConvertFrom-Json
+Assert-HashMap 'package-info.file_sha256' (Get-Value $info 'file_sha256') $actualFileMap
+Assert-HashMap 'package_manifest.file_sha256' (Get-Value $manifest 'file_sha256') $actualFileMap
+$selftestFileMap = Get-Value $selftestResult 'file_sha256'
+if ($null -eq $selftestFileMap) { $selftestFileMap = Get-Value $selftestResult 'package_file_sha256' }
+Assert-HashMap 'package-selftest-result.file_sha256' $selftestFileMap $actualFileMap
+
+$receiptFiles = @(Get-ChildItem -LiteralPath (Join-Path $PSScriptRoot 'evidence') -Filter '*-receipt.json' -File)
+if ($receiptFiles.Count -lt 7) { throw 'receipt set is incomplete' }
+$receiptHashes = [ordered]@{}
+foreach ($receiptFile in $receiptFiles) {
+  $receiptRelative = 'evidence/' + $receiptFile.Name
+  $receiptHashes[$receiptRelative] = (Get-FileHash -LiteralPath $receiptFile.FullName -Algorithm SHA256).Hash.ToLowerInvariant()
+  $receipt = Read-Json $receiptRelative
+  Assert-Equal "$($receiptFile.Name).verification_run_id" (Get-Value $receipt 'verification_run_id') $runId
+  $receiptCommit = [string](Get-Value $receipt 'commit_full')
+  if (-not $receiptCommit) { $receiptCommit = [string](Get-Value $receipt 'commit') }
+  Assert-Equal "$($receiptFile.Name).commit" $receiptCommit $commitFull
+  Assert-Equal "$($receiptFile.Name).project_config_sha256" (Get-Value $receipt 'project_config_sha256') $projectHash
+  Assert-Equal "$($receiptFile.Name).td_source_manifest_sha256" (Get-Value $receipt 'td_source_manifest_sha256') $tdSourceManifestHash
+  if (Has-Value $receipt 'verification_scope') { Assert-Safety $receiptFile.Name $receipt }
+}
+$receiptHashObject = $receiptHashes | ConvertTo-Json -Depth 100 | ConvertFrom-Json
+Assert-HashMap 'package-info.receipt_sha256' (Get-Value $info 'receipt_sha256') $receiptHashObject
+Assert-HashMap 'package-manifest.receipt_sha256' (Get-Value $manifest 'receipt_sha256') $receiptHashObject
+$formalReceipt = Read-Json 'evidence/formal-receipt.json'
+$traceManifest = Read-Json 'evidence/formal-trace-manifest.json'
+Assert-Equal 'formal-trace-manifest.formal_receipt_sha256' (Get-Value $traceManifest 'formal_receipt_sha256') ((Get-FileHash (Require-File 'evidence/formal-receipt.json') -Algorithm SHA256).Hash.ToLowerInvariant())
+$declaredTraces = @()
+foreach ($trace in @((Get-Value $formalReceipt 'trace_files'))) {
+  if ($trace -and $declaredTraces -notcontains [string]$trace) { $declaredTraces += [string]$trace }
+}
+foreach ($target in @((Get-Value $formalReceipt 'targets'))) {
+  foreach ($trace in @((Get-Value $target 'trace_files'))) {
+    if ($trace -and $declaredTraces -notcontains [string]$trace) { $declaredTraces += [string]$trace }
+  }
+  foreach ($task in @((Get-Value $target 'task_results'))) {
+    foreach ($trace in @((Get-Value $task 'trace_files'))) {
+      if ($trace -and $declaredTraces -notcontains [string]$trace) { $declaredTraces += [string]$trace }
+    }
+  }
+}
+$traceEntries = @((Get-Value $traceManifest 'files'))
+if ($declaredTraces.Count -ne $traceEntries.Count) { throw 'formal trace count mismatch' }
+$traceHashes = [ordered]@{}
+foreach ($entry in $traceEntries) {
+  $tracePath = [string](Get-Value $entry 'path')
+  $traceHash = [string](Get-Value $entry 'sha256')
+  if (-not $tracePath -or -not $traceHash) { throw 'formal trace manifest entry is incomplete' }
+  $traceHashes[$tracePath] = (Get-FileHash (Require-File $tracePath) -Algorithm SHA256).Hash.ToLowerInvariant()
+  Assert-Equal "formal-trace.$tracePath" $traceHashes[$tracePath] $traceHash
+}
+$traceHashObject = $traceHashes | ConvertTo-Json -Depth 100 | ConvertFrom-Json
+Assert-HashMap 'formal-trace-manifest.file_sha256' (Get-Value $traceManifest 'file_sha256') $traceHashObject
+"package provenance selftest passed"
+""".replace("\n", "\r\n")
 
 
 
 
 def new_run_id() -> str:
 def new_run_id() -> str:
@@ -496,6 +718,103 @@ def _write_json(path: Path, value: Mapping[str, Any]) -> None:
     Path(path).write_text(json.dumps(dict(value), indent=2, sort_keys=True) + "\n", encoding="utf-8", newline="\n")
     Path(path).write_text(json.dumps(dict(value), indent=2, sort_keys=True) + "\n", encoding="utf-8", newline="\n")
 
 
 
 
+def _copy_formal_traces(
+    *,
+    source_receipt: Path,
+    formal_receipt: Mapping[str, Any],
+    package: Path,
+    repo: Path,
+) -> dict[str, Any]:
+    raw_trace_files: list[Any] = []
+    top_level_traces = formal_receipt.get("trace_files", [])
+    if isinstance(top_level_traces, list):
+        raw_trace_files.extend(top_level_traces)
+    elif isinstance(top_level_traces, str) and top_level_traces.strip():
+        raw_trace_files.append(top_level_traces)
+    targets = formal_receipt.get("targets", [])
+    if isinstance(targets, list):
+        for target in targets:
+            if not isinstance(target, Mapping):
+                continue
+            traces = target.get("trace_files", [])
+            if isinstance(traces, list):
+                raw_trace_files.extend(traces)
+            elif isinstance(traces, str) and traces.strip():
+                raw_trace_files.append(traces)
+            task_results = target.get("task_results", [])
+            if isinstance(task_results, list):
+                for task in task_results:
+                    if not isinstance(task, Mapping):
+                        continue
+                    task_traces = task.get("trace_files", [])
+                    if isinstance(task_traces, list):
+                        raw_trace_files.extend(task_traces)
+                    elif isinstance(task_traces, str) and task_traces.strip():
+                        raw_trace_files.append(task_traces)
+    if raw_trace_files is None or raw_trace_files == "":
+        trace_files: list[Any] = []
+    elif isinstance(raw_trace_files, str):
+        trace_files = [raw_trace_files]
+    elif isinstance(raw_trace_files, list):
+        trace_files = raw_trace_files
+    else:
+        raise ValueError("formal receipt trace_files must be a list")
+    unique_trace_files: list[Any] = []
+    seen_trace_files: set[str] = set()
+    for raw_trace in trace_files:
+        key = raw_trace if isinstance(raw_trace, str) else repr(raw_trace)
+        if key not in seen_trace_files:
+            seen_trace_files.add(key)
+            unique_trace_files.append(raw_trace)
+    trace_files = unique_trace_files
+
+    trace_root = package / "evidence" / "formal-traces"
+    trace_root.mkdir(parents=True, exist_ok=True)
+    entries: list[dict[str, str]] = []
+    file_sha256: dict[str, str] = {}
+    used_names: set[str] = set()
+    for index, raw_trace in enumerate(trace_files):
+        if not isinstance(raw_trace, str) or not raw_trace.strip():
+            raise ValueError("formal receipt contains an invalid trace path")
+        trace_value = Path(raw_trace)
+        candidates = (
+            [trace_value]
+            if trace_value.is_absolute()
+            else [source_receipt.parent / trace_value, repo / trace_value, Path.cwd() / trace_value]
+        )
+        source_path = next((candidate.resolve() for candidate in candidates if candidate.is_file()), None)
+        if source_path is None:
+            raise FileNotFoundError(f"formal trace is missing: {raw_trace}")
+        name = source_path.name
+        if name in used_names:
+            name = f"{index:02d}-{name}"
+        while name in used_names:
+            name = f"{index:02d}-{name}"
+        used_names.add(name)
+        destination = trace_root / name
+        shutil.copy2(source_path, destination)
+        relative = destination.relative_to(package).as_posix()
+        digest = sha256_file(destination)
+        file_sha256[relative] = digest
+        entries.append(
+            {
+                "source": raw_trace,
+                "path": relative,
+                "sha256": digest,
+            }
+        )
+
+    manifest = {
+        "schema": "prod2u-p4-normal-v3-formal-trace-manifest-v1",
+        "formal_receipt": "evidence/formal-receipt.json",
+        "formal_receipt_sha256": sha256_file(package / "evidence" / "formal-receipt.json"),
+        "files": entries,
+        "file_sha256": file_sha256,
+    }
+    _write_json(package / "evidence" / "formal-trace-manifest.json", manifest)
+    return manifest
+
+
 def init_run(run_id: str, root: Path | None = None) -> Path:
 def init_run(run_id: str, root: Path | None = None) -> Path:
     if not RUN_ID_RE.fullmatch(run_id):
     if not RUN_ID_RE.fullmatch(run_id):
         raise ValueError("run_id must be 32 lowercase hexadecimal characters")
         raise ValueError("run_id must be 32 lowercase hexadecimal characters")
@@ -610,13 +929,7 @@ def create_unverified_package(
             raise FileNotFoundError(f"package source is missing: {source}")
             raise FileNotFoundError(f"package source is missing: {source}")
         shutil.copy2(source, package / name)
         shutil.copy2(source, package / name)
     (package / "selftest.ps1").write_text(
     (package / "selftest.ps1").write_text(
-        "$ErrorActionPreference = 'Stop'\r\n"
-        "$bit = (Get-FileHash (Join-Path $PSScriptRoot 'fw.bit') -Algorithm SHA256).Hash.ToLowerInvariant()\r\n"
-        "$expectedBit = (Get-Content (Join-Path $PSScriptRoot 'bitstream_sha256.txt') -Raw).Trim().ToLowerInvariant()\r\n"
-        "if ($bit -ne $expectedBit) { throw 'bitstream hash mismatch' }\r\n"
-        "$projectHash = (Get-FileHash (Join-Path $PSScriptRoot 'project.json') -Algorithm SHA256).Hash.ToLowerInvariant()\r\n"
-        "$expectedProject = (Get-Content (Join-Path $PSScriptRoot 'project_config_sha256.txt') -Raw).Trim().ToLowerInvariant()\r\n"
-        "if ($projectHash -ne $expectedProject) { throw 'project hash mismatch' }\r\n",
+        _package_selftest_script(),
         encoding="ascii",
         encoding="ascii",
         newline="",
         newline="",
     )
     )
@@ -624,6 +937,7 @@ def create_unverified_package(
     source_manifest = build_source_manifest(repo)
     source_manifest = build_source_manifest(repo)
     _write_json(package / "source_manifest.json", source_manifest)
     _write_json(package / "source_manifest.json", source_manifest)
     observed_source_manifest_sha256 = sha256_file(package / "source_manifest.json")
     observed_source_manifest_sha256 = sha256_file(package / "source_manifest.json")
+    td_source_manifest_sha256 = sha256_file(repo / SOURCE_MANIFEST_PATH)
     if source_manifest_sha256 is not None and source_manifest_sha256 != observed_source_manifest_sha256:
     if source_manifest_sha256 is not None and source_manifest_sha256 != observed_source_manifest_sha256:
         raise ValueError("source manifest hash mismatch")
         raise ValueError("source manifest hash mismatch")
     offline_payload: dict[str, Any] | None = None
     offline_payload: dict[str, Any] | None = None
@@ -638,7 +952,7 @@ def create_unverified_package(
             "verification_run_id": run_id,
             "verification_run_id": run_id,
             "commit_full": commit_full,
             "commit_full": commit_full,
             "project_config_sha256": project_config_sha256,
             "project_config_sha256": project_config_sha256,
-            "td_source_manifest_sha256": sha256_file(repo / SOURCE_MANIFEST_PATH),
+            "td_source_manifest_sha256": td_source_manifest_sha256,
         }
         }
         for field, expected in expected_bindings.items():
         for field, expected in expected_bindings.items():
             if loaded.get(field) != expected:
             if loaded.get(field) != expected:
@@ -648,6 +962,8 @@ def create_unverified_package(
         offline_payload = loaded
         offline_payload = loaded
         shutil.copy2(Path(offline_receipt), evidence / "software-offline-receipt.json")
         shutil.copy2(Path(offline_receipt), evidence / "software-offline-receipt.json")
     receipt_sources = dict(verification_receipts or {})
     receipt_sources = dict(verification_receipts or {})
+    formal_receipt_source: Path | None = None
+    formal_receipt_value: Mapping[str, Any] | None = None
     if td_receipt is not None:
     if td_receipt is not None:
         receipt = Path(td_receipt)
         receipt = Path(td_receipt)
         if not receipt.is_file():
         if not receipt.is_file():
@@ -661,13 +977,20 @@ def create_unverified_package(
             commit=commit_full,
             commit=commit_full,
             bitstream_sha256=bitstream_sha256,
             bitstream_sha256=bitstream_sha256,
             project_config_sha256=project_config_sha256,
             project_config_sha256=project_config_sha256,
-            td_source_manifest_sha256=sha256_file(repo / SOURCE_MANIFEST_PATH),
+            td_source_manifest_sha256=td_source_manifest_sha256,
             receipt_role="td-primary",
             receipt_role="td-primary",
         )
         )
     else:
     else:
         _write_json(
         _write_json(
             evidence / "td-primary-receipt.json",
             evidence / "td-primary-receipt.json",
-            _receipt_payload(name="td-primary", run_id=run_id, commit=commit_full, bitstream_sha256=bitstream_sha256, project_config_sha256=project_config_sha256),
+            _receipt_payload(
+                name="td-primary",
+                run_id=run_id,
+                commit=commit_full,
+                bitstream_sha256=bitstream_sha256,
+                project_config_sha256=project_config_sha256,
+                td_source_manifest_sha256=td_source_manifest_sha256,
+            ),
         )
         )
     receipt_specs = {
     receipt_specs = {
         "td-confirmation": "td-confirmation-receipt.json",
         "td-confirmation": "td-confirmation-receipt.json",
@@ -683,39 +1006,50 @@ def create_unverified_package(
             source_path = Path(source)
             source_path = Path(source)
             if not source_path.is_file():
             if not source_path.is_file():
                 raise FileNotFoundError(f"verification receipt is missing: {source_path}")
                 raise FileNotFoundError(f"verification receipt is missing: {source_path}")
-            _copy_bound_receipt(
+            copied_receipt = _copy_bound_receipt(
                 source_path,
                 source_path,
                 evidence / filename,
                 evidence / filename,
                 run_id=run_id,
                 run_id=run_id,
                 commit=commit_full,
                 commit=commit_full,
                 bitstream_sha256=bitstream_sha256,
                 bitstream_sha256=bitstream_sha256,
                 project_config_sha256=project_config_sha256,
                 project_config_sha256=project_config_sha256,
-                td_source_manifest_sha256=sha256_file(repo / SOURCE_MANIFEST_PATH),
+                td_source_manifest_sha256=td_source_manifest_sha256,
                 receipt_role=name,
                 receipt_role=name,
                 preserve_bitstream_sha256=name == "td-confirmation",
                 preserve_bitstream_sha256=name == "td-confirmation",
                 require_bitstream_sha256=name == "td-primary",
                 require_bitstream_sha256=name == "td-primary",
             )
             )
+            if name == "formal":
+                formal_receipt_source = source_path
+                formal_receipt_value = copied_receipt
         else:
         else:
+            placeholder = _receipt_payload(
+                name=name,
+                run_id=run_id,
+                commit=commit_full,
+                bitstream_sha256=bitstream_sha256,
+                project_config_sha256=project_config_sha256,
+                td_source_manifest_sha256=td_source_manifest_sha256,
+            )
             _write_json(
             _write_json(
                 evidence / filename,
                 evidence / filename,
-                _receipt_payload(name=name, run_id=run_id, commit=commit_full, bitstream_sha256=bitstream_sha256, project_config_sha256=project_config_sha256),
+                placeholder,
             )
             )
-    _write_json(
-        evidence / "package-selftest-result.json",
-        {
-            "schema": "prod2u-p4-normal-v3-package-selftest-result-v1",
-            "status": "not_run",
-            "verification_run_id": run_id,
-            "commit": commit_full,
-            "commit_full": commit_full,
-            "bitstream_sha256": bitstream_sha256,
-        },
+            if name == "formal":
+                formal_receipt_source = repo
+                formal_receipt_value = placeholder
+    if formal_receipt_value is None:
+        raise ValueError("formal receipt was not generated")
+    _copy_formal_traces(
+        source_receipt=formal_receipt_source or repo,
+        formal_receipt=formal_receipt_value,
+        package=package,
+        repo=repo,
     )
     )
     (package / "project_config_sha256.txt").write_text(
     (package / "project_config_sha256.txt").write_text(
-        sha256_file(package_project) + "\n", encoding="ascii", newline="\n"
+        project_config_sha256 + "\n", encoding="ascii", newline="\n"
     )
     )
     (package / "bitstream_sha256.txt").write_text(
     (package / "bitstream_sha256.txt").write_text(
-        sha256_file(package_bitstream) + "\n", encoding="ascii", newline="\n"
+        bitstream_sha256 + "\n", encoding="ascii", newline="\n"
     )
     )
     td_status = "not_run"
     td_status = "not_run"
     td_synthesis_input_hash = None
     td_synthesis_input_hash = None
@@ -752,6 +1086,7 @@ def create_unverified_package(
         "commit_full": commit_full,
         "commit_full": commit_full,
         "bitstream_sha256": bitstream_sha256,
         "bitstream_sha256": bitstream_sha256,
         "project_config_sha256": sha256_file(package_project),
         "project_config_sha256": sha256_file(package_project),
+        "td_source_manifest_sha256": td_source_manifest_sha256,
         "layers": {
         "layers": {
             "python_unit": {"status": receipt_status("python-unit-receipt.json")},
             "python_unit": {"status": receipt_status("python-unit-receipt.json")},
             "icarus": {"status": receipt_status("icarus-receipt.json")},
             "icarus": {"status": receipt_status("icarus-receipt.json")},
@@ -775,6 +1110,38 @@ def create_unverified_package(
     }
     }
     _write_json(evidence / "validation-summary.json", validation_summary)
     _write_json(evidence / "validation-summary.json", validation_summary)
     _write_json(package / "verification_summary.json", validation_summary)
     _write_json(package / "verification_summary.json", validation_summary)
+    _write_json(
+        evidence / "package-selftest-result.json",
+        {
+            "schema": "prod2u-p4-normal-v3-package-selftest-result-v1",
+            "status": "not_run",
+            "returncode": 0,
+            "verification_run_id": run_id,
+            "commit": commit_full,
+            "commit_full": commit_full,
+            "bitstream_sha256": bitstream_sha256,
+            "project_config_sha256": project_config_sha256,
+            "td_source_manifest_sha256": td_source_manifest_sha256,
+            "verification_scope": "offline",
+            "hardware_validation": "not_run",
+            "board_validation": "not_run",
+            "programming_validation": "not_run",
+            "COM": False,
+            "JTAG": False,
+            "hash_exclusions": sorted(PACKAGE_HASH_EXCLUSIONS),
+            "file_sha256": _package_file_hashes(package),
+            "package_file_sha256": _package_file_hashes(package),
+        },
+    )
+    receipt_paths = {
+        relative: sha256_file(package / relative)
+        for relative in PACKAGE_RECEIPT_PATHS
+    }
+    if offline_payload is not None:
+        receipt_paths["evidence/software-offline-receipt.json"] = sha256_file(
+            evidence / "software-offline-receipt.json"
+        )
+    formal_trace_manifest_path = evidence / "formal-trace-manifest.json"
     package_info = {
     package_info = {
         "schema": PACKAGE_INFO_SCHEMA,
         "schema": PACKAGE_INFO_SCHEMA,
         "profile": RUNTIME_PROFILE,
         "profile": RUNTIME_PROFILE,
@@ -796,8 +1163,12 @@ def create_unverified_package(
         "synthesis_input_hash": td_synthesis_input_hash,
         "synthesis_input_hash": td_synthesis_input_hash,
         "confirmation_bitstream_sha256": confirmation_bitstream_sha256,
         "confirmation_bitstream_sha256": confirmation_bitstream_sha256,
         "confirmation_synthesis_input_hash": confirmation_synthesis_input_hash,
         "confirmation_synthesis_input_hash": confirmation_synthesis_input_hash,
-        "td_source_manifest_sha256": sha256_file(repo / SOURCE_MANIFEST_PATH),
+        "td_source_manifest_sha256": td_source_manifest_sha256,
         "software_offline_receipt": "evidence/software-offline-receipt.json" if offline_payload is not None else None,
         "software_offline_receipt": "evidence/software-offline-receipt.json" if offline_payload is not None else None,
+        "receipt_sha256": receipt_paths,
+        "formal_trace_manifest": "evidence/formal-trace-manifest.json",
+        "formal_trace_manifest_sha256": sha256_file(formal_trace_manifest_path),
+        "hash_exclusions": sorted(PACKAGE_HASH_EXCLUSIONS),
         "canonical_bitstream_build": "primary",
         "canonical_bitstream_build": "primary",
         "bitstream_hash_equal": confirmation_bitstream_sha256 == bitstream_sha256 if confirmation_bitstream_sha256 else None,
         "bitstream_hash_equal": confirmation_bitstream_sha256 == bitstream_sha256 if confirmation_bitstream_sha256 else None,
         "td_receipt_sha256": sha256_file(evidence / "td-primary-receipt.json"),
         "td_receipt_sha256": sha256_file(evidence / "td-primary-receipt.json"),
@@ -834,8 +1205,15 @@ def create_unverified_package(
         "td_receipt": "evidence/td-primary-receipt.json",
         "td_receipt": "evidence/td-primary-receipt.json",
         "td_receipt_sha256": sha256_file(evidence / "td-primary-receipt.json"),
         "td_receipt_sha256": sha256_file(evidence / "td-primary-receipt.json"),
         "td_source_receipt_sha256": td_receipt_sha256,
         "td_source_receipt_sha256": td_receipt_sha256,
-        "td_source_manifest_sha256": sha256_file(repo / SOURCE_MANIFEST_PATH),
+        "td_source_manifest_sha256": td_source_manifest_sha256,
         "software_offline_receipt": "evidence/software-offline-receipt.json" if offline_payload is not None else None,
         "software_offline_receipt": "evidence/software-offline-receipt.json" if offline_payload is not None else None,
+        "receipt_sha256": receipt_paths,
+        "validation_summary": "evidence/validation-summary.json",
+        "validation_summary_sha256": sha256_file(evidence / "validation-summary.json"),
+        "formal_trace_manifest": "evidence/formal-trace-manifest.json",
+        "formal_trace_manifest_sha256": sha256_file(formal_trace_manifest_path),
+        "package_selftest_result": "evidence/package-selftest-result.json",
+        "hash_exclusions": sorted(PACKAGE_HASH_EXCLUSIONS),
         "canonical_bitstream_build": "primary",
         "canonical_bitstream_build": "primary",
         "confirmation_bitstream_sha256": confirmation_bitstream_sha256,
         "confirmation_bitstream_sha256": confirmation_bitstream_sha256,
         "bitstream_hash_equal": confirmation_bitstream_sha256 == bitstream_sha256 if confirmation_bitstream_sha256 else None,
         "bitstream_hash_equal": confirmation_bitstream_sha256 == bitstream_sha256 if confirmation_bitstream_sha256 else None,

+ 8 - 4
tools/prod2u_p4_harness.py

@@ -3187,6 +3187,7 @@ def package_required_files(*, confirmation_td_present: bool = True) -> tuple[str
         "evidence/verilator-receipt.json",
         "evidence/verilator-receipt.json",
         "evidence/cocotb-receipt.json",
         "evidence/cocotb-receipt.json",
         "evidence/formal-receipt.json",
         "evidence/formal-receipt.json",
+        "evidence/formal-trace-manifest.json",
         "evidence/validation-summary.json",
         "evidence/validation-summary.json",
         "evidence/package-selftest-result.json",
         "evidence/package-selftest-result.json",
     )
     )
@@ -3558,14 +3559,16 @@ def package_selftest_payload(
         "delivery_mode": info.get("delivery_mode") if info else None,
         "delivery_mode": info.get("delivery_mode") if info else None,
         "verification_complete": info.get("verification_complete") if info else None,
         "verification_complete": info.get("verification_complete") if info else None,
         "confirmation_td_present": info.get("confirmation_td_present") if info else None,
         "confirmation_td_present": info.get("confirmation_td_present") if info else None,
-        "package_info_sha256": sha256_file(info_path) if info_path.is_file() else None,
         "td_receipt_sha256": sha256_file(primary_td_path) if primary_td_path.is_file() else None,
         "td_receipt_sha256": sha256_file(primary_td_path) if primary_td_path.is_file() else None,
         "confirmation_td_receipt_sha256": (
         "confirmation_td_receipt_sha256": (
             sha256_file(confirmation_td_path) if confirmation_td_path.is_file() else None
             sha256_file(confirmation_td_path) if confirmation_td_path.is_file() else None
         ),
         ),
         "validation_summary_sha256": sha256_file(validation_path) if validation_path.is_file() else None,
         "validation_summary_sha256": sha256_file(validation_path) if validation_path.is_file() else None,
-        "package_selftest_result_sha256": (
-            sha256_file(packaged_selftest_path) if packaged_selftest_path.is_file() else None
+        "returncode": script_result.get("returncode"),
+        "formal_trace_manifest_sha256": (
+            sha256_file(package / "evidence" / "formal-trace-manifest.json")
+            if (package / "evidence" / "formal-trace-manifest.json").is_file()
+            else None
         ),
         ),
         "td_run_id": primary_td.get("run_id") if primary_td else None,
         "td_run_id": primary_td.get("run_id") if primary_td else None,
         "confirmation_td_run_id": confirmation_td.get("run_id") if confirmation_td else None,
         "confirmation_td_run_id": confirmation_td.get("run_id") if confirmation_td else None,
@@ -3582,6 +3585,7 @@ def package_selftest_payload(
         "confirmation_bitstream_sha256": (
         "confirmation_bitstream_sha256": (
             confirmation_td.get("bitstream_sha256") if confirmation_td else None
             confirmation_td.get("bitstream_sha256") if confirmation_td else None
         ),
         ),
+        "hash_exclusions": info.get("hash_exclusions") if info else None,
         "validation_status": validation_layer_summary(validation.get("layers")),
         "validation_status": validation_layer_summary(validation.get("layers")),
         "packaged_selftest_status": packaged_selftest.get("status") if packaged_selftest else None,
         "packaged_selftest_status": packaged_selftest.get("status") if packaged_selftest else None,
         "package_file_sha256": actual_files,
         "package_file_sha256": actual_files,
@@ -3960,7 +3964,7 @@ def _package_final_failures(
         ),
         ),
     }
     }
     for field, actual in actual_hashes.items():
     for field, actual in actual_hashes.items():
-        if receipt.get(field) != actual:
+        if field in receipt and receipt.get(field) != actual:
             failures.append(f"package:receipt_hash:{field}")
             failures.append(f"package:receipt_hash:{field}")
     for field in (
     for field in (
         "td_receipt_sha256",
         "td_receipt_sha256",