provider_resource.py

verification/tools/provider_resource.py

provider_resource.py243 lines← SDK documentation
1#!/usr/bin/env python32"""Check actual native page observations and an owning split-byte-loan pilot."""3from pathlib import Path4import argparse5import datetime6import fcntl7import json8import re9import subprocess10import sys11import uuid1213import creusot14import run_receipt15import creusot_report16from rust_source import complete_item17import rust_source1819ROOT = creusot.ROOT20PROOF = ROOT / 'verification/proofs/provider/creusot/admission.rs'21MEMORY = ROOT / 'cdk-rsx/crates/cdk-rsx-platform/src/memory.rs'22POOL = ROOT / 'cdk-rsx/crates/cdk-rsx-platform/src/memory/page_pool.rs'23EXPECTED = {24    'admit/proof.json': 'vc_admit',25    'impl_VecBacking/pages_proof/proof.json': 'vc_pages_proof',26    'write_control_while_root_loaned/proof.json': 'vc_write_control_while_root_loaned',27    **{name + '/proof.json': 'vc_' + name for name in (28        'one_page_witness', 'empty_witness', 'partial_page_witness', 'two_page_witness')},29}30313233def native_source(memory):34    declaration = "struct VecBacking<'a>(&'a mut Vec<u8>);"35    creusot.require(memory.count(declaration) == 1, 'Native provider declaration changed')36    original = declaration + '\n' + complete_item(memory, "unsafe impl page_pool::Backing for VecBacking<'_>")37    marker = '#[creusot_std::prelude::trusted]'38    creusot.require(marker not in original, 'Unexpected product proof annotation')39    staged, count = re.subn(r'(?m)^([ \t]*)((?:unsafe )?fn )',40        lambda m: m[1] + marker + '\n' + m[1] + m[2], original)41    creusot.require(count == 4, 'Unexpected native Backing method set')42    recovered = re.sub(r'(?m)^[ \t]*#\[creusot_std::prelude::trusted\]\n', '', staged)43    creusot.require(recovered == original, 'Native target source staging changed bytes')44    return staged454647def audit_proof(source):48    creusot.require(not re.search(r'#\[[^\]\n]*\b(?:trusted|assume|ignore|external_body)\b', source),49                    'Proof must not add a trusted/ignored algorithm')50    creusot.require('Ghost::conjure' not in source, 'Proof must not manufacture a permission')51    erasure_lines = [line.strip() for line in source.splitlines() if '#[erasure(' in line]52    creusot.require(erasure_lines == ["#[erasure(<VecBacking<'_> as page_pool::Backing>::pages)]"],53                    'Unexpected producer erasure target or inline target body')54    ordinary = '\n'.join(line for line in source.splitlines() if not line.strip().startswith('#[erasure('))55    creusot.require(not re.search(r'(?:\.\s*(?:pages|grow_to|control_ptr|zero)\s*\(|::\s*(?:pages|grow_to|control_ptr|zero)\b)', ordinary),56                    'Original trusted target used as proof callee')575859def stage(output, control):60    memory, pool = MEMORY.read_text(), POOL.read_text()61    constants = []62    for name in ('PAGE_BYTES', 'ROOT_BYTES'):63        matches = [line for line in pool.splitlines() if line.startswith('pub const ' + name + ':')]64        creusot.require(len(matches) == 1, 'Product constant changed: ' + name)65        constants.append('#[creusot_std::prelude::trusted]\n#[creusot_std::prelude::constant(eval)]\n' + matches[0])66    text = PROOF.read_text()67    audit_proof(text)68    if control == 'erasure':69        old, new = 'self.0.len() / page_pool::PAGE_BYTES', 'self.0.len() / page_pool::PAGE_BYTES + 1'70    elif control == 'semantic':71        old, new = 'assert!(bytes[0] == 0xa5u8);', 'assert!(bytes[0] == 0x5au8);'72    elif control == 'alias':73        old = 'let mut resource = admit(&mut backing).unwrap();'74        # First one-page witness only. The later resource use keeps the loan live.75        new = old + '\n        backing.0.resize(page_pool::PAGE_BYTES * 2, 0);'76    else:77        old = new = None78    if old is not None:79        creusot.require(text.count(old) == (2 if control == 'alias' else 1), 'Control anchor changed')80        text = text.replace(old, new, 1)81    (output / 'src').mkdir()82    (output / 'src/lib.rs').write_text('#![allow(dead_code,unexpected_cfgs)]\n'83        '#[cfg(not(all(target_pointer_width="64", target_endian="little")))]\n'84        'compile_error!("provider resource suite requires native64 little-endian");\nmod native;\n')85    (output / 'src/native.rs').write_text('mod page_pool { use core::ops::Range;\n'86        + '\n'.join(constants) + '\n' + complete_item(pool, 'pub unsafe trait Backing')87        + '\n}\n' + native_source(memory) + '\n#[path="admission.rs"] mod proof;\n')88    (output / 'src/admission.rs').write_text(text)89    for name in ('Cargo.toml', 'Cargo.lock', 'why3find.json'):90        (output / name).write_bytes((creusot.PROOF.parent / name).read_bytes())91    return {str(p.relative_to(output)): creusot.sha(p) for p in output.rglob('*') if p.is_file()}929394def validate_diagnostics(log, exit_code, goal):95    if goal:96        creusot.require_logical_rejection(log, exit_code, goal)97    else:98        creusot.require(type(exit_code) is int and exit_code == 0, 'Unexpected native proof exit')99        creusot.require_no_fatal_diagnostics(log, [])100101102def validate_reports(proof_root, inventory, control, exit_code, log):103    validate_diagnostics(log, exit_code, 'vc_one_page_witness' if control == 'semantic' else None)104    if isinstance(inventory, creusot_report.GoalInventory):105        inventory.verify()106        expected_goals = inventory.goals107    else:108        expected_goals = inventory109    if control is None:110        result = creusot_report.validate_directory(proof_root, inventory, expected=EXPECTED)111        return {**result, 'open_goals': 0}112    creusot.require(control == 'semantic', 'Unexpected report control')113    found = {p.relative_to(proof_root).as_posix(): p for p in proof_root.rglob('proof.json')}114    creusot.require(set(found) == set(EXPECTED) == set(expected_goals),115                    'Missing or unexpected provider report/inventory')116    summary = {'files': len(found), 'goal_count': 0, 'prover_leaves': 0, 'open_goals': 0}117    for relative, path in found.items():118        creusot.require(not path.is_symlink(), 'Provider report symlink refused')119        report = creusot_report.parse_report(path.read_text())120        if relative != 'one_page_witness/proof.json':121            result = creusot_report.validate_report(report, EXPECTED[relative], expected_goals[relative])122            summary['goal_count'] += result['goal_count']123            summary['prover_leaves'] += result['prover_leaves']124            continue125        goals = creusot_report.report_goals(report, EXPECTED[relative])126        creusot.require(set(goals) == set(expected_goals[relative]),127                        'Missing or unexpected semantic-control goal')128        for name, node in goals.items():129            deliberate = name == 'vc_one_page_witness'130            leaves, opened = creusot_report.proof_counts(node, allow_open=deliberate)131            creusot.require(not deliberate or opened == 1,132                            'Semantic control must leave exactly its designated goal open')133            summary['prover_leaves'] += leaves134            summary['open_goals'] += opened135        summary['goal_count'] += len(goals)136    creusot.require(summary['prover_leaves'] > 0 and summary['open_goals'] == 1,137                    'Unexpected semantic-control proof outcome')138    return summary139140141def validate_compile_control(log, exit_code, control):142    log = creusot.diagnostic_text(log)143    errors = [line for line in log.splitlines() if line.startswith('error')]144    substantive = [line for line in errors if not creusot.one_error_compiler_summary(line)]145    creusot.require(type(exit_code) is int and exit_code == 1 and len(errors) == 2 and len(substantive) == 1,146                    'Compiler control must fail only its designated error')147    if control == 'erasure':148        expected = "error: failed #[erasure] check for native::proof::<impl native::VecBacking<'_>>::pages_proof"149        creusot.require(substantive == [expected] and 'mismatched statement' in log,150                        'Changed source body was not rejected by strict erasure')151    else:152        expected = 'error[E0499]: cannot borrow `*backing.0` as mutable more than once at a time'153        creusot.require(substantive == [expected] and 'first borrow later used here' in log,154                        'Live-loan growth was not rejected at its expected borrow')155    creusot.require_no_fatal_diagnostics(log, [*errors, 'Error: Compilation failed'])156157158def verify_inputs(inputs, before, binaries, receipt):159    receipt.verify()160    creusot.require(before == {str(p.relative_to(ROOT)): creusot.sha(p) for p in inputs},161                    'Provider input changed during proof')162    creusot.require(creusot.validate_binaries() == binaries, 'Pinned verifier changed during proof')163    creusot.require(not creusot.git(ROOT / 'cdk-rsx', 'status', '--porcelain'),164                    'SDK source changed during proof')165166167def run(control=None):168    creusot.validate_source()169    binaries = creusot.validate_binaries()170    stamp = datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')171    output = creusot.TEMP / ('provider-' + stamp + '-' + (control or 'positive') + '-' + uuid.uuid4().hex[:8])172    output.mkdir(parents=True)173    inputs = [*rust_source.INPUTS, MEMORY, POOL, PROOF, Path(__file__), *run_receipt.INPUTS, Path(creusot.__file__),174        Path(creusot.__file__).with_suffix('.toml'), Path(creusot.__file__).with_suffix('.nix'),175        Path(creusot_report.__file__), *creusot.FRONTEND_PATCHES,176        *[creusot.PROOF.parent / name for name in ('Cargo.toml', 'Cargo.lock', 'why3find.json')]]177    before = {str(p.relative_to(ROOT)): creusot.sha(p) for p in inputs}178    staged = stage(output, control)179    creusot.require(not creusot.git(ROOT / 'cdk-rsx', 'status', '--porcelain'), 'SDK source is dirty')180    receipt = run_receipt.write(ROOT, output, {181        'factory': creusot.git(ROOT, 'rev-parse', 'HEAD'),182        'sdk': creusot.git(ROOT / 'cdk-rsx', 'rev-parse', 'HEAD'),183        'sources': before, 'staged': staged, 'binaries': binaries,184        'nix_store': str(creusot.TOOL.resolve()), 'control': control,185        'scope': 'native64 source pages; proof-side exclusive Vec byte loans; no u64/opaque-key/Wasm transport',186    })187    command = [creusot.TOOL / 'bin/cargo-creusot', 'creusot', '--erasure-check=error',188               '-j', '4', 'native/proof', '--only=coma', '--', '--locked']189    print('Provider ' + (control or 'positive') + ': ' + str(output), flush=True)190    env = creusot.environment(output)191    env['CARGO_TERM_COLOR'] = 'never'192    with (output / 'run.log').open('w') as log:193        translation = subprocess.run([str(x) for x in command], cwd=output,194            env=env, stdout=log, stderr=subprocess.STDOUT)195    verify_inputs(inputs, before, binaries, receipt)196    if control in ('erasure', 'alias'):197        validate_compile_control((output / 'run.log').read_text(), translation.returncode, control)198        summary = {'status': 'EXPECTED_' + ('ERASURE' if control == 'erasure' else 'BORROW') + '_REJECTION'}199    else:200        creusot.require(translation.returncode == 0, 'Provider translation failed')201        proof_root = output / 'verif/page_pool_creusot_rlib/native/proof'202        inventory = creusot_report.goal_inventory(203            proof_root, EXPECTED, creusot.TOOL / 'bin/why3',204            translation_root=output / 'verif/page_pool_creusot_rlib',205            load_paths=[creusot.TOOL / 'share/why3find/packages/creusot'],206            config=creusot.TOOL / 'creusot_why3.conf', cwd=output, env=env,207            output_dir=output / 'goal-inventory')208        (output / 'goal-inventory.json').write_text(json.dumps({209            'goals': {name: sorted(goals) for name, goals in inventory.goals.items()},210            'inputs': inventory.hashes,211        }, indent=2) + '\n')212        command = [creusot.TOOL / 'bin/cargo-creusot', 'creusot', '--only=prove',213                   '-j', '4', 'native/proof', '--', '--locked']214        with (output / 'run.log').open('a') as log:215            process = subprocess.run([str(x) for x in command], cwd=output,216                env=env, stdout=log, stderr=subprocess.STDOUT)217        verify_inputs(inputs, before, binaries, receipt)218        inventory.verify()219        creusot.require(process.returncode == (1 if control == 'semantic' else 0),220                        'Provider proof did not complete as expected')221        summary = validate_reports(proof_root, inventory, control, process.returncode, (output / 'run.log').read_text())222    print(json.dumps({'suite': control or 'positive', 'summary': summary, 'output': str(output)}, indent=2))223    return output224225226def main():227    parser = argparse.ArgumentParser(description=__doc__)228    parser.add_argument('suite', choices=('positive', 'semantic', 'erasure', 'alias', 'all'), nargs='?', default='all')229    args = parser.parse_args()230    creusot.TEMP.mkdir(exist_ok=True)231    with (creusot.TEMP / '.creusot-runner.lock').open('w') as lock:232        fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)233        for control in (None, 'semantic', 'erasure', 'alias') if args.suite == 'all' else (None if args.suite == 'positive' else args.suite,):234            run(control)235236237if __name__ == '__main__':238    try:239        with creusot.cache_lease():240            main()241    except (RuntimeError, subprocess.CalledProcessError, BlockingIOError) as error:242        print('Provider verification refused: ' + str(error), file=sys.stderr)243        sys.exit(1)