escrow_machines 0.7.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/CHANGELOG.md +88 -0
- data/Cargo.lock +314 -0
- data/Cargo.toml +24 -0
- data/LICENSE.txt +21 -0
- data/README.md +254 -0
- data/ext/escrow_machines_native/core/CHANGELOG.md +59 -0
- data/ext/escrow_machines_native/core/Cargo.toml +17 -0
- data/ext/escrow_machines_native/core/README.md +64 -0
- data/ext/escrow_machines_native/core/src/frame.rs +243 -0
- data/ext/escrow_machines_native/core/src/lib.rs +453 -0
- data/ext/escrow_machines_native/core/src/merge.rs +132 -0
- data/ext/escrow_machines_native/core/src/ops.rs +180 -0
- data/ext/escrow_machines_native/core/src/table.rs +108 -0
- data/ext/escrow_machines_native/extconf.rb +2 -0
- data/ext/escrow_machines_native/ffi/Cargo.toml +21 -0
- data/ext/escrow_machines_native/ffi/extconf.rb +14 -0
- data/ext/escrow_machines_native/ffi/src/init.rs +70 -0
- data/ext/escrow_machines_native/ffi/src/lib.rs +343 -0
- data/lib/escrow_machines/version.rb +4 -0
- data/lib/escrow_machines.rb +60 -0
- data/sig/escrow_machines.rbs +112 -0
- metadata +90 -0
data/README.md
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
# EscrowMachines
|
|
2
|
+
|
|
3
|
+
> You cannot sell the seat twice if you only ever sell the seats you are holding. 🏦
|
|
4
|
+
|
|
5
|
+
A rights ledger for Ruby replicas that can't always talk to each other. A fixed set of replicas shares a fixed supply: seats, credits, stock, quota. Each replica holds part of it and spends only from its own part, with no round trip to anyone. Rights move between replicas by transfer, never by wishful thinking. Merge the replicas in any order, any number of times, and they agree. The total spent never exceeds the supply, partitioned or not.
|
|
6
|
+
|
|
7
|
+
## Quick Start
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
gem 'escrow_machines'
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
```ruby
|
|
14
|
+
# 100 seats, three regions. Every region builds the same allotment.
|
|
15
|
+
paris = EscrowMachines::Escrow.new(0, [60, 30, 10])
|
|
16
|
+
tokyo = EscrowMachines::Escrow.new(2, [60, 30, 10])
|
|
17
|
+
|
|
18
|
+
tokyo.spend(8) # => 2, seats left in Tokyo
|
|
19
|
+
tokyo.spend(5) # => :insufficient. Paris has 60. Tokyo has 2.
|
|
20
|
+
|
|
21
|
+
receipt = paris.transfer(2, 1, 20).receipt
|
|
22
|
+
save(paris.encode) # persist before the receipt leaves the building
|
|
23
|
+
tokyo.accept(receipt) # => :applied
|
|
24
|
+
tokyo.accept(receipt) # => :replayed, the relay stuttered
|
|
25
|
+
tokyo.spend(5) # => 17
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
One escrow per replica. `Escrow.new` takes what the core's constructor takes, in its order: `local`, the index of this replica, and `allotted`, every replica's starting rights. `transfer` takes `to`, `id` and `amount`. Amounts, replica indexes and transfer ids are Integers. No clock, no network, no storage: you bring those.
|
|
29
|
+
|
|
30
|
+
## A Message to the Resistance
|
|
31
|
+
|
|
32
|
+
So you have a hundred seats and three regions, and you put the count in a replicated counter because the conference talk said CRDTs never conflict. They don't. Each region decremented happily through a forty-second partition, the counters merged without a single conflict, and the merged value was minus eleven. Eleven people are now standing in a lobby holding a confirmation email.
|
|
33
|
+
|
|
34
|
+
A PN-counter converges. Converging on a negative number is still converging. What it can't do is say no, because saying no requires knowing something about the other replicas, and the entire point was not asking them.
|
|
35
|
+
|
|
36
|
+
The other fix is asking them: a lock, a leader, a quorum on every sale. Now Tokyo can't sell a seat while the link to Paris is down, which is the outage you bought replicas to avoid.
|
|
37
|
+
|
|
38
|
+
There's a third option from 1986. Split the hundred up front. Each replica owns a share and sells from its share alone. A replica that runs low asks a neighbour for some of theirs, and the neighbour gives away only what it still holds. Nobody ever needs a global answer, because nobody ever spends a right they aren't holding. That's escrow, and the bookkeeping for it is this gem.
|
|
39
|
+
|
|
40
|
+
## Chapter 1: Stardate 2026.316, the AMS O'Neil
|
|
41
|
+
|
|
42
|
+
> **AMS O'Neil**, NCC-4233, *O'Neil*-class treasury escort.
|
|
43
|
+
> The hold carries what was counted aboard. Nothing more is for sale.
|
|
44
|
+
|
|
45
|
+
The escort doesn't make money. It moves a counted amount between stations and refuses to let anyone spend a chit that isn't physically in the hold. Each station's strongbox has one keyholder. A station can hand chits to another station and log the handover; it cannot reach into someone else's box, and it cannot print.
|
|
46
|
+
|
|
47
|
+
On a bridge somewhere, a cadet volunteers:
|
|
48
|
+
|
|
49
|
+
```ruby
|
|
50
|
+
def sell(region, seats)
|
|
51
|
+
counter = PNCounter.for(:seats)
|
|
52
|
+
return :sold_out if counter.value < seats
|
|
53
|
+
counter.decrement(region, seats)
|
|
54
|
+
end
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
"That," says the escort's purser, "checks a number three stations are changing, and then changes it. You've sold the same eleven seats in three time zones."
|
|
58
|
+
|
|
59
|
+
## The Flight Plan
|
|
60
|
+
|
|
61
|
+
Every right in the supply is in exactly one place at any moment:
|
|
62
|
+
|
|
63
|
+
```mermaid
|
|
64
|
+
stateDiagram-v2
|
|
65
|
+
[*] --> held: allotted at construction
|
|
66
|
+
held --> spent: spend, by the holder only
|
|
67
|
+
spent --> held: refund, by the replica that spent it
|
|
68
|
+
held --> in_flight: transfer, giver deducts at once
|
|
69
|
+
in_flight --> held: accept or merge, receiver credits
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Held plus spent plus in flight always equals the supply. Nothing mints, nothing leaks, and an in-flight right belongs to nobody until its receipt lands.
|
|
73
|
+
|
|
74
|
+
And the afternoon Tokyo ran low while the relay was repeating itself:
|
|
75
|
+
|
|
76
|
+
```mermaid
|
|
77
|
+
sequenceDiagram
|
|
78
|
+
participant T as Tokyo
|
|
79
|
+
participant P as Paris
|
|
80
|
+
participant D as Paris disk
|
|
81
|
+
|
|
82
|
+
T->>P: need 20, transfer id 1
|
|
83
|
+
P->>P: transfer(2, 1, 20)
|
|
84
|
+
P->>D: encode
|
|
85
|
+
P-->>T: Receipt (lost in the relay)
|
|
86
|
+
|
|
87
|
+
T->>P: need 20, transfer id 1 (retry)
|
|
88
|
+
P->>P: transfer(2, 1, 20)
|
|
89
|
+
Note over P: same id, same Receipt, nothing moves twice
|
|
90
|
+
P-->>T: Receipt
|
|
91
|
+
P-->>T: Receipt (the relay finds the first one)
|
|
92
|
+
|
|
93
|
+
T->>T: accept → :applied
|
|
94
|
+
T->>T: accept → :replayed
|
|
95
|
+
Note over T: 20 seats, once.
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
## How the Escrow Works
|
|
99
|
+
|
|
100
|
+
### Spend
|
|
101
|
+
|
|
102
|
+
```ruby
|
|
103
|
+
escrow = EscrowMachines::Escrow.new(0, [10, 5])
|
|
104
|
+
|
|
105
|
+
escrow.spend(7) # => 3, what this replica has left
|
|
106
|
+
escrow.spend(4) # => :insufficient
|
|
107
|
+
escrow.available # => 3
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
`spend` looks at one number: what this replica holds. The other replica's 5 are not part of the question. A refused spend changes nothing.
|
|
111
|
+
|
|
112
|
+
### Refund
|
|
113
|
+
|
|
114
|
+
```ruby
|
|
115
|
+
escrow.refund(2) # => 5, back in this replica's hold
|
|
116
|
+
escrow.refund(6) # => :exceeds_spent
|
|
117
|
+
escrow.outstanding(0) # => 5, spent and not refunded
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
A refund returns rights this replica spent. It can't return more than that, because that would be printing. Refund where you spent: the rights come back to the replica that let them go.
|
|
121
|
+
|
|
122
|
+
### Transfer
|
|
123
|
+
|
|
124
|
+
```ruby
|
|
125
|
+
left = EscrowMachines::Escrow.new(0, [10, 0])
|
|
126
|
+
right = EscrowMachines::Escrow.new(1, [10, 0])
|
|
127
|
+
|
|
128
|
+
transfer = left.transfer(1, 1, 4)
|
|
129
|
+
transfer # => #<data EscrowMachines::Transfer::Applied receipt=...>
|
|
130
|
+
receipt = transfer.receipt
|
|
131
|
+
receipt # => #<data EscrowMachines::Receipt from=0, to=1, id=1, amount=4, total=4>
|
|
132
|
+
left.available # => 6, deducted now
|
|
133
|
+
|
|
134
|
+
again = left.transfer(1, 1, 4)
|
|
135
|
+
again.class # => EscrowMachines::Transfer::Replayed. Nothing moved again.
|
|
136
|
+
again.receipt == receipt # => true, the same Receipt
|
|
137
|
+
left.transfer(1, 1, 9) # => :id_conflict
|
|
138
|
+
left.transfer(1, 0, 4) # => :stale_id
|
|
139
|
+
left.transfer(1, 2, 7) # => :insufficient
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
`transfer` answers the core's `Transfer`: a `Transfer::Applied` when the rights moved now, a `Transfer::Replayed` when this id had already moved them. Both carry the `receipt` to deliver, so `transfer.receipt` works either way. You choose the id. It has to go up for each destination, and a retry reuses the one it's retrying. The latest id is answered `Transfer::Replayed` with its original receipt for as long as it stays the latest. Anything older is `:stale_id`: refused, not repeated.
|
|
143
|
+
|
|
144
|
+
```ruby
|
|
145
|
+
left.last_transfer(0, 1) # => #<data EscrowMachines::Mark id=1, amount=4>
|
|
146
|
+
left.last_transfer(1, 0) # => nil, nothing has gone that way
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
### Accept
|
|
150
|
+
|
|
151
|
+
```ruby
|
|
152
|
+
right.accept(receipt) # => :applied
|
|
153
|
+
right.accept(receipt) # => :replayed
|
|
154
|
+
right.available # => 4
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
A receipt says how much `from` has granted `to` in total, not "add four". Deliver it twice, deliver it after a newer one, deliver it to a bystander: the answer is the same grant. A receipt that contradicts what the replica already knows is `:malformed`, `:id_conflict`, or `:forged`, and changes nothing.
|
|
158
|
+
|
|
159
|
+
### Merge
|
|
160
|
+
|
|
161
|
+
```ruby
|
|
162
|
+
right.spend(1)
|
|
163
|
+
left.merge(right) # => :merged
|
|
164
|
+
left.balance(1) # => 3, what left now believes right holds
|
|
165
|
+
left.available # => 6, still only its own
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
`merge` folds in everything another replica knows. Any order, any number of times, any gossip topology. It never makes someone else's rights spendable here. `balance` for another replica is an estimate, and it can be negative when you've seen rights leave a replica before you've seen them arrive there.
|
|
169
|
+
|
|
170
|
+
### Persist, and what happens when you didn't
|
|
171
|
+
|
|
172
|
+
```ruby
|
|
173
|
+
frame = left.encode # binary String, Escrow::ENCODED_LEN bytes
|
|
174
|
+
left = EscrowMachines::Escrow.decode(frame) # RangeError if it isn't a sane frame
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
A replica that restarts from an old frame has forgotten spends it already made. The first peer that remembers them proves it:
|
|
178
|
+
|
|
179
|
+
```ruby
|
|
180
|
+
stale = EscrowMachines::Escrow.decode(old_frame)
|
|
181
|
+
stale.merge(right) # => :diverged, and stale is untouched
|
|
182
|
+
stale.recover(right) # => :recovered, adopts what right saw of it
|
|
183
|
+
# => :overdrawn if the two histories can't both be true
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
`recover` is a decision, which is why it isn't `merge`. It restores what some peer witnessed. A spend that never left the lost replica is gone, and no method can find it.
|
|
187
|
+
|
|
188
|
+
### Capacity
|
|
189
|
+
|
|
190
|
+
```ruby
|
|
191
|
+
EscrowMachines::CAPACITY # => 8
|
|
192
|
+
EscrowMachines::Escrow.new(0, [1] * 9) # RangeError
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
Up to eight replicas, fixed when you build the escrow. The set doesn't grow, shrink, or rename itself afterwards.
|
|
196
|
+
|
|
197
|
+
### What each verb can answer
|
|
198
|
+
|
|
199
|
+
Escrow takes no clock, so no answer records one: every honoured answer, repeats included, depends only on the state and the arguments.
|
|
200
|
+
|
|
201
|
+
| Verb | Honoured | Refusals |
|
|
202
|
+
| --- | --- | --- |
|
|
203
|
+
| `spend` | the Integer left | `:zero_amount`, `:insufficient`, `:overflow` |
|
|
204
|
+
| `refund` | the Integer now held | `:zero_amount`, `:exceeds_spent`, `:overflow` |
|
|
205
|
+
| `transfer` | a `Transfer::Applied`, or the repeat `Transfer::Replayed` | `:zero_amount`, `:unknown_replica`, `:self_transfer`, `:stale_id`, `:id_conflict`, `:insufficient`, `:overflow` |
|
|
206
|
+
| `accept` | `:applied`, or the repeat `:replayed` | `:unknown_replica`, `:malformed`, `:id_conflict`, `:forged`, `:overflow` |
|
|
207
|
+
| `merge` | `:merged` | `:config_mismatch`, `:diverged`, `:overflow` |
|
|
208
|
+
| `recover` | `:recovered` | `:config_mismatch`, `:diverged`, `:overdrawn`, `:overflow` |
|
|
209
|
+
|
|
210
|
+
`Receipt`, `Mark`, `Transfer::Applied` and `Transfer::Replayed` are frozen `Data` values with the fields of the core types they are named after. Method names are the core's: `local`, `replicas`, `supply`, `allotted`, `available`, `balance`, `spent`, `refunded`, `outstanding`, `granted`, `last_transfer`, `encode`, `decode`. The core's `Refusal` has sixteen variants, each with its own symbol and no catch-all. Thirteen come back from calls; the three frame refusals (`:truncated`, `:wrong_structure`, `:wrong_shape`), like a `:malformed` frame, appear only in `decode`'s `RangeError` message, `"the frame is refused: wrong_shape"`. Four of them carry a number in the core (`Insufficient { available }`, `ExceedsSpent { outstanding }`, `StaleId { latest }`, `IdConflict { amount }`); a refusal in Ruby is a bare symbol, and the same numbers are what the readers answer: `available` for `:insufficient`, `outstanding(local)` for `:exceeds_spent`, `last_transfer(local, to).id` for `:stale_id` and `last_transfer(from, to).amount` for `:id_conflict`.
|
|
211
|
+
|
|
212
|
+
`Receipt`, `Mark` and the `Transfer` values are checked by the core when they are built, by hand or by the escrow alike: a receipt naming one replica on both ends, moving zero, or moving more than its `total` raises `RangeError`, as does a `Mark` of zero; a non-Integer field raises `TypeError`, and a `Transfer` value holding anything but a `Receipt` raises `TypeError`. So `accept` never sees a receipt that contradicts itself (the core's `Receipt` has private fields for the same reason), and `:self_transfer` is `transfer`'s answer alone. The four classes are sealed: subclassing one raises `TypeError` and `allocate` is undefined. Sealing stops accidents, not reflection (a named subclass's constant is bound before the raise, `Marshal.load` skips `initialize`), so the binding is the authority: a receipt it reads must be exactly a `Receipt` and is checked by `Receipt::new` again, raising `TypeError` or `RangeError` before the core sees it.
|
|
213
|
+
|
|
214
|
+
## The Rules of the Escort
|
|
215
|
+
|
|
216
|
+
- **Everything is an Integer** in `0..2**64-1`: amounts, replica indexes, ids. Floats, nil and strings raise `TypeError`. Out of range raises `RangeError`. So does an allotment that adds up past `2**64-1`, a frame `decode` cannot read, and a `Receipt` or `Mark` the core would not build. Nothing raises `ArgumentError` except Ruby itself, for a wrong number of arguments.
|
|
217
|
+
- **A raise changes nothing.** Every argument is checked before the core is called, and every class was resolved once when the extension loaded, so a call that raises left the escrow untouched.
|
|
218
|
+
- **Same allotment everywhere.** Every replica is built from the same `allotted` array. Views built from different ones answer `:config_mismatch` and don't merge.
|
|
219
|
+
- **The binding never loses work.** Every argument is read before the core is called. `transfer` builds its answer from a copy of the escrow kept only once the `Transfer` exists: a build that raises moves no rights, one that freezes the escrow raises `FrozenError`, and one that changes the escrow meanwhile (a redefined `new` calling back in) raises `RuntimeError`; in each case the outer transfer is not applied.
|
|
220
|
+
- **Refusals don't raise.** `:insufficient`, `:exceeds_spent`, `:zero_amount`, `:unknown_replica`, `:self_transfer`, `:stale_id`, `:id_conflict`, `:malformed`, `:forged`, `:config_mismatch`, `:diverged`, `:overdrawn` and `:overflow` are answers. A refused call leaves the escrow exactly as it was.
|
|
221
|
+
- **Counters are lifetime totals.** Grants and spends only count up. A pair that has moved `2**64-1` rights between them over the years answers `:overflow` instead of wrapping.
|
|
222
|
+
- **Frozen means frozen.** `freeze` the escrow and `spend`, `refund`, `transfer`, `accept`, `merge` and `recover` raise `FrozenError`, before any argument is read.
|
|
223
|
+
|
|
224
|
+
## What You Think You're Doing vs Reality
|
|
225
|
+
|
|
226
|
+
### You Think: "CRDTs can't conflict, so my counter is safe."
|
|
227
|
+
### Reality: It merged cleanly to minus eleven.
|
|
228
|
+
|
|
229
|
+
Convergence means everyone ends up with the same number. It doesn't mean the number is one you can live with. An invariant like "never below zero" is a promise about the sum of decisions made by replicas that can't see each other, and the only way to keep it without asking is to hand each replica a budget in advance. That's the difference between a counter and an escrow: one records what happened, the other can refuse.
|
|
230
|
+
|
|
231
|
+
### You Think: "The transfer timed out, so I'll send it again with a new id."
|
|
232
|
+
### Reality: Now two transfers happened.
|
|
233
|
+
|
|
234
|
+
The id is the transfer's name. A retry is the same transfer, so it has the same name. A new id is a new transfer, and Paris will cheerfully send another twenty.
|
|
235
|
+
|
|
236
|
+
## What's Yours
|
|
237
|
+
|
|
238
|
+
This is an early release of a policy core. The API will change. It decides; it doesn't run anything.
|
|
239
|
+
|
|
240
|
+
**Durable replica identity is yours.** `encode` the escrow and get it onto disk before you act on a successful `spend`, `refund` or `transfer`, and before a receipt leaves the process. A replica that comes back from an older frame under the same index can spend the same rights twice, and `:diverged` only tells you after a peer notices. Never run two live processes as the same replica.
|
|
241
|
+
|
|
242
|
+
**Transfer ids are yours.** Per destination, strictly increasing, reused on retry. Only the latest id for a pair replays; keep your retries ahead of your next request.
|
|
243
|
+
|
|
244
|
+
**Transport is yours.** Receipts and frames are values. How they cross the wire, who asks whom for rights, and how much to ask for are your call. Rights in flight are spendable by nobody until the receipt or a merge arrives, so a lost receipt strands rights until gossip catches up.
|
|
245
|
+
|
|
246
|
+
**Authenticity is yours.** `accept` and `merge` catch contradictions, not liars. A fabricated receipt from a replica that never granted anything will be believed. Don't accept frames from anyone you wouldn't hand the strongbox key.
|
|
247
|
+
|
|
248
|
+
**Membership is yours.** The replica set is fixed. Retiring a replica means transferring its rights out first and never using the index again.
|
|
249
|
+
|
|
250
|
+
## License
|
|
251
|
+
|
|
252
|
+
MIT License. See [LICENSE.txt](LICENSE.txt) for details.
|
|
253
|
+
|
|
254
|
+
**Remember: the counter will merge either way. The question is whether it ever said no.**
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## [0.6.1](https://github.com/seuros/escrow_machines/compare/escrow-machines-v0.6.0...escrow-machines-v0.6.1) (2026-11-16)
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
### Bug Fixes
|
|
7
|
+
|
|
8
|
+
* refuse merges that disagree on a transfer's cumulative total ([cbcafa5](https://github.com/seuros/escrow_machines/commit/cbcafa54cbb866a9f5c425dbcbbad90b09694f6e))
|
|
9
|
+
|
|
10
|
+
## [0.6.0](https://github.com/seuros/escrow_machines/compare/escrow-machines-v0.5.0...escrow-machines-v0.6.0) (2026-11-16)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
### ⚠ BREAKING CHANGES
|
|
14
|
+
|
|
15
|
+
* fold FrameError into Refusal, new 0xE6 frame of plain tallies
|
|
16
|
+
|
|
17
|
+
### Features
|
|
18
|
+
|
|
19
|
+
* fold FrameError into Refusal, new 0xE6 frame of plain tallies ([04c0d32](https://github.com/seuros/escrow_machines/commit/04c0d32b6be44d1fdff8a3cec23cd39fbbf54233))
|
|
20
|
+
|
|
21
|
+
## [0.5.0](https://github.com/seuros/escrow_machines/compare/escrow-machines-v0.4.0...escrow-machines-v0.5.0) (2026-11-14)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
### ⚠ BREAKING CHANGES
|
|
25
|
+
|
|
26
|
+
* adopt matryona-machines 0.2: exact Receipt fields, exact-class Escrow partners, honoured replays proven unchanged
|
|
27
|
+
|
|
28
|
+
### Features
|
|
29
|
+
|
|
30
|
+
* adopt matryona-machines 0.2: exact Receipt fields, exact-class Escrow partners, honoured replays proven unchanged ([78045e6](https://github.com/seuros/escrow_machines/commit/78045e6f0722a55c2804920207ae197a1e472ac9))
|
|
31
|
+
|
|
32
|
+
## [0.4.0](https://github.com/seuros/escrow_machines/compare/escrow-machines-v0.3.0...escrow-machines-v0.4.0) (2026-11-14)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
### ⚠ BREAKING CHANGES
|
|
36
|
+
|
|
37
|
+
* private Mark/Receipt fields, sealed validated values, clone-then-keep transfer, compile-time frame bound
|
|
38
|
+
|
|
39
|
+
### Features
|
|
40
|
+
|
|
41
|
+
* private Mark/Receipt fields, sealed validated values, clone-then-keep transfer, compile-time frame bound ([223b8cb](https://github.com/seuros/escrow_machines/commit/223b8cb5dcb34e5cb615c8f7667b17bb7eac8e16))
|
|
42
|
+
|
|
43
|
+
## [0.3.0](https://github.com/seuros/escrow_machines/compare/escrow-machines-v0.2.0...escrow-machines-v0.3.0) (2026-11-13)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
### ⚠ BREAKING CHANGES
|
|
47
|
+
|
|
48
|
+
* see CONVENTIONS: one exhaustive Refusal per crate, Result from every mutator, honoured idempotent repeats, Ruby mirrors the core. No compatibility aliases. replica/dump/load are local/encode/decode; transfer answers Transfer::Applied or Transfer::Replayed.
|
|
49
|
+
|
|
50
|
+
### Features
|
|
51
|
+
|
|
52
|
+
* Ruby uses the core's names and positional arguments, Transfer variants as values ([8d83f20](https://github.com/seuros/escrow_machines/commit/8d83f20731ca496ebfb251480f9895e7726b3367))
|
|
53
|
+
|
|
54
|
+
## [0.2.0](https://github.com/seuros/escrow_machines/compare/escrow-machines-v0.1.0...escrow-machines-v0.2.0) (2026-11-12)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
### Features
|
|
58
|
+
|
|
59
|
+
* initial extraction ([d0edc22](https://github.com/seuros/escrow_machines/commit/d0edc223cc69da6ca9b35d07940545a439464356))
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
[package]
|
|
2
|
+
name = "escrow-machines"
|
|
3
|
+
version = "0.6.1"
|
|
4
|
+
edition.workspace = true
|
|
5
|
+
rust-version.workspace = true
|
|
6
|
+
license.workspace = true
|
|
7
|
+
description = "Bounded-counter escrow: fixed-replica rights accounting, conserved spends, and replay-safe transfers"
|
|
8
|
+
readme = "README.md"
|
|
9
|
+
exclude = ["src/**/tests.rs", "src/tests/", "tests/"]
|
|
10
|
+
keywords = ["escrow", "crdt", "bounded-counter", "idempotency", "no-std"]
|
|
11
|
+
categories = ["no-std", "data-structures"]
|
|
12
|
+
[dependencies]
|
|
13
|
+
merge-machines.workspace = true
|
|
14
|
+
[dev-dependencies]
|
|
15
|
+
matryona-machines = { workspace = true, features = ["testing"] }
|
|
16
|
+
[lints]
|
|
17
|
+
workspace = true
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
# escrow-machines
|
|
2
|
+
|
|
3
|
+
> **AMS O'Neil**, NCC-4233, *O'Neil*-class treasury escort.
|
|
4
|
+
|
|
5
|
+
Engine-room flight manual: move counted rights between stations and never spend what is not in the hold.
|
|
6
|
+
|
|
7
|
+
Allocation-free `no_std` bounded-counter CRDT. A fixed set of up to `N` replicas
|
|
8
|
+
shares a fixed supply of rights. `Escrow<N>` is one replica's view: a matrix of
|
|
9
|
+
cumulative grants between replicas plus per-replica spent and refunded counters.
|
|
10
|
+
`spend` and `transfer` are checked against the rights the local replica holds,
|
|
11
|
+
so the total spent cannot exceed the supply under any partition. `refund`
|
|
12
|
+
returns only what the local replica itself spent. Nothing is minted after
|
|
13
|
+
construction.
|
|
14
|
+
|
|
15
|
+
`merge` is a cell-wise join: commutative, associative, idempotent. `transfer`
|
|
16
|
+
takes a caller-chosen id, strictly increasing per `(from, to)` pair; repeating
|
|
17
|
+
the latest id returns the original `Receipt` and moves nothing. Receipts carry
|
|
18
|
+
the cumulative grant, so `accept` is idempotent and order-insensitive. Every
|
|
19
|
+
refusal is a `Refusal` value and leaves the state untouched; counters refuse at
|
|
20
|
+
`u64::MAX` instead of wrapping.
|
|
21
|
+
|
|
22
|
+
`Escrow` implements the `merge-machines` `Merge` trait. Replica ids are
|
|
23
|
+
dense, `0..replicas` with `replicas <= N`, so every per-replica table is a
|
|
24
|
+
plain `[T; N]` read through a position that is below `N` by construction: a
|
|
25
|
+
lookup cannot miss. The counters are such tables, one `u64` cell per replica
|
|
26
|
+
joined by `max`, so raising one never needs a free slot and its only refusal
|
|
27
|
+
is `Overflow`. Frame refusals are `Refusal` variants like every other
|
|
28
|
+
(`Truncated`, `WrongStructure`, `WrongShape`, `Malformed`); there is no second
|
|
29
|
+
error type. The frame stores each counter as `N` 64-bit fields; it leads with
|
|
30
|
+
`0xE6`, and a frame from before (`0xE5`, which embedded `merge-machines`
|
|
31
|
+
counter frames) is `WrongStructure`.
|
|
32
|
+
|
|
33
|
+
The escrow adds what a PN-counter lacks: writes are restricted to the local
|
|
34
|
+
replica's own cells and bounded by its balance.
|
|
35
|
+
|
|
36
|
+
Contracts the caller owns:
|
|
37
|
+
|
|
38
|
+
- **Durable replica identity.** Persist `encode`'s fixed-length frame before
|
|
39
|
+
acting on a successful call. A replica restarted from an older frame can
|
|
40
|
+
double-spend; `merge` answers `Diverged` once a peer proves it, and `recover`
|
|
41
|
+
adopts the peer's record explicitly (`Overdrawn` if the histories cannot both
|
|
42
|
+
hold). Spends no peer saw are unrecoverable.
|
|
43
|
+
- **Transfer ids.** Monotonic per destination, reused on retry. Only the latest
|
|
44
|
+
id per pair replays; older ids answer `StaleId`.
|
|
45
|
+
- **Authenticity and transport.** Contradictory receipts and frames are refused;
|
|
46
|
+
fabricated but self-consistent ones are not detectable here.
|
|
47
|
+
- **Membership.** The replica set and allotment are fixed at construction and
|
|
48
|
+
must be identical on every replica.
|
|
49
|
+
|
|
50
|
+
`Receipt::new` and `Mark::new` build only values some call could produce
|
|
51
|
+
(`None` for a receipt naming one replica twice, moving zero or more than its
|
|
52
|
+
`total`, and for a mark of zero). Their fields are private, read through
|
|
53
|
+
`from()`, `to()`, `id()`, `amount()`, `total()`, so no receipt contradicts
|
|
54
|
+
itself and `accept` needs no check for one: its `Malformed` is a receipt that
|
|
55
|
+
contradicts the grants already seen.
|
|
56
|
+
|
|
57
|
+
No call takes a clock, so no answer records one.
|
|
58
|
+
|
|
59
|
+
The Ruby gem mirrors `Receipt` and `Mark` as `Data` values of the same names,
|
|
60
|
+
validated through those constructors, and `Transfer` as one `Data` per
|
|
61
|
+
variant, `Transfer::Applied` and `Transfer::Replayed`, each carrying the
|
|
62
|
+
`receipt`.
|
|
63
|
+
|
|
64
|
+
Pre-1.0: breaking changes land in minor versions. No clock, I/O, hashing, or randomness.
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
//! The fixed-length frame a replica persists to keep its identity durable.
|
|
2
|
+
|
|
3
|
+
use crate::table::{Member, Tally};
|
|
4
|
+
use crate::{Escrow, Mark, Refusal};
|
|
5
|
+
|
|
6
|
+
/// The byte that leads every escrow frame. `0xE5` led the frames that
|
|
7
|
+
/// embedded `merge-machines` counter frames; those are another structure now.
|
|
8
|
+
const TAG: u8 = 0xE6;
|
|
9
|
+
/// Bytes of a two-byte header field.
|
|
10
|
+
const SMALL: usize = 2;
|
|
11
|
+
/// Bytes of a 64-bit field.
|
|
12
|
+
const FIELD: usize = 8;
|
|
13
|
+
/// Bytes before the tables: tag, capacity, replica count, local replica.
|
|
14
|
+
const HEADER: usize = 1 + 3 * SMALL;
|
|
15
|
+
/// Bytes of one mark record: a presence byte, the id, the amount.
|
|
16
|
+
const MARK: usize = 1 + 2 * FIELD;
|
|
17
|
+
|
|
18
|
+
/// The front of `bytes`, `len` long, leaving the rest in place.
|
|
19
|
+
fn take<'a>(bytes: &mut &'a [u8], len: usize) -> Result<&'a [u8], Refusal> {
|
|
20
|
+
let (head, rest) = bytes.split_at_checked(len).ok_or(Refusal::Truncated)?;
|
|
21
|
+
*bytes = rest;
|
|
22
|
+
Ok(head)
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
fn take_u64(bytes: &mut &[u8]) -> Result<u64, Refusal> {
|
|
26
|
+
let mut field = [0; FIELD];
|
|
27
|
+
field.copy_from_slice(take(bytes, FIELD)?);
|
|
28
|
+
Ok(u64::from_le_bytes(field))
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
fn take_small(bytes: &mut &[u8]) -> Result<usize, Refusal> {
|
|
32
|
+
let mut field = [0; SMALL];
|
|
33
|
+
field.copy_from_slice(take(bytes, SMALL)?);
|
|
34
|
+
Ok(usize::from(u16::from_le_bytes(field)))
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/// A frame being filled front to back.
|
|
38
|
+
struct Writer<'a> {
|
|
39
|
+
out: &'a mut [u8],
|
|
40
|
+
at: usize,
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
impl Writer<'_> {
|
|
44
|
+
/// The next `len` bytes of the frame.
|
|
45
|
+
fn slot(&mut self, len: usize) -> Result<&mut [u8], Refusal> {
|
|
46
|
+
let end = self.at.checked_add(len).ok_or(Refusal::Truncated)?;
|
|
47
|
+
let slot = self.out.get_mut(self.at..end).ok_or(Refusal::Truncated)?;
|
|
48
|
+
self.at = end;
|
|
49
|
+
Ok(slot)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
fn put(&mut self, field: &[u8]) -> Result<(), Refusal> {
|
|
53
|
+
self.slot(field.len())?.copy_from_slice(field);
|
|
54
|
+
Ok(())
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/// The low two bytes of `value`, which is at most `N`, and `encode`
|
|
58
|
+
/// rejects at compile time any `N` above [`u16::MAX`].
|
|
59
|
+
fn put_small(&mut self, value: usize) -> Result<(), Refusal> {
|
|
60
|
+
let [low, high, ..] = value.to_le_bytes();
|
|
61
|
+
self.put(&[low, high])
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/// Every cell of `tally`, member order, one 64-bit field each.
|
|
65
|
+
fn put_tally<const N: usize>(&mut self, tally: &Tally<N>) -> Result<(), Refusal> {
|
|
66
|
+
for count in tally.counts() {
|
|
67
|
+
self.put(&count.to_le_bytes())?;
|
|
68
|
+
}
|
|
69
|
+
Ok(())
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/// `N` 64-bit fields read as one tally.
|
|
74
|
+
fn take_tally<const N: usize>(bytes: &mut &[u8]) -> Result<Tally<N>, Refusal> {
|
|
75
|
+
let mut counts = [0; N];
|
|
76
|
+
for count in &mut counts {
|
|
77
|
+
*count = take_u64(bytes)?;
|
|
78
|
+
}
|
|
79
|
+
Ok(Tally::from_counts(counts))
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
impl<const N: usize> Escrow<N> {
|
|
83
|
+
/// Length of the [`encode`](Self::encode) frame.
|
|
84
|
+
/// The allotment, then the spent, refunded and `N` grant tallies, each
|
|
85
|
+
/// `N` fields, then the `N * N` marks.
|
|
86
|
+
pub const ENCODED_LEN: usize = HEADER + N * FIELD + (N + 2) * N * FIELD + N * N * MARK;
|
|
87
|
+
|
|
88
|
+
/// Writes this view into `out` and returns the number of bytes written.
|
|
89
|
+
/// Persist the frame before acting on the call that changed the state.
|
|
90
|
+
///
|
|
91
|
+
/// # Errors
|
|
92
|
+
///
|
|
93
|
+
/// [`Refusal::Truncated`] when `out` is shorter than
|
|
94
|
+
/// [`ENCODED_LEN`](Self::ENCODED_LEN), and nothing else: an `N` that does
|
|
95
|
+
/// not fit the frame's two-byte capacity field does not compile.
|
|
96
|
+
pub fn encode(&self, out: &mut [u8]) -> Result<usize, Refusal> {
|
|
97
|
+
const { assert!(N <= u16::MAX as usize, "the capacity must fit two bytes") };
|
|
98
|
+
let out = out.get_mut(..Self::ENCODED_LEN).ok_or(Refusal::Truncated)?;
|
|
99
|
+
let mut out = Writer { out, at: 0 };
|
|
100
|
+
out.put(&[TAG])?;
|
|
101
|
+
out.put_small(N)?;
|
|
102
|
+
out.put_small(self.replicas)?;
|
|
103
|
+
out.put_small(self.local.index())?;
|
|
104
|
+
for share in &self.allotted {
|
|
105
|
+
out.put(&share.to_le_bytes())?;
|
|
106
|
+
}
|
|
107
|
+
out.put_tally(&self.spent)?;
|
|
108
|
+
out.put_tally(&self.refunded)?;
|
|
109
|
+
for row in &self.grants {
|
|
110
|
+
out.put_tally(row)?;
|
|
111
|
+
}
|
|
112
|
+
for mark in self.marks.iter().flatten() {
|
|
113
|
+
let Mark { id, amount } = mark.unwrap_or(Mark { id: 0, amount: 0 });
|
|
114
|
+
out.put(&[u8::from(mark.is_some())])?;
|
|
115
|
+
out.put(&id.to_le_bytes())?;
|
|
116
|
+
out.put(&amount.to_le_bytes())?;
|
|
117
|
+
}
|
|
118
|
+
Ok(Self::ENCODED_LEN)
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/// Reads a view written by [`encode`](Self::encode).
|
|
122
|
+
///
|
|
123
|
+
/// # Errors
|
|
124
|
+
///
|
|
125
|
+
/// [`Refusal::Truncated`], [`Refusal::WrongStructure`], [`Refusal::WrongShape`]
|
|
126
|
+
/// for a frame of another capacity, or [`Refusal::Malformed`] for a frame
|
|
127
|
+
/// whose contents no sequence of calls could have produced.
|
|
128
|
+
pub fn decode(bytes: &[u8]) -> Result<Self, Refusal> {
|
|
129
|
+
let mut bytes = bytes.get(..Self::ENCODED_LEN).ok_or(Refusal::Truncated)?;
|
|
130
|
+
if take(&mut bytes, 1)? != [TAG] {
|
|
131
|
+
return Err(Refusal::WrongStructure);
|
|
132
|
+
}
|
|
133
|
+
if take_small(&mut bytes)? != N {
|
|
134
|
+
return Err(Refusal::WrongShape);
|
|
135
|
+
}
|
|
136
|
+
let replicas = take_small(&mut bytes)?;
|
|
137
|
+
// A local position past the capacity is not one `sound` can even
|
|
138
|
+
// look up: the frame is impossible.
|
|
139
|
+
let local = Member::new(take_small(&mut bytes)?).ok_or(Refusal::Malformed)?;
|
|
140
|
+
let mut allotted = [0; N];
|
|
141
|
+
for share in &mut allotted {
|
|
142
|
+
*share = take_u64(&mut bytes)?;
|
|
143
|
+
}
|
|
144
|
+
let spent = take_tally(&mut bytes)?;
|
|
145
|
+
let refunded = take_tally(&mut bytes)?;
|
|
146
|
+
let mut grants = [Tally::new(); N];
|
|
147
|
+
for row in &mut grants {
|
|
148
|
+
*row = take_tally(&mut bytes)?;
|
|
149
|
+
}
|
|
150
|
+
let mut marks = [[None; N]; N];
|
|
151
|
+
for mark in marks.iter_mut().flatten() {
|
|
152
|
+
let present = take(&mut bytes, 1)?;
|
|
153
|
+
let (id, amount) = (take_u64(&mut bytes)?, take_u64(&mut bytes)?);
|
|
154
|
+
*mark = match present {
|
|
155
|
+
[0] if id == 0 && amount == 0 => None,
|
|
156
|
+
[1] => Some(Mark { id, amount }),
|
|
157
|
+
_ => return Err(Refusal::Malformed),
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
let escrow = Self {
|
|
161
|
+
local,
|
|
162
|
+
replicas,
|
|
163
|
+
allotted,
|
|
164
|
+
spent,
|
|
165
|
+
refunded,
|
|
166
|
+
grants,
|
|
167
|
+
marks,
|
|
168
|
+
};
|
|
169
|
+
if escrow.sound() {
|
|
170
|
+
Ok(escrow)
|
|
171
|
+
} else {
|
|
172
|
+
Err(Refusal::Malformed)
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/// Whether some sequence of calls could have produced this state.
|
|
177
|
+
fn sound(&self) -> bool {
|
|
178
|
+
let members = (1..=N).contains(&self.replicas) && self.local.index() < self.replicas;
|
|
179
|
+
let supply = self
|
|
180
|
+
.allotted
|
|
181
|
+
.iter()
|
|
182
|
+
.try_fold(0_u64, |sum, share| sum.checked_add(*share));
|
|
183
|
+
members
|
|
184
|
+
&& supply.is_some()
|
|
185
|
+
&& self.allotted.iter().skip(self.replicas).all(|s| *s == 0)
|
|
186
|
+
&& self.spent.zero_from(self.replicas)
|
|
187
|
+
&& self.refunded.zero_from(self.replicas)
|
|
188
|
+
&& (0..self.replicas)
|
|
189
|
+
.filter_map(Member::new)
|
|
190
|
+
.all(|member| self.spends_paid_for(member))
|
|
191
|
+
&& self
|
|
192
|
+
.grants
|
|
193
|
+
.iter()
|
|
194
|
+
.zip(&self.marks)
|
|
195
|
+
.enumerate()
|
|
196
|
+
.all(|(from, (row, marks))| self.sound_row(from, row, marks))
|
|
197
|
+
&& (0..=i128::from(u64::MAX)).contains(&self.signed_balance(self.local))
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/// Whether `member`'s spent and refunded counters are ones its calls could
|
|
201
|
+
/// have reached, given its inflow: its allotment plus every grant this view
|
|
202
|
+
/// knows it received.
|
|
203
|
+
///
|
|
204
|
+
/// A replica spends only rights it holds, and refunds only its own spends,
|
|
205
|
+
/// so in its own history `spent - refunded <= inflow - given`, and nothing
|
|
206
|
+
/// was ever spent while the inflow was zero. Another view holds counters
|
|
207
|
+
/// joined from several of its versions, which may pair its latest spent
|
|
208
|
+
/// with a later outgoing grant, so `given` drops out; but the version that
|
|
209
|
+
/// carried the spent counter also carried its refunds and received grants,
|
|
210
|
+
/// and joins only raise those. What survives every join is exact: any
|
|
211
|
+
/// counters with `refunded <= spent`, `spent - refunded <= inflow` and
|
|
212
|
+
/// `spent == 0` when `inflow == 0` are reached by cycling spend 1 and
|
|
213
|
+
/// refund 1, then spending the rest. The local balance check covers
|
|
214
|
+
/// `given` for the local replica.
|
|
215
|
+
fn spends_paid_for(&self, member: Member<N>) -> bool {
|
|
216
|
+
let (spent, refunded) = (self.spent.count(member), self.refunded.count(member));
|
|
217
|
+
let inflow = self.inflow(member);
|
|
218
|
+
spent
|
|
219
|
+
.checked_sub(refunded)
|
|
220
|
+
.is_some_and(|outstanding| i128::from(outstanding) <= inflow)
|
|
221
|
+
&& (spent == 0 || inflow > 0)
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/// Whether row `from` grants only to other known replicas, and every
|
|
225
|
+
/// grant has the mark of the transfer that last raised it.
|
|
226
|
+
fn sound_row(&self, from: usize, row: &Tally<N>, marks: &[Option<Mark>; N]) -> bool {
|
|
227
|
+
let cells_known = row.zero_from(if from < self.replicas {
|
|
228
|
+
self.replicas
|
|
229
|
+
} else {
|
|
230
|
+
0
|
|
231
|
+
});
|
|
232
|
+
cells_known
|
|
233
|
+
&& marks
|
|
234
|
+
.iter()
|
|
235
|
+
.zip(row.counts())
|
|
236
|
+
.enumerate()
|
|
237
|
+
.all(|(to, (mark, granted))| {
|
|
238
|
+
mark.map_or(*granted == 0, |mark| {
|
|
239
|
+
from != to && mark.amount > 0 && mark.amount <= *granted
|
|
240
|
+
})
|
|
241
|
+
})
|
|
242
|
+
}
|
|
243
|
+
}
|