native_witness.py

verification/tools/native_witness.py

native_witness.py131 lines← SDK documentation
1"""Compile and execute the finite standalone native frontend witnesses."""2from pathlib import Path3import json4import os5import re6import subprocess78import creusot9import equality_bridge1011INPUTS = (Path(__file__), Path(equality_bridge.__file__), Path(equality_bridge.kani.__file__),12          Path(equality_bridge.kani.__file__).with_suffix('.toml'),13          creusot.ROOT / 'cdk-rsx/rust-toolchain.toml')14FILES = ('witness.rs', 'witness', 'compile.stdout', 'compile.stderr', 'run.stdout', 'run.stderr')151617def environment(compiler):18    env = dict(os.environ)19    for key in ('RUSTC_WRAPPER', 'RUSTC_WORKSPACE_WRAPPER', 'RUSTFLAGS', 'CARGO_ENCODED_RUSTFLAGS',20                'LD_LIBRARY_PATH', 'LD_PRELOAD', 'LD_AUDIT'):21        env.pop(key, None)22    env.update(RUSTC=str(compiler), RUSTUP_AUTO_INSTALL='0',23               PATH=str(compiler.parent) + ':' + env['PATH'])24    return env252627def snapshot(paths):28    return {str(path.relative_to(creusot.ROOT)): creusot.sha(path) for path in paths}293031def checkout_identity():32    creusot.require(not creusot.git(creusot.ROOT / 'cdk-rsx', 'status', '--porcelain'), 'Native witness SDK is dirty')33    return {'factory': creusot.git(creusot.ROOT, 'rev-parse', 'HEAD'),34            'sdk': creusot.git(creusot.ROOT / 'cdk-rsx', 'rev-parse', 'HEAD')}353637def compiler_identity():38    compiler = equality_bridge.production_compiler().resolve()39    creusot.require(compiler.is_file() and os.access(compiler, os.X_OK), 'Missing preprovisioned production compiler')40    digest = creusot.sha(compiler)41    result = subprocess.run([str(compiler), '--version'], env=environment(compiler),42                            capture_output=True, text=True, timeout=30)43    creusot.require(result.returncode == 0 and result.stdout.strip() == equality_bridge.VERSIONS['production'],44                    'Wrong production compiler version')45    creusot.require(compiler == equality_bridge.production_compiler().resolve() and creusot.sha(compiler) == digest,46                    'Native compiler changed during identity capture')47    return {'path': str(compiler), 'sha256': digest, 'version': result.stdout.strip()}484950def regular(path):51    return path.is_file() and not path.is_symlink()525354def executable_hash(path, expected=None):55    creusot.require(regular(path) and os.access(path, os.X_OK), 'Missing or substituted native executable')56    digest = creusot.sha(path)57    creusot.require(expected is None or digest == expected, 'Native executable changed')58    return digest596061def verify(ticket, witnesses, paths, before):62    output = Path(ticket['output'])63    receipt = output / 'native.json'64    creusot.require(regular(receipt) and type(ticket['record_sha256']) is str65                    and re.fullmatch(r'[0-9a-f]{64}', ticket['record_sha256'])66                    and creusot.sha(receipt) == ticket['record_sha256'], 'Native witness record changed')67    data = ticket['qualification']68    creusot.require(json.loads(receipt.read_text()) == data, 'Native witness metadata differs')69    creusot.require(data['sources'] == before == snapshot(paths), 'Native witness sources changed')70    creusot.require(data['checkout'] == checkout_identity(), 'Native witness checkout changed')71    creusot.require(data['compiler'] == compiler_identity(), 'Native witness compiler changed')72    expected = {str(source.relative_to(creusot.ROOT)): sentinel for source, sentinel in witnesses}73    creusot.require(set(data['witnesses']) == set(expected), 'Missing native witness')74    for source, sentinel in witnesses:75        record = data['witnesses'][str(source.relative_to(creusot.ROOT))]76        directory = output / source.stem77        creusot.require(set(record) == {'sentinel', 'files', 'compile_exit_code', 'run_exit_code'}78                        and all(type(record[key]) is int and record[key] == 079                                for key in ('compile_exit_code', 'run_exit_code'))80                        and record['sentinel'] == sentinel and set(record['files']) == set(FILES)81                        and all(type(value) is str and re.fullmatch(r'[0-9a-f]{64}', value)82                                for value in record['files'].values()), 'Invalid native witness identities')83        creusot.require(all(regular(directory / name) and creusot.sha(directory / name) == digest84                            for name, digest in record['files'].items()), 'Native witness artifacts changed')85        creusot.require(os.access(directory / 'witness', os.X_OK), 'Native witness artifact is not executable')86        creusot.require((directory / 'witness.rs').read_bytes() == source.read_bytes(), 'Native staged source differs')87        creusot.require((directory / 'run.stdout').read_bytes() == (sentinel + '\n').encode(), 'Wrong native witness sentinel')888990def qualify(output, witnesses, paths, before):91    output.mkdir()92    compiler = compiler_identity()93    data = {'checkout': checkout_identity(), 'compiler': compiler, 'sources': before, 'witnesses': {}}94    executable = Path(compiler['path'])95    env = environment(executable)96    for source, sentinel in witnesses:97        directory = output / source.stem98        directory.mkdir()99        staged, artifact = directory / 'witness.rs', directory / 'witness'100        staged.write_bytes(source.read_bytes())101        sealed = {'witness.rs': creusot.sha(staged)}102103        def unchanged():104            creusot.require(snapshot(paths) == before, 'Native witness sources changed')105            creusot.require(compiler_identity() == compiler, 'Native witness compiler changed')106            creusot.require(checkout_identity() == data['checkout'], 'Native witness checkout changed')107            creusot.require(all(regular(directory / name) and creusot.sha(directory / name) == digest108                                for name, digest in sealed.items()), 'Native staged source/artifact changed')109110        unchanged()111        with (directory / 'compile.stdout').open('wb') as stdout, (directory / 'compile.stderr').open('wb') as stderr:112            compiled = subprocess.run([str(executable), '--edition=2024', '--target', equality_bridge.TARGET,113                '-Cpanic=unwind', str(staged), '-o', str(artifact)], cwd=directory, env=env,114                stdout=stdout, stderr=stderr, timeout=120)115        creusot.require(compiled.returncode == 0 and regular(artifact) and os.access(artifact, os.X_OK),116                        'Native witness compilation failed')117        sealed.update({name: creusot.sha(directory / name) for name in ('witness', 'compile.stdout', 'compile.stderr')})118        unchanged()119        with (directory / 'run.stdout').open('wb') as stdout, (directory / 'run.stderr').open('wb') as stderr:120            ran = subprocess.run([str(artifact)], cwd=directory, env=env, stdout=stdout, stderr=stderr, timeout=30)121        creusot.require(ran.returncode == 0 and (directory / 'run.stdout').read_bytes() == (sentinel + '\n').encode(),122                        'Native witness failed or returned wrong sentinel')123        sealed.update({name: creusot.sha(directory / name) for name in ('run.stdout', 'run.stderr')})124        unchanged()125        data['witnesses'][str(source.relative_to(creusot.ROOT))] = {'sentinel': sentinel, 'files': sealed,126            'compile_exit_code': compiled.returncode, 'run_exit_code': ran.returncode}127    receipt = output / 'native.json'128    receipt.write_text(json.dumps(data, indent=2) + '\n')129    ticket = {'output': str(output), 'qualification': data, 'record_sha256': creusot.sha(receipt)}130    verify(ticket, witnesses, paths, before)131    return ticket