Files

86 lines
4.1 KiB
Python

"""Rehearse the candidate in a private reflink copy and strictly decode every changed member."""
import argparse
import hashlib
import json
import subprocess
import sys
import tempfile
from pathlib import Path
from stage import OPS, PROJECT, check_parent, read, save, sha
sys.path.insert(0, str(OPS / 'patchserver'))
import store_step
import verify_ui
def stage_blob(blobs, raw):
# Scratch compression only. The logical STORE records use ordinary full frames.
packed = subprocess.run(['zstd', '-q', '-1', '-T4', '--stdout'], input=raw,
stdout=subprocess.PIPE, check=True).stdout
digest = sha(packed)
(blobs / (digest + '.zst')).write_bytes(packed)
return digest, len(packed)
def verify(work):
inputs = read(work / 'inputs.json')
check_parent(inputs)
candidate = work / 'candidate'
frames, physical, plan = store_step.candidate_frames(candidate)
parent_store = Path(inputs['parent_store'])
if store_step.build_key(parent_store) != plan['parent_build_key']:
raise ValueError('Rehearsal seed no longer matches stage parent')
assets = read(work / 'members.json')
with tempfile.TemporaryDirectory(prefix='content-rehearsal-', dir=work) as scratch:
temp = Path(scratch)
clone = temp / 'store'
subprocess.run(['cp', '-a', '--reflink=always', parent_store, clone], check=True)
blobs = temp / 'blobs'
blobs.mkdir()
lines = []
for ekey, raw in sorted(frames.items()):
digest, size = stage_blob(blobs, raw)
lines.append(f'FRAME {ekey.hex()} {len(raw)} {sha(raw)} {digest} {size} zstd')
for target, file in physical.items():
if target.startswith('Data/config/'):
raw = file.read_bytes()
digest, size = stage_blob(blobs, raw)
lines.append(f'CONF {target} {sha(raw)} {len(raw)} {digest} {size}')
activation = plan['forward']['final_activation']
raw = (candidate / activation['file']).read_bytes()
digest, size = stage_blob(blobs, raw)
lines.append(f"ACTIVATE .build.info {activation['parent_sha256']} {sha(raw)} {digest} {size}")
step = {'parent':plan['parent_build_key'], 'child':plan['candidate_build_key'], 'lines':lines}
result = store_step.apply(clone, step, blobs)
if store_step.build_key(clone) != plan['candidate_build_key']:
raise ValueError('Portable STORE replay did not activate the staged content')
list_path = temp / 'member-ids.txt'
list_path.write_text(''.join(f"{r['fdid']}\n" for r in assets))
decoded = temp / 'decoded'
with (work / 'candidate-extract.log').open('wb') as log:
subprocess.run([PROJECT / 'tools/casc-tool/build/casc-tool', 'extract-batch',
'--strict-encrypted','--from-list',list_path,decoded,'--storage',clone,
'--locale','enus','--listfile',inputs['listfile']],
stdout=log, stderr=subprocess.STDOUT, check=True)
for row in assets:
actual = sha((decoded / row['path']).read_bytes())
if actual != row['sha256']:
raise ValueError(f"Packaged FDID {row['fdid']} differs: {actual}")
original = {path:(Path(inputs['decoded_ui']) / path).read_bytes() for path in verify_ui.paths()}
packaged = {path:(decoded / path).read_bytes() if (decoded / path).exists() else raw
for path, raw in original.items()}
verify_ui.verify(original, packaged)
check_parent(inputs)
stage_sha = hashlib.sha256((candidate / 'stage-plan.json').read_bytes()).hexdigest()
save(work / 'readback.json', {'published_parent':step['parent'], 'candidate':step['child'],
'stage_plan_sha256':stage_sha, 'portable_store':result, 'decoded_and_matched':len(assets),
'members':assets})
print(f"{step['child']}: {len(assets)} packaged enUS members match their candidate hashes.")
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('work',type=Path)
verify(parser.parse_args().work.resolve())