import json
import tempfile
from pathlib import Path
import proofframe as pf
CONTRACT = {
"version": "proofframe.contract.v1",
"columns": {
"order_id": {"required": True, "unique": True, "not_null": True},
"amount": {"not_null": True, "min": 0.0},
},
}
CSV_OPTIONS = {
"delimiter": ";",
"decimal_point": ",",
"encoding": "utf-8",
"null_values": ["NULL"],
"column_types": {"order_id": "int64", "amount": "float64"},
}
POLICY = {"max_violations": 0, "minimum_evaluated": {"amount": 3}}
def main() -> None:
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
delivery = root / "orders.csv"
delivery.write_text(
"order_id;amount\n1001;1234,50\n1002;99,00\n1003;7,25\n",
encoding="utf-8",
)
keys = pf.generate_keypair()
bundle = pf.accept_file(
delivery,
CONTRACT,
policy=POLICY,
csv_options=CSV_OPTIONS,
output=root / "acceptance.json",
private_key=keys["private_key"],
)
decision = bundle["payload"]["decision"]
print(json.dumps(decision, indent=2))
if decision["status"] != "accepted" or decision["evaluated"]["amount"] != 3:
raise SystemExit(f"the delivery was not accepted as documented: {decision}")
saved = json.loads((root / "acceptance.json").read_text(encoding="utf-8"))
if not pf.verify_acceptance(saved, expected_public_key=keys["public_key"])["valid"]:
raise SystemExit("the saved bundle did not verify")
if saved["payload"]["decision"]["status"] != "accepted":
raise SystemExit("the saved bundle carries a different decision")
if not all(bundle["payload"][i] for i in ("contract_id", "policy_id", "read_settings_id")):
raise SystemExit("the bundle is missing a bound identity")
tampered = json.loads(json.dumps(saved))
tampered["payload"]["read_settings"]["csv"]["decimal_point"] = "."
if pf.verify_acceptance(tampered, expected_public_key=keys["public_key"])["valid"]:
raise SystemExit("an edited read setting still verified")
short = root / "short.csv"
short.write_text("order_id;amount\n2001;10,00\n", encoding="utf-8")
rejected = pf.accept_file(short, CONTRACT, policy=POLICY, csv_options=CSV_OPTIONS)
if rejected["payload"]["decision"] != {
"status": "rejected",
"reasons": ["minimum_evaluated:amount"],
"evaluated": rejected["payload"]["decision"]["evaluated"],
}:
raise SystemExit(f"unexpected rejection: {rejected['payload']['decision']}")
unreadable = pf.accept_file(
root / "never-delivered.csv", CONTRACT, policy=POLICY, csv_options=CSV_OPTIONS
)
if unreadable["payload"]["decision"]["status"] != "unknown":
raise SystemExit("a file that could not be read was not reported as unknown")
print("rejected:", rejected["payload"]["decision"]["reasons"])
print("unknown:", unreadable["payload"]["decision"]["reasons"])
if __name__ == "__main__":
main()