From f9fff2cb802f35faa3ecea2c4d88380656fff121 Mon Sep 17 00:00:00 2001 From: Shawn Blackmore Date: Thu, 1 Oct 2026 07:51:39 -0700 Subject: [PATCH] fix: close SQLite handles on Windows --- src/31_Profiles/governance_privacy.py | 42 ++++++++----- src/31_Profiles/profile_core.py | 26 ++++++-- src/31_Profiles/resilience_interop.py | 40 ++++++++---- .../institutional_semantics.py | 62 ++++++++++++------- .../privacy_provenance.py | 50 +++++++++------ .../topology_crypto.py | 42 ++++++++----- src/36_Adoption_Layer/rights_passport.py | 22 +++++-- src/37_Verifiable_Reality/evidence_objects.py | 26 ++++++-- src/38_Global_Passports/global_passport.py | 20 +++++- src/38_Global_Passports/profile_registry.py | 24 +++++-- src/38_Global_Passports/protocol_origin.py | 24 +++++-- src/40_BTDU/canonical_btdu.py | 9 ++- tests/test_v3_btdu.py | 2 + tests/test_v3_protocol_origin_lineage.py | 6 +- 14 files changed, 281 insertions(+), 114 deletions(-) diff --git a/src/31_Profiles/governance_privacy.py b/src/31_Profiles/governance_privacy.py index 7aab16da..f56829b4 100644 --- a/src/31_Profiles/governance_privacy.py +++ b/src/31_Profiles/governance_privacy.py @@ -2,6 +2,20 @@ from pathlib import Path from typing import Any import hashlib, json, secrets, sqlite3, time +from contextlib import contextmanager + + +@contextmanager +def dbctx(path): + db = sqlite3.connect(path) + try: + yield db + db.commit() + except Exception: + db.rollback() + raise + finally: + db.close() def now_ms(): return int(time.time() * 1000) def canon(v): return json.dumps(v, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=str).encode() @@ -48,7 +62,7 @@ class DisputeLedger: KINDS = {"CLAIM", "CHALLENGE", "EVIDENCE", "RULING", "SUPERSESSION", "CONSEQUENCE"} def __init__(self, root: str | Path, identity): self.path = Path(root) / "entity_v3_disputes.sqlite"; self.identity = identity - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("""CREATE TABLE IF NOT EXISTS records( record_id TEXT PRIMARY KEY, kind TEXT NOT NULL, actor_entity_id TEXT NOT NULL, subject_ref TEXT NOT NULL, target_ref TEXT, payload_json TEXT NOT NULL, @@ -68,7 +82,7 @@ def record(self, kind: str, actor: str, subject_ref: str, payload: dict, "authority_basis": authority_basis, "created_at_ms": now_ms(), "history_rewrite_prohibited": True} sig = self.identity.sign(actor, body) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("INSERT INTO records VALUES(?,?,?,?,?,?,?,?,?)", ( body["record_id"], kind, actor, body["subject_ref"], target_ref, json.dumps(body["payload"], sort_keys=True), authority_basis, @@ -76,7 +90,7 @@ def record(self, kind: str, actor: str, subject_ref: str, payload: dict, return dict(body, signature=sig) def state(self, subject_ref: str) -> dict: - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.row_factory = sqlite3.Row rows = db.execute("SELECT * FROM records WHERE subject_ref=? ORDER BY created_at_ms,record_id", (subject_ref,)).fetchall() @@ -95,7 +109,7 @@ class StatusTimeProfile: """Signed time/status objects with deterministic stale and revocation behaviour.""" def __init__(self, root: str | Path, identity): self.path = Path(root) / "entity_v3_status_time.sqlite"; self.identity = identity - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("""CREATE TABLE IF NOT EXISTS statuses( status_id TEXT PRIMARY KEY, subject_ref TEXT NOT NULL, issuer TEXT NOT NULL, state TEXT NOT NULL, epoch INTEGER NOT NULL, effective_at_ms INTEGER NOT NULL, @@ -116,7 +130,7 @@ def publish_status(self, issuer: str, subject_ref: str, state: str, *, epoch: in if stale_policy not in {"FAIL_CLOSED", "READ_ONLY_GRACE", "ALLOW_UNTIL_EXPIRY"}: raise ValueError("invalid stale policy") effective = int(effective_at_ms or now_ms()); expires = effective + max(1, int(ttl_ms)) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: latest = db.execute("SELECT COALESCE(MAX(epoch),-1) FROM statuses WHERE subject_ref=?", (subject_ref,)).fetchone()[0] if int(epoch) <= int(latest): raise ValueError("status epoch must increase") @@ -125,7 +139,7 @@ def publish_status(self, issuer: str, subject_ref: str, state: str, *, epoch: in "effective_at_ms": effective, "expires_at_ms": expires, "stale_policy": stale_policy, "created_at_ms": now_ms()} sig = self.identity.sign(issuer, body) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("INSERT INTO statuses VALUES(?,?,?,?,?,?,?,?,?,?)", ( body["status_id"], subject_ref, issuer, state, int(epoch), effective, expires, stale_policy, body["created_at_ms"], json.dumps(sig, sort_keys=True))) @@ -133,7 +147,7 @@ def publish_status(self, issuer: str, subject_ref: str, state: str, *, epoch: in def evaluate(self, subject_ref: str, *, at_ms=None) -> dict: at = int(at_ms or now_ms()) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.row_factory = sqlite3.Row row = db.execute("SELECT * FROM statuses WHERE subject_ref=? AND effective_at_ms<=? " "ORDER BY epoch DESC LIMIT 1", (subject_ref, at)).fetchone() @@ -154,7 +168,7 @@ class RecoveryQuorum: """Multi-party approval gate wrapped around the existing cryptographic recovery mechanism.""" def __init__(self, root: str | Path, identity): self.path = Path(root) / "entity_v3_recovery_quorum.sqlite"; self.identity = identity - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("""CREATE TABLE IF NOT EXISTS policies( entity_id TEXT PRIMARY KEY, approvers_json TEXT NOT NULL, threshold INTEGER NOT NULL)""") db.execute("""CREATE TABLE IF NOT EXISTS requests( @@ -168,14 +182,14 @@ def set_policy(self, entity_id: str, approvers: list[str], threshold: int) -> di unique = sorted(set(approvers)); threshold = int(threshold) if threshold < 1 or threshold > len(unique): raise ValueError("invalid recovery threshold") for a in unique: self.identity.load_manifest(a) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("INSERT OR REPLACE INTO policies VALUES(?,?,?)", (entity_id, json.dumps(unique), threshold)) return {"entity_id": entity_id, "approvers": unique, "threshold": threshold} def request(self, entity_id: str, reason: Any) -> dict: request_id = rid("recovery3") - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: if not db.execute("SELECT 1 FROM policies WHERE entity_id=?", (entity_id,)).fetchone(): raise KeyError("recovery quorum policy missing") db.execute("INSERT INTO requests VALUES(?,?,?,?,?)", @@ -183,7 +197,7 @@ def request(self, entity_id: str, reason: Any) -> dict: return {"request_id": request_id, "entity_id": entity_id, "status": "OPEN"} def approve(self, request_id: str, approver: str) -> dict: - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.row_factory = sqlite3.Row req = db.execute("SELECT * FROM requests WHERE request_id=? AND status='OPEN'", (request_id,)).fetchone() @@ -194,14 +208,14 @@ def approve(self, request_id: str, approver: str) -> dict: body = {"schema": "entity-v3-recovery-approval-v1", "request_id": request_id, "entity_id": req["entity_id"], "approver": approver, "created_at_ms": now_ms()} sig = self.identity.sign(approver, body) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("INSERT OR REPLACE INTO approvals VALUES(?,?,?,?)", (request_id, approver, body["created_at_ms"], json.dumps(sig, sort_keys=True))) count = db.execute("SELECT COUNT(*) FROM approvals WHERE request_id=?", (request_id,)).fetchone()[0] return dict(body, signature=sig, approval_count=count, threshold=int(policy["threshold"])) def execute(self, request_id: str) -> dict: - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.row_factory = sqlite3.Row req = db.execute("SELECT * FROM requests WHERE request_id=? AND status='OPEN'", (request_id,)).fetchone() @@ -218,7 +232,7 @@ def execute(self, request_id: str) -> dict: if not self.identity.verify_signature(manifest, body, json.loads(row["signature_json"])): raise PermissionError("invalid recovery approval") result = self.identity.recover_signing_key(req["entity_id"]) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("UPDATE requests SET status='EXECUTED' WHERE request_id=?", (request_id,)) return {"request_id": request_id, "entity_id": req["entity_id"], "status": "EXECUTED", "manifest_revision": result["manifest_revision"], diff --git a/src/31_Profiles/profile_core.py b/src/31_Profiles/profile_core.py index 05842d1f..5377d3d7 100644 --- a/src/31_Profiles/profile_core.py +++ b/src/31_Profiles/profile_core.py @@ -3,6 +3,20 @@ from pathlib import Path from typing import Any import hashlib, json, sqlite3, time +from contextlib import contextmanager + + +@contextmanager +def dbctx(path): + db = sqlite3.connect(path) + try: + yield db + db.commit() + except Exception: + db.rollback() + raise + finally: + db.close() CORE_VERSION = "3.0.0" CORE_PRIMITIVES = ("ENTITY", "AUTHORITY", "RIGHT", "EVENT", "VALUE") @@ -35,7 +49,7 @@ class ProfileRegistry: def __init__(self, root: str | Path): self.path = Path(root) / "entity_v3_profiles.sqlite" self.path.parent.mkdir(parents=True, exist_ok=True) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("""CREATE TABLE IF NOT EXISTS profiles( profile_id TEXT NOT NULL, version TEXT NOT NULL, schema_hash TEXT NOT NULL, dependencies_json TEXT NOT NULL, mandatory INTEGER NOT NULL, @@ -50,7 +64,7 @@ def register(self, d: ProfileDescriptor) -> dict: if len(d.schema_hash) != 64: raise ValueError("schema_hash must be SHA-256") deps = tuple(sorted(set(d.dependencies))) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.row_factory = sqlite3.Row old = db.execute("SELECT * FROM profiles WHERE profile_id=? AND version=?", (d.profile_id, d.version)).fetchone() @@ -87,7 +101,7 @@ def register_schema(self, schema_id: str, version: str, document: Any, if compatibility not in {"IMMUTABLE", "BACKWARD", "FORWARD", "BIDIRECTIONAL"}: raise ValueError("invalid compatibility") digest = sha256(document) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.row_factory = sqlite3.Row old = db.execute("SELECT * FROM schemas WHERE schema_id=? AND version=?", (schema_id, version)).fetchone() @@ -161,7 +175,7 @@ class StandardGovernance: def __init__(self, root: str | Path, identity): self.path = Path(root) / "entity_v3_standard_governance.sqlite" self.identity = identity - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("""CREATE TABLE IF NOT EXISTS rfcs( rfc_id TEXT PRIMARY KEY, proposer TEXT NOT NULL, body_sha256 TEXT NOT NULL, change_class TEXT NOT NULL, threshold INTEGER NOT NULL, @@ -181,7 +195,7 @@ def propose(self, proposer: str, body: Any, change_class="PROFILE", threshold=2) "body_sha256": digest, "change_class": change_class, "threshold": max(1, int(threshold)), "status": "OPEN", "created_at_ms": now_ms()} sig = self.identity.sign(proposer, record) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("INSERT INTO rfcs VALUES(?,?,?,?,?,?,?,?)", ( rfc_id, proposer, digest, change_class, record["threshold"], "OPEN", record["created_at_ms"], json.dumps(sig, sort_keys=True))) @@ -194,7 +208,7 @@ def endorse(self, rfc_id: str, endorser: str, decision="APPROVE") -> dict: record = {"schema": "entity-v3-rfc-endorsement-v1", "rfc_id": rfc_id, "endorser": endorser, "decision": decision, "created_at_ms": now_ms()} sig = self.identity.sign(endorser, record) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.row_factory = sqlite3.Row rfc = db.execute("SELECT * FROM rfcs WHERE rfc_id=? AND status='OPEN'", (rfc_id,)).fetchone() if not rfc: raise KeyError("open RFC not found") diff --git a/src/31_Profiles/resilience_interop.py b/src/31_Profiles/resilience_interop.py index 2b62f3f0..3df883b4 100644 --- a/src/31_Profiles/resilience_interop.py +++ b/src/31_Profiles/resilience_interop.py @@ -2,6 +2,20 @@ from pathlib import Path from typing import Any import hashlib, json, secrets, sqlite3, time +from contextlib import contextmanager + + +@contextmanager +def dbctx(path): + db = sqlite3.connect(path) + try: + yield db + db.commit() + except Exception: + db.rollback() + raise + finally: + db.close() def now_ms(): return int(time.time() * 1000) def canon(v): return json.dumps(v, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=str).encode() @@ -12,7 +26,7 @@ class FederatedResolutionProfile: """Multiple signed resolver observations, quorum selection and split-view detection.""" def __init__(self, root: str | Path, identity): self.path = Path(root) / "entity_v3_federated_resolution.sqlite"; self.identity = identity - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("""CREATE TABLE IF NOT EXISTS views( view_id TEXT PRIMARY KEY, object_id TEXT NOT NULL, resolver TEXT NOT NULL, version INTEGER NOT NULL, epoch INTEGER NOT NULL, resolution_sha256 TEXT NOT NULL, @@ -30,14 +44,14 @@ def observe(self, resolver: str, object_id: str, resolution_record: dict, "object_id": object_id, "resolver": resolver, "version": version, "epoch": int(epoch), "resolution_sha256": digest(resolution_record), "expires_at_ms": now_ms() + max(1, int(ttl_ms)), "created_at_ms": now_ms()} - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: rows = db.execute("SELECT DISTINCT resolution_sha256 FROM views " "WHERE object_id=? AND resolver=? AND version=? AND epoch=?", (object_id, resolver, version, int(epoch))).fetchall() if rows and any(r[0] != body["resolution_sha256"] for r in rows): raise ValueError("resolver equivocation detected") sig = self.identity.sign(resolver, body) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("INSERT INTO views VALUES(?,?,?,?,?,?,?,?,?)", ( body["view_id"], object_id, resolver, version, int(epoch), body["resolution_sha256"], body["expires_at_ms"], body["created_at_ms"], @@ -46,7 +60,7 @@ def observe(self, resolver: str, object_id: str, resolution_record: dict, def resolve_quorum(self, object_id: str, *, minimum_resolvers=2, at_ms=None) -> dict: at = int(at_ms or now_ms()) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.row_factory = sqlite3.Row rows = db.execute("SELECT * FROM views WHERE object_id=? AND expires_at_ms>=? " "ORDER BY version DESC,epoch DESC,created_at_ms DESC", @@ -76,7 +90,7 @@ class AgentDelegationProfile: """Sub-agent authority with depth/capability/budget/time attenuation and kill semantics.""" def __init__(self, root: str | Path, identity): self.path = Path(root) / "entity_v3_agent_delegation.sqlite"; self.identity = identity - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("""CREATE TABLE IF NOT EXISTS grants( grant_id TEXT PRIMARY KEY, principal TEXT NOT NULL, grantor TEXT NOT NULL, grantee TEXT NOT NULL, parent_grant_id TEXT, depth INTEGER NOT NULL, @@ -90,7 +104,7 @@ def grant(self, principal: str, grantor: str, grantee: str, capabilities: list[s parent_grant_id: str | None = None) -> dict: caps = sorted({str(c).upper() for c in capabilities}) depth = 0 - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.row_factory = sqlite3.Row if parent_grant_id: parent = db.execute("SELECT * FROM grants WHERE grant_id=? AND status='ACTIVE'", @@ -113,7 +127,7 @@ def grant(self, principal: str, grantor: str, grantee: str, capabilities: list[s "expires_at_ms": int(expires_at_ms), "policy_sha256": policy_sha256, "status": "ACTIVE", "created_at_ms": now_ms()} sig = self.identity.sign(grantor, body) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("INSERT INTO grants VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", ( body["grant_id"], principal, grantor, grantee, parent_grant_id, depth, int(max_depth), json.dumps(caps), body["budget_units"], 0, @@ -123,7 +137,7 @@ def grant(self, principal: str, grantor: str, grantee: str, capabilities: list[s def consume(self, grant_id: str, capability: str, units=1, *, at_ms=None) -> dict: at, units, capability = int(at_ms or now_ms()), max(0, int(units)), capability.upper() - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.row_factory = sqlite3.Row row = db.execute("SELECT * FROM grants WHERE grant_id=?", (grant_id,)).fetchone() if not row or row["status"] != "ACTIVE": raise PermissionError("inactive grant") @@ -139,7 +153,7 @@ def consume(self, grant_id: str, capability: str, units=1, *, at_ms=None) -> dic "remaining_units": int(row["budget_units"]) - spent} def kill(self, grant_id: str) -> dict: - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: queue, revoked = [grant_id], [] while queue: current = queue.pop(0) @@ -154,7 +168,7 @@ class PhysicalBindingProfile: """Physical↔digital binding with hardware evidence, custody and clone suspicion.""" def __init__(self, root: str | Path, identity): self.path = Path(root) / "entity_v3_physical_binding.sqlite"; self.identity = identity - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("""CREATE TABLE IF NOT EXISTS bindings( binding_id TEXT PRIMARY KEY, object_id TEXT NOT NULL, actor TEXT NOT NULL, hardware_fingerprint TEXT NOT NULL, evidence_sha256 TEXT NOT NULL, @@ -165,7 +179,7 @@ def __init__(self, root: str | Path, identity): created_at_ms INTEGER NOT NULL, signature_json TEXT NOT NULL)""") def bind(self, actor: str, object_id: str, hardware_fingerprint: str, evidence_sha256: str) -> dict: - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: conflict = db.execute("SELECT object_id FROM bindings WHERE hardware_fingerprint=? " "AND status='ACTIVE' AND object_id<>?", (hardware_fingerprint, object_id)).fetchall() @@ -176,7 +190,7 @@ def bind(self, actor: str, object_id: str, hardware_fingerprint: str, evidence_s "object_id": object_id, "actor": actor, "hardware_fingerprint": hardware_fingerprint, "evidence_sha256": evidence_sha256, "status": "ACTIVE", "created_at_ms": now_ms()} sig = self.identity.sign(actor, body) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("INSERT INTO bindings VALUES(?,?,?,?,?,?,?,?)", ( body["binding_id"], object_id, actor, hardware_fingerprint, evidence_sha256, "ACTIVE", body["created_at_ms"], json.dumps(sig, sort_keys=True))) @@ -189,7 +203,7 @@ def custody_transfer(self, actor: str, object_id: str, from_entity: str | None, "evidence_sha256": evidence_sha256, "created_at_ms": now_ms(), "custody_is_not_ownership": True} sig = self.identity.sign(actor, body) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("INSERT INTO custody VALUES(?,?,?,?,?,?,?)", ( body["event_id"], object_id, from_entity, to_entity, evidence_sha256, body["created_at_ms"], json.dumps(sig, sort_keys=True))) diff --git a/src/35_Global_Infrastructure/institutional_semantics.py b/src/35_Global_Infrastructure/institutional_semantics.py index 926aa30b..f94fab19 100644 --- a/src/35_Global_Infrastructure/institutional_semantics.py +++ b/src/35_Global_Infrastructure/institutional_semantics.py @@ -2,6 +2,20 @@ from pathlib import Path from typing import Any import hashlib, json, secrets, sqlite3, time +from contextlib import contextmanager + + +@contextmanager +def dbctx(path): + db = sqlite3.connect(path) + try: + yield db + db.commit() + except Exception: + db.rollback() + raise + finally: + db.close() REGISTRY_KINDS = { "SCHEMA", "RIGHT", "EVENT", "CAPABILITY", "ASSET_CLASS", @@ -35,7 +49,7 @@ def __init__(self, root: str | Path, identity): self.path = Path(root) / "entity_v3_jurisdiction_profiles.sqlite" self.path.parent.mkdir(parents=True, exist_ok=True) self.identity = identity - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("""CREATE TABLE IF NOT EXISTS profiles( profile_id TEXT PRIMARY KEY, jurisdiction_code TEXT NOT NULL, domain TEXT NOT NULL, version TEXT NOT NULL, authority_entity_id TEXT NOT NULL, @@ -85,7 +99,7 @@ def register(self, authority: str, jurisdiction_code: str, domain: str, version: if end is not None and end <= start: raise ValueError("effective_to_ms must follow effective_from_ms") self.identity.load_manifest(authority) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.row_factory = sqlite3.Row if parent_profile_id and not db.execute( "SELECT 1 FROM profiles WHERE profile_id=?", (parent_profile_id,) @@ -114,7 +128,7 @@ def register(self, authority: str, jurisdiction_code: str, domain: str, version: "legal_effect_is_deployment_specific": True, } sig = self.identity.sign(authority, body) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("INSERT INTO profiles VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)", ( profile_id, jurisdiction_code, domain, version, authority, schema_sha256, json.dumps(normalized_rules, sort_keys=True), start, end, int(precedence), @@ -123,7 +137,7 @@ def register(self, authority: str, jurisdiction_code: str, domain: str, version: return dict(body, signature=sig) def supersede(self, actor: str, old_profile_id: str, new_profile_id: str) -> dict: - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.row_factory = sqlite3.Row old = db.execute("SELECT * FROM profiles WHERE profile_id=?", (old_profile_id,)).fetchone() new = db.execute("SELECT * FROM profiles WHERE profile_id=?", (new_profile_id,)).fetchone() @@ -136,7 +150,7 @@ def supersede(self, actor: str, old_profile_id: str, new_profile_id: str) -> dic "actor_entity_id": actor, "created_at_ms": now_ms(), "history_rewrite_prohibited": True} sig = self.identity.sign(actor, body) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("INSERT INTO supersessions VALUES(?,?,?,?,?)", ( old_profile_id, new_profile_id, actor, body["created_at_ms"], json.dumps(sig, sort_keys=True))) db.execute("UPDATE profiles SET status='SUPERSEDED' WHERE profile_id=?", (old_profile_id,)) @@ -153,7 +167,7 @@ def applicable(self, jurisdictions: list[str], domain: str, *, at_ms: int | None "AND status='ACTIVE' AND effective_from_ms<=? " "AND (effective_to_ms IS NULL OR effective_to_ms>=?) " "ORDER BY precedence DESC,jurisdiction_code,version") - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.row_factory = sqlite3.Row rows = db.execute(sql, (*codes, domain, at, at)).fetchall() out = [] @@ -203,7 +217,7 @@ def __init__(self, root: str | Path, identity): self.path = Path(root) / "entity_v3_semantic_registry.sqlite" self.path.parent.mkdir(parents=True, exist_ok=True) self.identity = identity - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("""CREATE TABLE IF NOT EXISTS namespaces( namespace_id TEXT PRIMARY KEY, owner_entity_id TEXT NOT NULL, description TEXT NOT NULL, governance_ref TEXT, @@ -232,7 +246,7 @@ def register_namespace(self, owner: str, namespace_id: str, description: str, "owner_entity_id": owner, "description": str(description).strip(), "governance_ref": governance_ref, "created_at_ms": now_ms()} sig = self.identity.sign(owner, body) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: old = db.execute("SELECT owner_entity_id FROM namespaces WHERE namespace_id=?", (namespace_id,)).fetchone() if old: @@ -252,7 +266,7 @@ def register_term(self, owner: str, namespace_id: str, kind: str, term_id: str, term_id, version = str(term_id).strip(), str(version).strip() if not term_id or not version: raise ValueError("term_id and version required") - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: ns = db.execute("SELECT owner_entity_id FROM namespaces WHERE namespace_id=?", (namespace_id,)).fetchone() if not ns: @@ -273,7 +287,7 @@ def register_term(self, owner: str, namespace_id: str, kind: str, term_id: str, "status": "ACTIVE", "supersedes_ref": supersedes_ref, "created_at_ms": now_ms()} sig = self.identity.sign(owner, body) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("INSERT INTO terms VALUES(?,?,?,?,?,?,?,?,?,?)", ( namespace_id, kind, term_id, version, definition_hash, json.dumps(definition, sort_keys=True), "ACTIVE", supersedes_ref, @@ -289,7 +303,7 @@ def resolve(self, term_ref: str) -> dict: namespace_id, kind, term_id = head.split(":", 2) except ValueError as exc: raise ValueError("invalid semantic term reference") from exc - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.row_factory = sqlite3.Row row = db.execute("SELECT * FROM terms WHERE namespace_id=? AND kind=? AND term_id=? AND version=?", (namespace_id.lower(), kind.upper(), term_id, version)).fetchone() @@ -320,7 +334,7 @@ def map_terms(self, actor: str, source_ref: str, target_ref: str, relation: str, "mapping_is_attestation_not_identity": True, "silent_semantic_coercion_prohibited": True} sig = self.identity.sign(actor, body) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("INSERT INTO crosswalks VALUES(?,?,?,?,?,?,?,?,?,?)", ( body["crosswalk_id"], actor, source_ref, target_ref, relation, evidence_sha256, json.dumps(body["jurisdiction_scope"]), confidence_bps, @@ -328,7 +342,7 @@ def map_terms(self, actor: str, source_ref: str, target_ref: str, relation: str, return dict(body, signature=sig) def mappings(self, source_ref: str, *, target_namespace: str | None = None) -> dict: - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.row_factory = sqlite3.Row rows = db.execute("SELECT * FROM crosswalks WHERE source_ref=? ORDER BY created_at_ms,crosswalk_id", (source_ref,)).fetchall() @@ -352,7 +366,7 @@ def __init__(self, root: str | Path, identity): self.path = Path(root) / "entity_v3_multistakeholder_governance.sqlite" self.path.parent.mkdir(parents=True, exist_ok=True) self.identity = identity - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("""CREATE TABLE IF NOT EXISTS bodies( body_id TEXT PRIMARY KEY, steward_entity_id TEXT NOT NULL, name TEXT NOT NULL, charter_sha256 TEXT NOT NULL, classes_json TEXT NOT NULL, @@ -394,7 +408,7 @@ def create_body(self, steward: str, name: str, charter_sha256: str, "min_approval_classes": min_approval_classes, "status": "ACTIVE", "created_at_ms": now_ms(), "single_implementation_is_not_standard_authority": True} sig = self.identity.sign(steward, body) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("INSERT INTO bodies VALUES(?,?,?,?,?,?,?,?,?,?)", ( body_id, steward, str(name), charter_sha256, json.dumps(classes), approval_threshold, min_approval_classes, "ACTIVE", body["created_at_ms"], @@ -403,7 +417,7 @@ def create_body(self, steward: str, name: str, charter_sha256: str, def add_member(self, body_id: str, steward: str, member: str, stakeholder_class: str) -> dict: stakeholder_class = stakeholder_class.upper() - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.row_factory = sqlite3.Row body = db.execute("SELECT * FROM bodies WHERE body_id=? AND status='ACTIVE'", (body_id,)).fetchone() if not body: @@ -417,7 +431,7 @@ def add_member(self, body_id: str, steward: str, member: str, stakeholder_class: "member_entity_id": member, "stakeholder_class": stakeholder_class, "status": "ACTIVE", "admitted_at_ms": now_ms()} sig = self.identity.sign(steward, record) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("INSERT OR REPLACE INTO members VALUES(?,?,?,?,?,?)", ( body_id, member, stakeholder_class, "ACTIVE", record["admitted_at_ms"], json.dumps(sig, sort_keys=True))) @@ -428,7 +442,7 @@ def propose(self, body_id: str, proposer: str, change_class: str, change_class = change_class.upper() if change_class not in {"CORE", "PROFILE", "ONTOLOGY", "SCHEMA", "TEST", "GOVERNANCE"}: raise ValueError("unsupported change class") - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: member = db.execute("SELECT 1 FROM members WHERE body_id=? AND member_entity_id=? AND status='ACTIVE'", (body_id, proposer)).fetchone() if not member: @@ -442,7 +456,7 @@ def propose(self, body_id: str, proposer: str, change_class: str, "target_ref": str(target_ref), "body_sha256": body_hash, "status": "OPEN", "created_at_ms": now_ms()} sig = self.identity.sign(proposer, record) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("INSERT INTO proposals VALUES(?,?,?,?,?,?,?,?,?)", ( proposal_id, body_id, proposer, change_class, str(target_ref), body_hash, "OPEN", record["created_at_ms"], json.dumps(sig, sort_keys=True))) @@ -453,7 +467,7 @@ def declare_conflict(self, proposal_id: str, member: str, basis: Any, *, recuse: "member_entity_id": member, "recuse": bool(recuse), "basis_sha256": digest(basis), "created_at_ms": now_ms()} sig = self.identity.sign(member, body) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: if not db.execute("SELECT 1 FROM proposals WHERE proposal_id=?", (proposal_id,)).fetchone(): raise KeyError("proposal missing") db.execute("INSERT OR REPLACE INTO conflicts VALUES(?,?,?,?,?,?)", ( @@ -465,7 +479,7 @@ def vote(self, proposal_id: str, voter: str, decision: str) -> dict: decision = decision.upper() if decision not in {"APPROVE", "REJECT", "ABSTAIN"}: raise ValueError("invalid governance decision") - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.row_factory = sqlite3.Row proposal = db.execute("SELECT * FROM proposals WHERE proposal_id=? AND status='OPEN'", (proposal_id,)).fetchone() if not proposal: @@ -482,7 +496,7 @@ def vote(self, proposal_id: str, voter: str, decision: str) -> dict: "voter_entity_id": voter, "stakeholder_class": member["stakeholder_class"], "decision": decision, "created_at_ms": now_ms()} sig = self.identity.sign(voter, body) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("INSERT OR REPLACE INTO ballots VALUES(?,?,?,?,?,?)", ( proposal_id, voter, member["stakeholder_class"], decision, body["created_at_ms"], json.dumps(sig, sort_keys=True))) @@ -490,7 +504,7 @@ def vote(self, proposal_id: str, voter: str, decision: str) -> dict: return dict(body, signature=sig, proposal_status=result["status"]) def tally(self, proposal_id: str) -> dict: - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.row_factory = sqlite3.Row proposal = db.execute("SELECT * FROM proposals WHERE proposal_id=?", (proposal_id,)).fetchone() if not proposal: @@ -508,7 +522,7 @@ def tally(self, proposal_id: str) -> dict: status = "REJECTED" else: status = "OPEN" - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("UPDATE proposals SET status=? WHERE proposal_id=?", (status, proposal_id)) return { "proposal_id": proposal_id, "status": status, diff --git a/src/35_Global_Infrastructure/privacy_provenance.py b/src/35_Global_Infrastructure/privacy_provenance.py index 4acec0eb..c2604737 100644 --- a/src/35_Global_Infrastructure/privacy_provenance.py +++ b/src/35_Global_Infrastructure/privacy_provenance.py @@ -3,6 +3,20 @@ from typing import Any, Callable import base64, hashlib, json, os, secrets, sqlite3, time from cryptography.hazmat.primitives.ciphers.aead import AESGCM +from contextlib import contextmanager + + +@contextmanager +def dbctx(path): + db = sqlite3.connect(path) + try: + yield db + db.commit() + except Exception: + db.rollback() + raise + finally: + db.close() def now_ms() -> int: return int(time.time() * 1000) @@ -35,7 +49,7 @@ def __init__(self, root: str | Path, identity): self.path = Path(root) / "entity_v3_purpose_access.sqlite" self.path.parent.mkdir(parents=True, exist_ok=True) self.identity = identity - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("""CREATE TABLE IF NOT EXISTS grants( grant_id TEXT PRIMARY KEY, controller TEXT NOT NULL, grantee TEXT NOT NULL, resource_ref TEXT NOT NULL, purposes_json TEXT NOT NULL, actions_json TEXT NOT NULL, @@ -61,7 +75,7 @@ def grant(self, controller: str, grantee: str, resource_ref: str, "purposes": purposes, "actions": actions, "max_uses": max(0, int(max_uses)), "expires_at_ms": int(expires_at_ms), "status": "ACTIVE", "created_at_ms": now_ms()} sig = self.identity.sign(controller, body) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("INSERT INTO grants VALUES(?,?,?,?,?,?,?,?,?,?,?,?)", ( body["grant_id"], controller, grantee, str(resource_ref), json.dumps(purposes), json.dumps(actions), body["max_uses"], 0, @@ -70,7 +84,7 @@ def grant(self, controller: str, grantee: str, resource_ref: str, return dict(body, signature=sig) def revoke(self, controller: str, grant_id: str) -> dict: - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.row_factory = sqlite3.Row row = db.execute("SELECT * FROM grants WHERE grant_id=?", (grant_id,)).fetchone() if not row: @@ -82,7 +96,7 @@ def revoke(self, controller: str, grant_id: str) -> dict: body = {"schema": "entity-v3-purpose-bound-revocation-v1", "grant_id": grant_id, "controller": controller, "status": "REVOKED", "created_at_ms": now_ms()} sig = self.identity.sign(controller, body) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("UPDATE grants SET status='REVOKED' WHERE grant_id=?", (grant_id,)) return dict(body, signature=sig, already_revoked=False) @@ -91,7 +105,7 @@ def authorize_use(self, grant_id: str, grantee: str, purpose: str, action: str, at = int(at_ms or now_ms()) purpose, action = purpose.upper(), action.upper() evidence_sha256 = sha256_hex(evidence_sha256) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.row_factory = sqlite3.Row db.execute("BEGIN IMMEDIATE") row = db.execute("SELECT * FROM grants WHERE grant_id=?", (grant_id,)).fetchone() @@ -128,7 +142,7 @@ def __init__(self, root: str | Path, identity): self.path = Path(root) / "entity_v3_retention.sqlite" self.path.parent.mkdir(parents=True, exist_ok=True) self.identity = identity - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("""CREATE TABLE IF NOT EXISTS records( record_id TEXT PRIMARY KEY, controller TEXT NOT NULL, subject_ref TEXT NOT NULL, payload_sha256 TEXT NOT NULL, storage_ref_sha256 TEXT, @@ -154,7 +168,7 @@ def register(self, controller: str, subject_ref: str, payload_sha256: str, *, "status": "ACTIVE", "created_at_ms": now_ms(), "raw_payload_stored_in_ledger": False} sig = self.identity.sign(controller, body) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("INSERT INTO records VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)", ( body["record_id"], controller, str(subject_ref), payload_sha256, storage_hash, body["purpose"], body["jurisdiction"], body["retain_until_ms"], mode, @@ -165,7 +179,7 @@ def destroy(self, controller: str, record_id: str, destruction_evidence_sha256: *, at_ms: int | None = None) -> dict: destruction_evidence_sha256 = sha256_hex(destruction_evidence_sha256) at = int(at_ms or now_ms()) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.row_factory = sqlite3.Row row = db.execute("SELECT * FROM records WHERE record_id=?", (record_id,)).fetchone() if not row: @@ -184,13 +198,13 @@ def destroy(self, controller: str, record_id: str, destruction_evidence_sha256: "destruction_evidence_sha256": destruction_evidence_sha256, "destroyed_at_ms": at, "commitment_preserved": True} sig = self.identity.sign(controller, body) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("UPDATE records SET status='DESTROYED', destruction_evidence_sha256=?, destroyed_at_ms=? WHERE record_id=?", (destruction_evidence_sha256, at, record_id)) return dict(body, signature=sig, status="DESTROYED", already_destroyed=False) def status(self, record_id: str) -> dict: - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.row_factory = sqlite3.Row row = db.execute("SELECT * FROM records WHERE record_id=?", (record_id,)).fetchone() if not row: @@ -205,7 +219,7 @@ def __init__(self, root: str | Path, identity): self.path = Path(root) / "entity_v3_confidential_provenance.sqlite" self.path.parent.mkdir(parents=True, exist_ok=True) self.identity = identity - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("""CREATE TABLE IF NOT EXISTS edges( edge_id TEXT PRIMARY KEY, actor TEXT NOT NULL, parent_ref TEXT NOT NULL, child_ref TEXT NOT NULL, @@ -236,7 +250,7 @@ def add_edge(self, actor: str, parent_ref: str, child_ref: str, relationship: st "metadata_commitment_sha256": commitment, "encrypted_metadata": encrypted, "created_at_ms": now_ms(), "confidential_metadata_not_public_provenance": True} sig = self.identity.sign(actor, body) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("INSERT INTO edges VALUES(?,?,?,?,?,?,?,?,?,?)", ( body["edge_id"], actor, str(parent_ref), str(child_ref), body["relationship"], evidence_sha256, commitment, @@ -245,7 +259,7 @@ def add_edge(self, actor: str, parent_ref: str, child_ref: str, relationship: st return dict(body, signature=sig) def reveal_metadata(self, edge_id: str, encryption_key: bytes) -> dict: - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.row_factory = sqlite3.Row row = db.execute("SELECT * FROM edges WHERE edge_id=?", (edge_id,)).fetchone() if not row: @@ -270,7 +284,7 @@ def __init__(self, root: str | Path, identity): self.path.parent.mkdir(parents=True, exist_ok=True) self.identity = identity self._callbacks: dict[str, Callable[[bytes, dict], bool]] = {} - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("""CREATE TABLE IF NOT EXISTS suites( suite_id TEXT PRIMARY KEY, governance_entity_id TEXT NOT NULL, algorithm TEXT NOT NULL, verifier_sha256 TEXT NOT NULL, @@ -294,7 +308,7 @@ def register_suite(self, governance_entity: str, suite_id: str, algorithm: str, "status": "ACTIVE", "created_at_ms": now_ms(), "registration_does_not_certify_cryptographic_security": True} sig = self.identity.sign(governance_entity, body) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: old = db.execute("SELECT verifier_sha256 FROM suites WHERE suite_id=?", (suite_id,)).fetchone() if old and old[0] != verifier_sha256: raise ValueError("proof suite verifier changed without new suite id") @@ -307,7 +321,7 @@ def register_suite(self, governance_entity: str, suite_id: str, algorithm: str, def bind_runtime_verifier(self, suite_id: str, verifier_sha256: str, callback: Callable[[bytes, dict], bool]) -> None: suite_id = suite_id.upper(); verifier_sha256 = sha256_hex(verifier_sha256) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: row = db.execute("SELECT verifier_sha256,status FROM suites WHERE suite_id=?", (suite_id,)).fetchone() if not row or row[1] != "ACTIVE": raise KeyError("active proof suite missing") @@ -318,7 +332,7 @@ def bind_runtime_verifier(self, suite_id: str, verifier_sha256: str, def verify(self, suite_id: str, verifier_entity: str, proof: bytes, public_inputs: dict) -> dict: suite_id = suite_id.upper() - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: row = db.execute("SELECT status FROM suites WHERE suite_id=?", (suite_id,)).fetchone() if not row or row[0] != "ACTIVE": raise PermissionError("proof suite is not active") @@ -334,7 +348,7 @@ def verify(self, suite_id: str, verifier_entity: str, proof: bytes, "created_at_ms": now_ms(), "proof_acceptance_is_suite_specific_not_universal_truth": True} sig = self.identity.sign(verifier_entity, body) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("INSERT INTO receipts VALUES(?,?,?,?,?,?,?,?)", ( body["receipt_id"], suite_id, verifier_entity, body["proof_sha256"], body["public_inputs_sha256"], int(accepted), body["created_at_ms"], diff --git a/src/35_Global_Infrastructure/topology_crypto.py b/src/35_Global_Infrastructure/topology_crypto.py index df66f886..6c26e629 100644 --- a/src/35_Global_Infrastructure/topology_crypto.py +++ b/src/35_Global_Infrastructure/topology_crypto.py @@ -2,6 +2,20 @@ from pathlib import Path from typing import Any, Callable import hashlib, json, secrets, sqlite3, time +from contextlib import contextmanager + + +@contextmanager +def dbctx(path): + db = sqlite3.connect(path) + try: + yield db + db.commit() + except Exception: + db.rollback() + raise + finally: + db.close() TOPOLOGY_CLASSES = {"CORE", "REGIONAL", "EDGE", "SATELLITE", "OFFLINE"} @@ -36,7 +50,7 @@ def __init__(self, root: str | Path, identity): self.path = Path(root) / "entity_v3_topology.sqlite" self.path.parent.mkdir(parents=True, exist_ok=True) self.identity = identity - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("""CREATE TABLE IF NOT EXISTS nodes( node_id TEXT PRIMARY KEY, operator_entity_id TEXT NOT NULL, topology_class TEXT NOT NULL, jurisdiction TEXT NOT NULL, @@ -58,7 +72,7 @@ def register_node(self, operator: str, node_id: str, topology_class: str, "capabilities": caps, "status": "ACTIVE", "created_at_ms": now_ms(), "infrastructure_membership_is_not_sovereign_authority": True} sig = self.identity.sign(operator, body) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: old = db.execute("SELECT operator_entity_id,topology_class,jurisdiction,trust_domain,capabilities_json FROM nodes WHERE node_id=?", (node_id,)).fetchone() if old: @@ -78,7 +92,7 @@ def __init__(self, root: str | Path, identity): self.path = Path(root) / "entity_v3_partition_sync.sqlite" self.path.parent.mkdir(parents=True, exist_ok=True) self.identity = identity - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("""CREATE TABLE IF NOT EXISTS checkpoints( checkpoint_id TEXT PRIMARY KEY, node_id TEXT NOT NULL, operator_entity_id TEXT NOT NULL, partition_id TEXT NOT NULL, @@ -109,7 +123,7 @@ def publish(self, node_id: str, operator: str, partition_id: str, *, raise ValueError("invalid checkpoint sequence/epoch") if clock.get(node_id) != sequence: raise ValueError("node vector-clock component must equal checkpoint sequence") - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.row_factory = sqlite3.Row last = db.execute("SELECT * FROM checkpoints WHERE node_id=? AND partition_id=? ORDER BY sequence DESC LIMIT 1", (node_id, partition_id)).fetchone() @@ -128,7 +142,7 @@ def publish(self, node_id: str, operator: str, partition_id: str, *, "created_at_ms": now_ms()} checkpoint_hash = digest(body) sig = self.identity.sign(operator, body) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("INSERT INTO checkpoints VALUES(?,?,?,?,?,?,?,?,?,?,?,?)", ( body["checkpoint_id"], node_id, operator, partition_id, sequence, epoch, previous_checkpoint_sha256, state_root_sha256, json.dumps(clock, sort_keys=True), @@ -136,7 +150,7 @@ def publish(self, node_id: str, operator: str, partition_id: str, *, return dict(body, checkpoint_sha256=checkpoint_hash, signature=sig) def _latest(self, partition_id: str) -> list[dict]: - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.row_factory = sqlite3.Row rows = db.execute("""SELECT c.* FROM checkpoints c JOIN ( SELECT node_id,partition_id,MAX(sequence) AS max_seq FROM checkpoints @@ -173,7 +187,7 @@ def merge(self, partition_id: str) -> dict: "checkpoint_id": chosen["checkpoint_id"], "partition_conflict": False} conflict_ids = sorted(x["checkpoint_id"] for x in latest) conflict_id = "partitionconflict3-" + digest({"partition": partition_id, "ids": conflict_ids})[:24] - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("INSERT OR IGNORE INTO conflicts VALUES(?,?,?,?,?)", ( conflict_id, partition_id, json.dumps(conflict_ids), "CONCURRENT_DIVERGENT_STATE", now_ms())) return {"partition_id": partition_id, "resolved": False, @@ -221,7 +235,7 @@ def __init__(self, root: str | Path, identity): self.path.parent.mkdir(parents=True, exist_ok=True) self.identity = identity self._verifiers: dict[str, Callable[[bytes, Any], bool]] = {} - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("""CREATE TABLE IF NOT EXISTS suites( suite_id TEXT PRIMARY KEY, governance_entity_id TEXT NOT NULL, algorithm TEXT NOT NULL, security_bits INTEGER NOT NULL, @@ -254,7 +268,7 @@ def register_suite(self, governance_entity: str, suite_id: str, algorithm: str, "not_before_ms": start, "deprecate_at_ms": dep, "retire_at_ms": ret, "status": "ACTIVE", "created_at_ms": now_ms()} sig = self.identity.sign(governance_entity, body) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: old = db.execute("SELECT algorithm,security_bits,verifier_sha256,not_before_ms,deprecate_at_ms,retire_at_ms FROM suites WHERE suite_id=?", (suite_id,)).fetchone() expected = (str(algorithm), security_bits, verifier_sha256, start, dep, ret) @@ -270,7 +284,7 @@ def register_suite(self, governance_entity: str, suite_id: str, algorithm: str, def bind_verifier(self, suite_id: str, verifier_sha256: str, callback: Callable[[bytes, Any], bool]) -> None: suite_id = suite_id.upper(); verifier_sha256 = sha256_hex(verifier_sha256) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: row = db.execute("SELECT verifier_sha256 FROM suites WHERE suite_id=?", (suite_id,)).fetchone() if not row or row[0] != verifier_sha256: raise PermissionError("crypto verifier hash mismatch") @@ -281,7 +295,7 @@ def register_transition(self, governance_entity: str, old_suite_id: str, new_sui old_suite_id, new_suite_id = old_suite_id.upper(), new_suite_id.upper() if old_suite_id == new_suite_id: raise ValueError("crypto transition requires distinct suites") - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: rows = db.execute("SELECT suite_id FROM suites WHERE suite_id IN (?,?)", (old_suite_id, new_suite_id)).fetchall() if {r[0] for r in rows} != {old_suite_id, new_suite_id}: @@ -297,7 +311,7 @@ def register_transition(self, governance_entity: str, old_suite_id: str, new_sui "old_retire_at_ms": retire, "created_at_ms": now_ms(), "downgrade_after_transition_prohibited": True} sig = self.identity.sign(governance_entity, body) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("INSERT OR REPLACE INTO transitions VALUES(?,?,?,?,?,?,?,?)", ( transition_id, governance_entity, old_suite_id, new_suite_id, start, retire, body["created_at_ms"], json.dumps(sig, sort_keys=True))) @@ -305,7 +319,7 @@ def register_transition(self, governance_entity: str, old_suite_id: str, new_sui def suite_state(self, suite_id: str, *, at_ms: int | None = None) -> str: at = int(at_ms or now_ms()); suite_id = suite_id.upper() - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: row = db.execute("SELECT not_before_ms,deprecate_at_ms,retire_at_ms FROM suites WHERE suite_id=?", (suite_id,)).fetchone() if not row: @@ -321,7 +335,7 @@ def suite_state(self, suite_id: str, *, at_ms: int | None = None) -> str: def required_suites(self, old_suite_id: str, new_suite_id: str, *, at_ms: int) -> list[str]: old_suite_id, new_suite_id = old_suite_id.upper(), new_suite_id.upper() - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: row = db.execute("SELECT dual_sign_from_ms,old_retire_at_ms FROM transitions WHERE old_suite_id=? AND new_suite_id=? ORDER BY created_at_ms DESC LIMIT 1", (old_suite_id, new_suite_id)).fetchone() if not row: diff --git a/src/36_Adoption_Layer/rights_passport.py b/src/36_Adoption_Layer/rights_passport.py index 8f2e5456..bf3bc06d 100644 --- a/src/36_Adoption_Layer/rights_passport.py +++ b/src/36_Adoption_Layer/rights_passport.py @@ -2,6 +2,20 @@ from pathlib import Path from typing import Any import hashlib, json, secrets, sqlite3, time +from contextlib import contextmanager + + +@contextmanager +def dbctx(path): + db = sqlite3.connect(path) + try: + yield db + db.commit() + except Exception: + db.rollback() + raise + finally: + db.close() EFFECTS = {"ALLOW", "REQUIRE", "PROHIBIT"} PRIVACY_PROFILES = { @@ -66,7 +80,7 @@ def __init__(self, root: str | Path, identity, fabric=None): self.path.parent.mkdir(parents=True, exist_ok=True) self.identity = identity self.fabric = fabric - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("""CREATE TABLE IF NOT EXISTS passports( passport_id TEXT PRIMARY KEY, object_id TEXT NOT NULL, controller_entity_id TEXT NOT NULL, version TEXT NOT NULL, passport_sha256 TEXT NOT NULL, body_json TEXT NOT NULL, @@ -132,7 +146,7 @@ def issue(self, controller: str, object_id: str, rights: list[dict], *, passport_hash = digest(body) sig = self.identity.sign(controller, body) try: - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("INSERT INTO passports VALUES(?,?,?,?,?,?,?,?,?)", ( body["passport_id"], body["object_id"], controller, body["version"], passport_hash, json.dumps(body, sort_keys=True), "ACTIVE", body["created_at_ms"], @@ -142,7 +156,7 @@ def issue(self, controller: str, object_id: str, rights: list[dict], *, return dict(body, passport_sha256=passport_hash, signature=sig) def get(self, passport_id: str) -> dict: - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.row_factory = sqlite3.Row row = db.execute("SELECT * FROM passports WHERE passport_id=?", (passport_id,)).fetchone() if not row: @@ -188,7 +202,7 @@ def supersede(self, actor: str, old_passport_id: str, new_passport_id: str) -> d "actor_entity_id": actor, "created_at_ms": now_ms(), "history_rewrite_prohibited": True} sig = self.identity.sign(actor, body) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("INSERT INTO supersessions VALUES(?,?,?,?,?)", ( old_passport_id, new_passport_id, actor, body["created_at_ms"], json.dumps(sig, sort_keys=True))) diff --git a/src/37_Verifiable_Reality/evidence_objects.py b/src/37_Verifiable_Reality/evidence_objects.py index 017caecb..9cf372cd 100644 --- a/src/37_Verifiable_Reality/evidence_objects.py +++ b/src/37_Verifiable_Reality/evidence_objects.py @@ -4,6 +4,20 @@ import hashlib, json, secrets, sqlite3, time from reality_profile import CLAIM_STATES, EVIDENCE_TYPES +from contextlib import contextmanager + + +@contextmanager +def dbctx(path): + db = sqlite3.connect(path) + try: + yield db + db.commit() + except Exception: + db.rollback() + raise + finally: + db.close() def now_ms() -> int: return int(time.time() * 1000) @@ -42,7 +56,7 @@ def __init__(self, root: str | Path, identity): self.path = Path(root) / "entity_v3_3_evidence.sqlite" self.path.parent.mkdir(parents=True, exist_ok=True) self.identity = identity - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("""CREATE TABLE IF NOT EXISTS evidence( evidence_id TEXT PRIMARY KEY, source_entity_id TEXT NOT NULL, evidence_type TEXT NOT NULL, subject_ref TEXT NOT NULL, content_sha256 TEXT NOT NULL, body_sha256 TEXT NOT NULL, @@ -82,7 +96,7 @@ def issue_evidence(self, source_entity_id: str, evidence_type: str, subject_ref: } body_sha = digest(body) sig = self.identity.sign(source_entity_id, body) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("INSERT INTO evidence VALUES(?,?,?,?,?,?,?,?,?)", ( body["evidence_id"], source_entity_id, evidence_type, body["subject_ref"], body["content_sha256"], body_sha, json.dumps(body, sort_keys=True), @@ -139,7 +153,7 @@ def issue_claim(self, issuer_entity_id: str, subject_ref: str, predicate: str, v } body_sha = digest(body) sig = self.identity.sign(issuer_entity_id, body) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("INSERT INTO claims VALUES(?,?,?,?,?,?,?,?,?,?)", ( body["claim_id"], issuer_entity_id, body["subject_ref"], body["predicate"], body["value_sha256"], state, body_sha, json.dumps(body, sort_keys=True), @@ -147,7 +161,7 @@ def issue_claim(self, issuer_entity_id: str, subject_ref: str, predicate: str, v return dict(body, body_sha256=body_sha, signature=sig) def get_claim(self, claim_id: str) -> dict: - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.row_factory = sqlite3.Row row = db.execute("SELECT * FROM claims WHERE claim_id=?", (claim_id,)).fetchone() if not row: @@ -181,7 +195,7 @@ def transition_claim(self, actor_entity_id: str, claim_id: str, to_state: str, r } body_sha = digest(body) sig = self.identity.sign(actor_entity_id, body) - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("INSERT INTO claim_transitions VALUES(?,?,?,?,?,?,?,?,?,?,?)", ( body["transition_id"], claim_id, actor_entity_id, from_state, to_state, body["reason"], json.dumps(body["evidence_refs"]), body_sha, json.dumps(body, sort_keys=True), @@ -190,7 +204,7 @@ def transition_claim(self, actor_entity_id: str, claim_id: str, to_state: str, r return dict(body, body_sha256=body_sha, signature=sig) def claim_history(self, claim_id: str) -> list[dict]: - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.row_factory = sqlite3.Row rows = db.execute("SELECT body_json,body_sha256,signature_json FROM claim_transitions WHERE claim_id=? ORDER BY created_at_ms,transition_id", (claim_id,)).fetchall() return [dict(json.loads(r["body_json"]), body_sha256=r["body_sha256"], diff --git a/src/38_Global_Passports/global_passport.py b/src/38_Global_Passports/global_passport.py index ba431be0..ce4d7375 100644 --- a/src/38_Global_Passports/global_passport.py +++ b/src/38_Global_Passports/global_passport.py @@ -2,6 +2,20 @@ from pathlib import Path from typing import Any import hashlib, json, secrets, sqlite3, time +from contextlib import contextmanager + + +@contextmanager +def dbctx(path): + db = sqlite3.connect(path) + try: + yield db + db.commit() + except Exception: + db.rollback() + raise + finally: + db.close() CORE_PRIMITIVES=("ENTITY","AUTHORITY","RIGHT","EVENT","VALUE") def now_ms()->int: return int(time.time()*1000) @@ -15,7 +29,7 @@ def __init__(self,root:str|Path,identity,fabric,rights_passports,profile_registr self.path=Path(root)/"entity_v3_4_global_passports.sqlite"; self.path.parent.mkdir(parents=True,exist_ok=True) self.identity=identity; self.fabric=fabric; self.rights=rights_passports; self.profiles=profile_registry; self.origin=origin_registry self.required_release_ref=str(required_release_ref) if required_release_ref else None - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("""CREATE TABLE IF NOT EXISTS global_passports( passport_id TEXT PRIMARY KEY, object_id TEXT NOT NULL, controller_entity_id TEXT NOT NULL, version TEXT NOT NULL, body_sha256 TEXT NOT NULL, body_json TEXT NOT NULL, @@ -69,12 +83,12 @@ def issue(self,controller_entity_id:str,object_id:str,rights_passport_id:str,pro if btdu is not None: body["btdu_binding"]=btdu body_sha=digest(body); sig=self.identity.sign(controller_entity_id,body) try: - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("INSERT INTO global_passports VALUES(?,?,?,?,?,?,?,?)",(body["passport_id"],object_id,controller_entity_id,body["version"],body_sha,json.dumps(body,sort_keys=True),json.dumps(sig,sort_keys=True),body["created_at_ms"])) except sqlite3.IntegrityError as exc: raise ValueError("immutable global passport version already exists") from exc return dict(body,body_sha256=body_sha,signature=sig) def get(self,passport_id:str)->dict: - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.row_factory=sqlite3.Row; row=db.execute("SELECT * FROM global_passports WHERE passport_id=?",(str(passport_id),)).fetchone() if not row: raise KeyError("global passport missing") body=json.loads(row["body_json"]) diff --git a/src/38_Global_Passports/profile_registry.py b/src/38_Global_Passports/profile_registry.py index 67c35320..cdd03c40 100644 --- a/src/38_Global_Passports/profile_registry.py +++ b/src/38_Global_Passports/profile_registry.py @@ -2,6 +2,20 @@ from pathlib import Path from typing import Any import hashlib, json, secrets, sqlite3, time +from contextlib import contextmanager + + +@contextmanager +def dbctx(path): + db = sqlite3.connect(path) + try: + yield db + db.commit() + except Exception: + db.rollback() + raise + finally: + db.close() PROFILE_KINDS={"GLOBAL","JURISDICTION","INDUSTRY","DOMAIN","PRIVACY","TRUST","DISCLOSURE"} CONFLICT_POLICIES={"FAIL_CLOSED","MOST_RESTRICTIVE"} @@ -19,7 +33,7 @@ class GlobalProfileRegistry: """Versioned composable profiles. Profiles constrain interpretation; they do not create sovereign authority.""" def __init__(self,root:str|Path,identity): self.path=Path(root)/"entity_v3_4_global_profiles.sqlite"; self.path.parent.mkdir(parents=True,exist_ok=True); self.identity=identity - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("""CREATE TABLE IF NOT EXISTS profiles( profile_ref TEXT PRIMARY KEY, profile_id TEXT NOT NULL, version TEXT NOT NULL, kind TEXT NOT NULL, body_sha256 TEXT NOT NULL, body_json TEXT NOT NULL, issuer_entity_id TEXT NOT NULL, @@ -65,7 +79,7 @@ def register(self,issuer_entity_id:str,profile_id:str,version:str,kind:str,*, "standards_mapping_is_not_normative_equivalence":True,"created_at_ms":now_ms()} body_sha=digest(body); sig=self.identity.sign(issuer_entity_id,body) try: - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("INSERT INTO profiles VALUES(?,?,?,?,?,?,?,?,?)",(ref,body["profile_id"],body["version"],kind,body_sha,json.dumps(body,sort_keys=True),issuer_entity_id,json.dumps(sig,sort_keys=True),body["created_at_ms"])) db.execute("INSERT INTO profile_variants VALUES(?,?,?,?,?,?,?,?,?,1)",(ref,body_sha,body["profile_id"],body["version"],kind,json.dumps(body,sort_keys=True),issuer_entity_id,json.dumps(sig,sort_keys=True),body["created_at_ms"])) except sqlite3.IntegrityError as exc: raise ValueError("immutable profile version already exists") from exc @@ -74,7 +88,7 @@ def import_signed(self,profile:dict,*,allow_semantic_rebind:bool=False)->dict: record=dict(profile or {}); check=self.verify(record) if not check.get("valid"): raise ValueError("invalid signed profile: "+str(check.get("reason","unknown"))) body=self._body(record); ref=body["profile_ref"] - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.row_factory=sqlite3.Row; prior=db.execute("SELECT * FROM profiles WHERE profile_ref=?",(ref,)).fetchone() if prior: old=self._row_record(prior) @@ -90,14 +104,14 @@ def import_signed(self,profile:dict,*,allow_semantic_rebind:bool=False)->dict: return self.get(ref) def get(self,profile_ref:str,body_sha256:str|None=None)->dict: - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.row_factory=sqlite3.Row row=(db.execute("SELECT * FROM profiles WHERE profile_ref=?",(str(profile_ref),)).fetchone() if body_sha256 is None else db.execute("SELECT * FROM profile_variants WHERE profile_ref=? AND body_sha256=?",(str(profile_ref),str(body_sha256))).fetchone()) if not row: raise KeyError("profile missing") return self._row_record(row) def list_variants(self,profile_ref:str)->list[dict]: - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.row_factory=sqlite3.Row; rows=db.execute("SELECT * FROM profile_variants WHERE profile_ref=? ORDER BY created_at_ms,body_sha256",(str(profile_ref),)).fetchall() return [self._row_record(row) for row in rows] diff --git a/src/38_Global_Passports/protocol_origin.py b/src/38_Global_Passports/protocol_origin.py index a60f4654..1d8cb711 100644 --- a/src/38_Global_Passports/protocol_origin.py +++ b/src/38_Global_Passports/protocol_origin.py @@ -8,6 +8,20 @@ from pathlib import Path from typing import Any import hashlib, json, re, sqlite3 +from contextlib import contextmanager + + +@contextmanager +def dbctx(path): + db = sqlite3.connect(path) + try: + yield db + db.commit() + except Exception: + db.rollback() + raise + finally: + db.close() SHA1_RE=re.compile(r"^[0-9a-f]{40}$") @@ -24,7 +38,7 @@ def __init__(self,root:str|Path,identity): self.path.parent.mkdir(parents=True,exist_ok=True) self.identity=identity self.default_release_ref=None - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.execute("""CREATE TABLE IF NOT EXISTS origin_chains( lineage_id TEXT PRIMARY KEY, body_sha256 TEXT NOT NULL, body_json TEXT NOT NULL, signatures_json TEXT NOT NULL)""") @@ -76,12 +90,12 @@ def verify_release(self,record:dict)->dict: return {"valid":False,"reason":type(exc).__name__} def get_origin(self,lineage_id:str)->dict: - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.row_factory=sqlite3.Row; row=db.execute("SELECT * FROM origin_chains WHERE lineage_id=?",(str(lineage_id),)).fetchone() if not row: raise KeyError("origin lineage missing") return {"body":json.loads(row["body_json"]),"body_sha256":row["body_sha256"],"signatures":json.loads(row["signatures_json"])} def get_release(self,release_ref:str)->dict: - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: db.row_factory=sqlite3.Row; row=db.execute("SELECT * FROM release_origins WHERE release_ref=?",(str(release_ref),)).fetchone() if not row: raise KeyError("release origin missing") return {"body":json.loads(row["body_json"]),"body_sha256":row["body_sha256"],"signature":json.loads(row["signature_json"])} @@ -90,7 +104,7 @@ def import_origin(self,record:dict)->dict: check=self.verify_origin(record) if not check["valid"]: raise ValueError("invalid origin lineage: "+check.get("reason","unknown")) body=record["body"] - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: prior=db.execute("SELECT body_sha256 FROM origin_chains WHERE lineage_id=?",(body["lineage_id"],)).fetchone() if prior and prior[0]!=record["body_sha256"]: raise ValueError("origin lineage conflict") db.execute("INSERT OR IGNORE INTO origin_chains VALUES(?,?,?,?)",(body["lineage_id"],record["body_sha256"],json.dumps(body,sort_keys=True),json.dumps(record["signatures"],sort_keys=True))) @@ -100,7 +114,7 @@ def import_release(self,record:dict)->dict: check=self.verify_release(record) if not check["valid"]: raise ValueError("invalid release origin: "+check.get("reason","unknown")) body=record["body"] - with sqlite3.connect(self.path) as db: + with dbctx(self.path) as db: prior=db.execute("SELECT body_sha256 FROM release_origins WHERE release_ref=?",(body["release_ref"],)).fetchone() if prior and prior[0]!=record["body_sha256"]: raise ValueError("release origin conflict") db.execute("INSERT OR IGNORE INTO release_origins VALUES(?,?,?,?,?,?,?)",(body["release_ref"],body["release_tag"],body["release_commit_sha1"],body["release_tree_sha1"],record["body_sha256"],json.dumps(body,sort_keys=True),json.dumps(record["signature"],sort_keys=True))) diff --git a/src/40_BTDU/canonical_btdu.py b/src/40_BTDU/canonical_btdu.py index 5c01b632..61bb2804 100644 --- a/src/40_BTDU/canonical_btdu.py +++ b/src/40_BTDU/canonical_btdu.py @@ -2,6 +2,7 @@ from pathlib import Path from typing import Any, Callable, Mapping, Iterable +from contextlib import contextmanager import hashlib, json, mimetypes, os, sqlite3, subprocess, sys, time HERE=Path(__file__).resolve().parent @@ -44,8 +45,14 @@ def _load_adam_extensions(self): from adam_v42.distributed import SovereignErasureStore self.BondAlgebra=BondAlgebra; self.FirstClassBond=FirstClassBond; self.HyperBond=HyperBond; self.HyperRole=HyperRole; self.BondFamily=BondFamily; self.ConfidenceClass=ConfidenceClass; self.SovereignErasureStore=SovereignErasureStore + @contextmanager def _db(self): - db=sqlite3.connect(self.db_path); db.row_factory=sqlite3.Row; return db + db=sqlite3.connect(self.db_path); db.row_factory=sqlite3.Row + try: + with db: + yield db + finally: + db.close() def _init_db(self): with self._db() as db: diff --git a/tests/test_v3_btdu.py b/tests/test_v3_btdu.py index 6d485a2e..0b4a8819 100644 --- a/tests/test_v3_btdu.py +++ b/tests/test_v3_btdu.py @@ -32,4 +32,6 @@ def test_unauthorized_mutation_is_rejected(self): u=self.make(); with self.assertRaises(PermissionError): u.materialize_primitive_bytes({"body":dict(self.auth_body,nonce="tampered"),"signature":self.receipt["signature"]}) u.close() + def test_close_releases_btdu_index_file(self): + u=self.make(); path=u.db_path; u.close(); moved=path.with_suffix(".closed-test.sqlite"); path.replace(moved); moved.replace(path); self.assertTrue(path.is_file()) if __name__=="__main__": unittest.main() \ No newline at end of file diff --git a/tests/test_v3_protocol_origin_lineage.py b/tests/test_v3_protocol_origin_lineage.py index fc799ab3..bb0c482f 100644 --- a/tests/test_v3_protocol_origin_lineage.py +++ b/tests/test_v3_protocol_origin_lineage.py @@ -100,8 +100,12 @@ def test_06_v340_state_migrates_to_canonical_profiles_without_breaking_old_passp old_record=old['global_passport']; old_body={k:v for k,v in old_record.items() if k not in {'body_sha256','signature'}} old_body.pop('protocol_origin',None); old_body.pop('protocol_origin_is_not_asset_provenance',None) old_sha=global_mod.digest(old_body); old_sig=identity.sign(user['entity_id'],old_body) - with sqlite3.connect(passports.path) as db: + db=sqlite3.connect(passports.path) + try: db.execute('UPDATE global_passports SET body_sha256=?,body_json=?,signature_json=? WHERE passport_id=?',(old_sha,json.dumps(old_body,sort_keys=True),json.dumps(old_sig,sort_keys=True),old_body['passport_id'])) + db.commit() + finally: + db.close() legacy_passport=dict(old_body,body_sha256=old_sha,signature=old_sig) user_before=identity.load_manifest(user['entity_id']); object_before=fabric.get_object(old['object']['object_id']); right_before=rights.get(old['rights_passport']['passport_id']) origin=origin_mod.ProtocolOriginRegistry(state,identity); status=origin.install_bundle(self.bundle,profiles)