"""Finite, two-replica illustration of lower-bound escrow accounting. Not a database implementation, network experiment, or performance benchmark. Rule reference: Balegas et al., arXiv:1503.09052v1, Figure 2. Run with Python 3.10+: python3 escrow-rights.py """ import json def initial(a=3, b=2): for value in (a, b): if type(value) is not int or value < 0: raise ValueError("initial rights must be nonnegative integers") return {"R": [[a, 0], [0, b]], "U": [0, 0]} def rights(state, actor): return (state["R"][actor][actor] + state["R"][1-actor][actor] - state["R"][actor][1-actor] - state["U"][actor]) def value(state): return sum(state["R"][i][i] - state["U"][i] for i in range(2)) def spend(state, actor, amount, destination=None): if type(actor) is not int or actor not in (0, 1): raise ValueError("actor must be 0 or 1") if type(amount) is not int or amount <= 0: raise ValueError("amount must be a positive integer") if destination is not None and (type(destination) is not int or destination != 1-actor): raise ValueError("transfer must name the other replica") if amount > rights(state, actor): return False if destination is None: state["U"][actor] += amount else: state["R"][actor][destination] += amount return True def merge(left, right): return { "R": [[max(left["R"][i][j], right["R"][i][j]) for j in range(2)] for i in range(2)], "U": [max(left["U"][i], right["U"][i]) for i in range(2)], } def example(): a, b = initial(), initial() rows = [] def record(label): joined = merge(a, b) rows.append([label, rights(a, 0), rights(b, 1), value(joined)]) record("Allocated") spend(a, 0, 3) spend(b, 1, 1) record("A uses 3; B uses 1") spend(b, 1, 1, destination=0) record("B transfers 1; A has not received it") a = merge(a, b) record("A receives the transfer") spend(a, 0, 1) b = merge(b, a) record("A uses the last right; states merge") return rows if __name__ == "__main__": print(json.dumps({"kind": "constructed example", "lower_bound": 0, "columns": ["stage", "A_local_rights", "B_local_rights", "merged_remaining"], "rows": example()}, indent=2))