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.
@@ -0,0 +1,180 @@
1
+ //! What a replica does with its own rights: spend, refund, transfer, accept.
2
+
3
+ use crate::{Accepted, Escrow, Mark, Receipt, Refusal, ReplicaId, Transfer};
4
+
5
+ impl<const N: usize> Escrow<N> {
6
+ /// Spends `amount` of the local replica's rights and returns what it has
7
+ /// left.
8
+ ///
9
+ /// # Errors
10
+ ///
11
+ /// [`Refusal::ZeroAmount`], [`Refusal::Insufficient`] when the local
12
+ /// replica holds less than `amount` (rights held elsewhere do not count),
13
+ /// or [`Refusal::Overflow`] when the lifetime spent counter is exhausted.
14
+ /// The state is untouched on refusal.
15
+ pub fn spend(&mut self, amount: u64) -> Result<u64, Refusal> {
16
+ if amount == 0 {
17
+ return Err(Refusal::ZeroAmount);
18
+ }
19
+ let available = self.available();
20
+ let left = available
21
+ .checked_sub(amount)
22
+ .ok_or(Refusal::Insufficient { available })?;
23
+ self.spent.raise(self.local, amount)?;
24
+ Ok(left)
25
+ }
26
+
27
+ /// Returns `amount` of the local replica's own spends to its balance and
28
+ /// returns what it now holds.
29
+ ///
30
+ /// # Errors
31
+ ///
32
+ /// [`Refusal::ZeroAmount`], [`Refusal::ExceedsSpent`] when `amount` is more
33
+ /// than the local replica has spent and not yet refunded (a refund never
34
+ /// mints), or [`Refusal::Overflow`] when the local balance would pass
35
+ /// [`u64::MAX`] or the lifetime refunded counter is exhausted. The state
36
+ /// is untouched on refusal.
37
+ pub fn refund(&mut self, amount: u64) -> Result<u64, Refusal> {
38
+ if amount == 0 {
39
+ return Err(Refusal::ZeroAmount);
40
+ }
41
+ let outstanding = self.outstanding_of(self.local);
42
+ if amount > outstanding {
43
+ return Err(Refusal::ExceedsSpent { outstanding });
44
+ }
45
+ // Rights received after the spend can already fill the balance, so the
46
+ // refund is checked against it, not only against the counter.
47
+ let held = self
48
+ .available()
49
+ .checked_add(amount)
50
+ .ok_or(Refusal::Overflow)?;
51
+ self.refunded.raise(self.local, amount)?;
52
+ Ok(held)
53
+ }
54
+
55
+ /// Moves `amount` of the local replica's rights to `to` under transfer
56
+ /// `id`.
57
+ ///
58
+ /// Ids are chosen by the caller and must strictly increase per
59
+ /// destination. Asking again with the latest id and the same amount moves
60
+ /// nothing and returns the original receipt as [`Transfer::Replayed`].
61
+ ///
62
+ /// # Errors
63
+ ///
64
+ /// [`Refusal::ZeroAmount`], [`Refusal::UnknownReplica`],
65
+ /// [`Refusal::SelfTransfer`], [`Refusal::StaleId`] for an id older than the
66
+ /// latest, [`Refusal::IdConflict`] for the latest id with another amount,
67
+ /// [`Refusal::Insufficient`], or [`Refusal::Overflow`] when the lifetime
68
+ /// grant counter for the pair is exhausted. The state is untouched on
69
+ /// refusal.
70
+ pub fn transfer(&mut self, to: ReplicaId, id: u64, amount: u64) -> Result<Transfer, Refusal> {
71
+ if amount == 0 {
72
+ return Err(Refusal::ZeroAmount);
73
+ }
74
+ let slot = self.index(to).ok_or(Refusal::UnknownReplica)?;
75
+ if slot == self.local {
76
+ return Err(Refusal::SelfTransfer);
77
+ }
78
+ let from = self.local();
79
+ let available = self.available();
80
+ let row = self.local.of_mut(&mut self.grants);
81
+ let mark_cell = slot.of_mut(self.local.of_mut(&mut self.marks));
82
+ let granted = row.count(slot);
83
+ if let Some(mark) = *mark_cell {
84
+ if id < mark.id {
85
+ return Err(Refusal::StaleId { latest: mark.id });
86
+ }
87
+ if id == mark.id {
88
+ if amount != mark.amount {
89
+ return Err(Refusal::IdConflict {
90
+ amount: mark.amount,
91
+ });
92
+ }
93
+ return Ok(Transfer::Replayed(Receipt {
94
+ from,
95
+ to,
96
+ id,
97
+ amount,
98
+ total: granted,
99
+ }));
100
+ }
101
+ }
102
+ if amount > available {
103
+ return Err(Refusal::Insufficient { available });
104
+ }
105
+ let total = row.raise(slot, amount)?;
106
+ *mark_cell = Some(Mark { id, amount });
107
+ Ok(Transfer::Applied(Receipt {
108
+ from,
109
+ to,
110
+ id,
111
+ amount,
112
+ total,
113
+ }))
114
+ }
115
+
116
+ /// Learns of a transfer from its receipt, without a full merge.
117
+ ///
118
+ /// Receipts are cumulative: one that is older than what this view already
119
+ /// knows, or the same, is [`Accepted::Replayed`] and changes nothing.
120
+ ///
121
+ /// # Errors
122
+ ///
123
+ /// [`Refusal::UnknownReplica`], [`Refusal::Malformed`] for a receipt that
124
+ /// contradicts the grants already seen for the pair (a [`Receipt`] cannot
125
+ /// contradict itself), [`Refusal::IdConflict`] for a known id
126
+ /// with another amount, [`Refusal::Forged`] for a grant the local replica
127
+ /// would have had to make and did not, or [`Refusal::Overflow`] when the
128
+ /// local balance would pass [`u64::MAX`]. The state is untouched on
129
+ /// refusal.
130
+ pub fn accept(&mut self, receipt: &Receipt) -> Result<Accepted, Refusal> {
131
+ let from = self.index(receipt.from).ok_or(Refusal::UnknownReplica)?;
132
+ let to = self.index(receipt.to).ok_or(Refusal::UnknownReplica)?;
133
+ let local = self.local;
134
+ let available = self.available();
135
+ let row = from.of_mut(&mut self.grants);
136
+ let mark_cell = to.of_mut(from.of_mut(&mut self.marks));
137
+ let held = row.count(to);
138
+ let known = *mark_cell;
139
+ let fresh = match known {
140
+ Some(mark) if receipt.id == mark.id => {
141
+ if receipt.amount != mark.amount {
142
+ return Err(Refusal::IdConflict {
143
+ amount: mark.amount,
144
+ });
145
+ }
146
+ if receipt.total != held {
147
+ return Err(Refusal::Malformed);
148
+ }
149
+ false
150
+ }
151
+ Some(mark) if receipt.id < mark.id => {
152
+ if receipt.total > held.saturating_sub(mark.amount) {
153
+ return Err(Refusal::Malformed);
154
+ }
155
+ false
156
+ }
157
+ None | Some(_) => true,
158
+ };
159
+ if !fresh {
160
+ return Ok(Accepted::Replayed);
161
+ }
162
+ if from == local {
163
+ return Err(Refusal::Forged);
164
+ }
165
+ let raise = receipt
166
+ .total
167
+ .checked_sub(held)
168
+ .filter(|raise| *raise >= receipt.amount)
169
+ .ok_or(Refusal::Malformed)?;
170
+ if to == local && available.checked_add(raise).is_none() {
171
+ return Err(Refusal::Overflow);
172
+ }
173
+ row.raise(to, raise)?;
174
+ *mark_cell = Some(Mark {
175
+ id: receipt.id,
176
+ amount: receipt.amount,
177
+ });
178
+ Ok(Accepted::Applied)
179
+ }
180
+ }
@@ -0,0 +1,108 @@
1
+ //! The per-replica tables escrow keeps, and the index that reads them.
2
+ //!
3
+ //! Replica ids here are dense, `0..replicas` with `replicas <= N`, so every
4
+ //! table is a plain `[T; N]` and every lookup goes through a [`Member`], which
5
+ //! is below `N` by construction. A lookup therefore cannot miss, and no
6
+ //! caller has a "missing row" arm to answer.
7
+
8
+ use crate::Refusal;
9
+ use merge_machines::ReplicaId;
10
+
11
+ /// A position below `N` in a `[T; N]` table.
12
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
13
+ pub struct Member<const N: usize>(usize);
14
+
15
+ impl<const N: usize> Member<N> {
16
+ /// The position `index`, or `None` at `N` or past it.
17
+ pub const fn new(index: usize) -> Option<Self> {
18
+ if index < N { Some(Self(index)) } else { None }
19
+ }
20
+
21
+ /// The position as a table index.
22
+ pub const fn index(self) -> usize {
23
+ self.0
24
+ }
25
+
26
+ /// The replica id this position holds the cells of.
27
+ pub const fn id(self) -> ReplicaId {
28
+ self.0 as ReplicaId
29
+ }
30
+
31
+ /// `table`'s cell for this member.
32
+ // In bounds by construction: `new` is the only way in and answers only
33
+ // below `N`, the table's length.
34
+ #[allow(clippy::indexing_slicing)]
35
+ pub const fn of<T>(self, table: &[T; N]) -> &T {
36
+ &table[self.0]
37
+ }
38
+
39
+ /// `table`'s cell for this member, to write.
40
+ // In bounds for the same reason as `of`.
41
+ #[allow(clippy::indexing_slicing)]
42
+ pub const fn of_mut<T>(self, table: &mut [T; N]) -> &mut T {
43
+ &mut table[self.0]
44
+ }
45
+ }
46
+
47
+ /// A grow-only count per member, joined cell by cell with `max`.
48
+ ///
49
+ /// Unlike a slot-table counter, it holds a cell for every position up front,
50
+ /// so raising a member's count never needs a free slot: the only refusal is
51
+ /// passing [`u64::MAX`].
52
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
53
+ pub struct Tally<const N: usize>([u64; N]);
54
+
55
+ impl<const N: usize> Tally<N> {
56
+ /// Zero for every member.
57
+ pub const fn new() -> Self {
58
+ Self([0; N])
59
+ }
60
+
61
+ /// A tally holding exactly `counts`, as a frame stores it.
62
+ pub const fn from_counts(counts: [u64; N]) -> Self {
63
+ Self(counts)
64
+ }
65
+
66
+ /// Every cell, member order.
67
+ pub const fn counts(&self) -> &[u64; N] {
68
+ &self.0
69
+ }
70
+
71
+ /// What `member` has counted.
72
+ pub const fn count(&self, member: Member<N>) -> u64 {
73
+ *member.of(&self.0)
74
+ }
75
+
76
+ /// Every cell added up, wide enough never to clamp: at most `N` terms of
77
+ /// at most [`u64::MAX`].
78
+ pub fn total(&self) -> i128 {
79
+ self.0.iter().map(|count| i128::from(*count)).sum()
80
+ }
81
+
82
+ /// Raises `member`'s count by `amount` and answers the new count.
83
+ ///
84
+ /// # Errors
85
+ ///
86
+ /// [`Refusal::Overflow`] when the count would pass [`u64::MAX`]; the
87
+ /// tally is unchanged.
88
+ pub fn raise(&mut self, member: Member<N>, amount: u64) -> Result<u64, Refusal> {
89
+ let cell = member.of_mut(&mut self.0);
90
+ *cell = cell.checked_add(amount).ok_or(Refusal::Overflow)?;
91
+ Ok(*cell)
92
+ }
93
+
94
+ /// Folds `other` in: each cell becomes the larger of the two.
95
+ pub fn join(&mut self, other: &Self) {
96
+ for (mine, theirs) in self.0.iter_mut().zip(&other.0) {
97
+ *mine = (*mine).max(*theirs);
98
+ }
99
+ }
100
+
101
+ /// Whether every cell at or past position `len` is zero.
102
+ pub fn zero_from(&self, len: usize) -> bool {
103
+ self.0.iter().skip(len).all(|count| *count == 0)
104
+ }
105
+ }
106
+
107
+ #[cfg(test)]
108
+ mod tests;
@@ -0,0 +1,2 @@
1
+ # frozen_string_literal: true
2
+ require_relative 'ffi/extconf'
@@ -0,0 +1,21 @@
1
+ [package]
2
+ name = "escrow_machines_native"
3
+ version = "0.1.6"
4
+ edition.workspace = true
5
+ rust-version.workspace = true
6
+ license.workspace = true
7
+ publish = false
8
+
9
+ [lib]
10
+ crate-type = ["cdylib"]
11
+ test = false
12
+ doctest = false
13
+
14
+ [dependencies]
15
+ escrow-machines.workspace = true
16
+ magnus.workspace = true
17
+ rb-sys.workspace = true
18
+ matryona-machines = { workspace = true, features = ["ruby"] }
19
+
20
+ [lints]
21
+ workspace = true
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+ require 'mkmf'
3
+ require 'pathname'
4
+ require 'rb_sys/mkmf'
5
+
6
+ create_rust_makefile('escrow_machines_native/escrow_machines_native') do |e|
7
+ e.ext_dir = Pathname(__dir__).relative_path_from(Pathname(Dir.pwd)).to_s
8
+ e.profile = ENV.fetch('RB_SYS_CARGO_PROFILE', :release).to_sym
9
+ end
10
+ makefile = File.join(Dir.pwd, 'Makefile')
11
+ File.write(makefile, File.read(makefile).gsub(
12
+ /^RB_SYS_CARGO_MANIFEST_DIR \?=.*$/,
13
+ "RB_SYS_CARGO_MANIFEST_DIR ?= #{File.expand_path(__dir__)}"
14
+ ))
@@ -0,0 +1,70 @@
1
+ //! Private native entry point, and the `Data` classes the binding builds and
2
+ //! checks, resolved once here so no call looks a constant up by name.
3
+ use crate::{CAPACITY, Core, Wrapper, checked_mark, checked_receipt, checked_transfer};
4
+ use magnus::{Error, RClass, RModule, Ruby, function, method, prelude::*};
5
+ use matryona_machines::ruby::Class;
6
+
7
+ /// The value classes `lib/escrow_machines.rb` defines before this loads.
8
+ pub struct Classes {
9
+ pub receipt: Class,
10
+ pub applied: Class,
11
+ pub replayed: Class,
12
+ pub mark: Class,
13
+ pub escrow: Class,
14
+ }
15
+
16
+ matryona_machines::registry! {
17
+ static CLASSES: Classes = "escrow_machines";
18
+ /// The classes resolved at init.
19
+ pub fn classes;
20
+ }
21
+
22
+ /// Resolves and pins the value classes, and pins `escrow`, which init
23
+ /// defined, fixing magnus's class for `Wrapper` to it: building an escrow
24
+ /// never runs `Object.const_get`. Called once, from init, after the escrow's
25
+ /// methods are defined.
26
+ fn resolve(ruby: &Ruby, module: RModule, escrow: RClass) -> Result<(), Error> {
27
+ let transfer: RModule = module.const_get("Transfer")?;
28
+ let classes = Classes {
29
+ receipt: Class::resolve(ruby, module, "Receipt")?,
30
+ applied: Class::resolve(ruby, transfer, "Applied")?,
31
+ replayed: Class::resolve(ruby, transfer, "Replayed")?,
32
+ mark: Class::resolve(ruby, module, "Mark")?,
33
+ escrow: Class::pin_wrapped::<Wrapper>(ruby, escrow)?,
34
+ };
35
+ CLASSES.set(ruby, classes).map(drop)
36
+ }
37
+
38
+ #[magnus::init]
39
+ fn init(ruby: &Ruby) -> Result<(), Error> {
40
+ let module = ruby.define_module("EscrowMachines")?;
41
+ module.const_set("CAPACITY", CAPACITY)?;
42
+ module.define_singleton_method("__receipt", function!(checked_receipt, 5))?;
43
+ module.define_singleton_method("__mark", function!(checked_mark, 2))?;
44
+ module.define_singleton_method("__transfer", function!(checked_transfer, 1))?;
45
+ let class = module.define_class("Escrow", ruby.class_object())?;
46
+ class.undef_default_alloc_func();
47
+ class.const_set("ENCODED_LEN", Core::ENCODED_LEN)?;
48
+ class.define_singleton_method("new", function!(Wrapper::new, 2))?;
49
+ class.define_singleton_method("decode", function!(Wrapper::decode, 1))?;
50
+ class.define_method("encode", method!(Wrapper::encode, 0))?;
51
+ class.define_method("spend", method!(Wrapper::spend, 1))?;
52
+ class.define_method("refund", method!(Wrapper::refund, 1))?;
53
+ class.define_method("transfer", method!(Wrapper::transfer, 3))?;
54
+ class.define_method("accept", method!(Wrapper::accept, 1))?;
55
+ class.define_method("merge", method!(Wrapper::merge, 1))?;
56
+ class.define_method("recover", method!(Wrapper::recover, 1))?;
57
+ class.define_method("local", method!(Wrapper::local, 0))?;
58
+ class.define_method("replicas", method!(Wrapper::replicas, 0))?;
59
+ class.define_method("capacity", method!(Wrapper::capacity, 0))?;
60
+ class.define_method("supply", method!(Wrapper::supply, 0))?;
61
+ class.define_method("available", method!(Wrapper::available, 0))?;
62
+ class.define_method("allotted", method!(Wrapper::allotted, 1))?;
63
+ class.define_method("balance", method!(Wrapper::balance, 1))?;
64
+ class.define_method("spent", method!(Wrapper::spent, 1))?;
65
+ class.define_method("refunded", method!(Wrapper::refunded, 1))?;
66
+ class.define_method("outstanding", method!(Wrapper::outstanding, 1))?;
67
+ class.define_method("granted", method!(Wrapper::granted, 2))?;
68
+ class.define_method("last_transfer", method!(Wrapper::last_transfer, 2))?;
69
+ resolve(ruby, module, class)
70
+ }