// Swift 5.9+. BOTH peers, no transport or presumed smartcard capabilities. // Ports implement the verified-transaction contract in examples/README.md. // close() rolls back unless committed; cached retries must not repeat an actuation. import Foundation enum Op { case register, use, revoke, retract } struct Envelope { let fields: [String]; let signature: String } struct Outcome { let receipt: Envelope; let fresh: Bool } enum DraftError: Error { case localApprovalRequired } protocol Transaction { var operation: Op { get } func cached() -> Envelope? func registerNewKey() throws func requireCurrentEntitlement() throws func revokeTarget() throws func retractRelationship() throws func signResult() throws -> Envelope func commitOnce(_ result: Envelope) throws func close() } protocol Ports { func challenge(_ op: Op, _ rid: String, _ target: String, _ context: String) throws -> Envelope func verifyProviderAndApprove(_ challenge: Envelope) throws func signProof(_ challenge: Envelope) throws -> Envelope func verifyResultAndApply(_ result: Envelope) throws func beginVerified(_ proof: Envelope, _ context: String) throws -> any Transaction func recoverRevoke(_ rid: String, _ target: String, _ context: String) throws -> Envelope } struct TokenSide { let ports: any Ports func respond(_ q: Envelope) throws -> Envelope { try ports.verifyProviderAndApprove(q); return try ports.signProof(q) } func accept(_ result: Envelope) throws { try ports.verifyResultAndApply(result) } } struct ProviderSide { let ports: any Ports func start(_ op: Op, _ rid: String, _ target: String, _ context: String) throws -> Envelope { try ports.challenge(op,rid,target,context) } func finish(_ proof: Envelope, _ context: String) throws -> Outcome { let tx = try ports.beginVerified(proof,context); defer { tx.close() } if let old = tx.cached() { return Outcome(receipt: old,fresh: false) } switch tx.operation { case .register: try tx.registerNewKey() case .use: try tx.requireCurrentEntitlement() case .revoke: try tx.revokeTarget() case .retract: try tx.retractRelationship() } let result = try tx.signResult(); try tx.commitOnce(result) return Outcome(receipt: result,fresh: true) } func lost(_ rid: String, _ target: String, _ context: String) throws -> Envelope { try ports.recoverRevoke(rid,target,context) } } func legacyValue(_ value: String, approved: Bool, selected: Bool) throws -> String { guard approved && selected && !value.isEmpty else { throw DraftError.localApprovalRequired } return value // Renderer/standard driver input only. }