karma-cigarette 0.1.0

Deterministic karma ledgers and net settlement by the Cocoshiga principle
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//! Deterministic karma accounting and net settlement.
//!
//! The crate models the **Cocoshiga principle**: record contributions, cancel
//! reciprocal obligations, preserve every party's net position, and emit only
//! the transfers still required for settlement.
//!
//! A contribution from a giver to a receiver makes the giver a creditor and
//! the receiver a debtor by the recorded number of units.
//!
//! ```
//! use karma_cigarette::{Cocoshiga, KarmaLedger};
//!
//! let mut ledger = KarmaLedger::new();
//! ledger.record("aya", "ben", 8, "helped with a task")?;
//! ledger.record("ben", "aya", 3, "returned the favor")?;
//!
//! let plan = Cocoshiga::settle(&ledger)?;
//! assert_eq!(plan.transfers()[0].units(), 5);
//! assert!(plan.is_conserved());
//! # Ok::<(), karma_cigarette::KarmaError>(())
//! ```

use std::collections::BTreeMap;
use std::error::Error;
use std::fmt::{self, Display, Formatter};

/// A stable, non-empty identifier for a party in a ledger.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PartyId(String);

impl PartyId {
    /// Creates a validated party identifier.
    pub fn new(value: impl Into<String>) -> Result<Self, KarmaError> {
        let value = value.into();
        if value.trim().is_empty() {
            return Err(KarmaError::EmptyParty);
        }
        Ok(Self(value))
    }

    /// Returns the identifier as text.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl Display for PartyId {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl AsRef<str> for PartyId {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

/// One contribution recorded in a [`KarmaLedger`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct KarmaEntry {
    giver: PartyId,
    receiver: PartyId,
    units: u64,
    memo: String,
}

impl KarmaEntry {
    /// Creates and validates an entry.
    pub fn new(
        giver: impl Into<String>,
        receiver: impl Into<String>,
        units: u64,
        memo: impl Into<String>,
    ) -> Result<Self, KarmaError> {
        let giver = PartyId::new(giver)?;
        let receiver = PartyId::new(receiver)?;
        if giver == receiver {
            return Err(KarmaError::SameParty);
        }
        if units == 0 {
            return Err(KarmaError::ZeroUnits);
        }
        Ok(Self {
            giver,
            receiver,
            units,
            memo: memo.into(),
        })
    }

    /// The party that supplied the contribution.
    pub fn giver(&self) -> &PartyId {
        &self.giver
    }

    /// The party that received the contribution.
    pub fn receiver(&self) -> &PartyId {
        &self.receiver
    }

    /// The positive number of units transferred by the contribution.
    pub fn units(&self) -> u64 {
        self.units
    }

    /// Application-defined context attached to the entry.
    pub fn memo(&self) -> &str {
        &self.memo
    }
}

/// An append-only collection of karma entries.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct KarmaLedger {
    entries: Vec<KarmaEntry>,
}

impl KarmaLedger {
    /// Creates an empty ledger.
    pub const fn new() -> Self {
        Self {
            entries: Vec::new(),
        }
    }

    /// Records a validated contribution.
    pub fn record(
        &mut self,
        giver: impl Into<String>,
        receiver: impl Into<String>,
        units: u64,
        memo: impl Into<String>,
    ) -> Result<&KarmaEntry, KarmaError> {
        let entry = KarmaEntry::new(giver, receiver, units, memo)?;
        self.entries.push(entry);
        Ok(self
            .entries
            .last()
            .expect("an entry was inserted immediately before access"))
    }

    /// Appends a previously validated entry.
    pub fn push(&mut self, entry: KarmaEntry) -> &KarmaEntry {
        self.entries.push(entry);
        self.entries
            .last()
            .expect("an entry was inserted immediately before access")
    }

    /// Returns all entries in insertion order.
    pub fn entries(&self) -> &[KarmaEntry] {
        &self.entries
    }

    /// Returns whether no contributions have been recorded.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Returns the number of recorded contributions.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Computes each party's net position.
    ///
    /// Positive values are receivables and negative values are payables.
    pub fn balances(&self) -> Result<BTreeMap<PartyId, i128>, KarmaError> {
        let mut balances = BTreeMap::<PartyId, i128>::new();
        for entry in &self.entries {
            let units = i128::from(entry.units);
            add_balance(&mut balances, &entry.giver, units)?;
            add_balance(&mut balances, &entry.receiver, -units)?;
        }
        Ok(balances)
    }

    /// Returns one party's net position, or zero when the party is absent.
    pub fn balance_of(&self, party: &str) -> Result<i128, KarmaError> {
        Ok(self
            .balances()?
            .into_iter()
            .find_map(|(id, balance)| (id.as_str() == party).then_some(balance))
            .unwrap_or(0))
    }
}

fn add_balance(
    balances: &mut BTreeMap<PartyId, i128>,
    party: &PartyId,
    delta: i128,
) -> Result<(), KarmaError> {
    let current = balances.entry(party.clone()).or_default();
    *current = current.checked_add(delta).ok_or(KarmaError::Overflow)?;
    Ok(())
}

/// A payment required to satisfy a net karma position.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SettlementTransfer {
    from: PartyId,
    to: PartyId,
    units: u128,
}

impl SettlementTransfer {
    /// Party that should pay.
    pub fn from(&self) -> &PartyId {
        &self.from
    }

    /// Party that should receive.
    pub fn to(&self) -> &PartyId {
        &self.to
    }

    /// Number of units to transfer.
    pub fn units(&self) -> u128 {
        self.units
    }
}

/// A deterministic settlement plan produced from a ledger.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct SettlementPlan {
    transfers: Vec<SettlementTransfer>,
    original_balances: BTreeMap<PartyId, i128>,
}

impl SettlementPlan {
    /// Required transfers in deterministic party order.
    pub fn transfers(&self) -> &[SettlementTransfer] {
        &self.transfers
    }

    /// Sum of all units moved by the plan.
    pub fn total_units(&self) -> u128 {
        self.transfers.iter().map(SettlementTransfer::units).sum()
    }

    /// Returns whether applying the plan clears every original balance.
    pub fn is_conserved(&self) -> bool {
        let mut balances = self.original_balances.clone();
        for transfer in &self.transfers {
            let Ok(units) = i128::try_from(transfer.units) else {
                return false;
            };
            let Some(from) = balances
                .get(&transfer.from)
                .and_then(|value| value.checked_add(units))
            else {
                return false;
            };
            let Some(to) = balances
                .get(&transfer.to)
                .and_then(|value| value.checked_sub(units))
            else {
                return false;
            };
            balances.insert(transfer.from.clone(), from);
            balances.insert(transfer.to.clone(), to);
        }
        balances.values().all(|&balance| balance == 0)
    }
}

/// Implements the Cocoshiga net-settlement principle.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Cocoshiga;

impl Cocoshiga {
    /// Nets reciprocal and transitive obligations into a settlement plan.
    ///
    /// Parties are processed in lexicographic order, so identical ledgers
    /// always yield identical plans.
    pub fn settle(ledger: &KarmaLedger) -> Result<SettlementPlan, KarmaError> {
        let balances = ledger.balances()?;
        let sum = balances.values().try_fold(0i128, |total, &balance| {
            total.checked_add(balance).ok_or(KarmaError::Overflow)
        })?;
        if sum != 0 {
            return Err(KarmaError::Unbalanced);
        }

        let mut debtors: Vec<(PartyId, u128)> = balances
            .iter()
            .filter(|&(_, &balance)| balance < 0)
            .map(|(party, &balance)| (party.clone(), balance.unsigned_abs()))
            .collect();
        let mut creditors: Vec<(PartyId, u128)> = balances
            .iter()
            .filter(|&(_, &balance)| balance > 0)
            .map(|(party, &balance)| (party.clone(), balance as u128))
            .collect();

        let mut transfers = Vec::new();
        let (mut debtor_index, mut creditor_index) = (0usize, 0usize);
        while debtor_index < debtors.len() && creditor_index < creditors.len() {
            let units = debtors[debtor_index].1.min(creditors[creditor_index].1);
            transfers.push(SettlementTransfer {
                from: debtors[debtor_index].0.clone(),
                to: creditors[creditor_index].0.clone(),
                units,
            });
            debtors[debtor_index].1 -= units;
            creditors[creditor_index].1 -= units;
            if debtors[debtor_index].1 == 0 {
                debtor_index += 1;
            }
            if creditors[creditor_index].1 == 0 {
                creditor_index += 1;
            }
        }

        let plan = SettlementPlan {
            transfers,
            original_balances: balances,
        };
        if !plan.is_conserved() {
            return Err(KarmaError::Unbalanced);
        }
        Ok(plan)
    }
}

/// Validation and arithmetic failures returned by the crate.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum KarmaError {
    /// A party identifier is empty or whitespace-only.
    EmptyParty,
    /// Giver and receiver are the same party.
    SameParty,
    /// An entry has no units.
    ZeroUnits,
    /// A checked arithmetic operation overflowed.
    Overflow,
    /// A settlement failed the conservation invariant.
    Unbalanced,
}

impl Display for KarmaError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::EmptyParty => "party identifiers cannot be empty",
            Self::SameParty => "giver and receiver must be different parties",
            Self::ZeroUnits => "karma units must be greater than zero",
            Self::Overflow => "karma balance overflowed",
            Self::Unbalanced => "settlement does not conserve all balances",
        })
    }
}

impl Error for KarmaError {}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn reciprocal_karma_is_netted() {
        let mut ledger = KarmaLedger::new();
        ledger.record("alice", "bob", 10, "lunch").unwrap();
        ledger.record("bob", "alice", 4, "coffee").unwrap();

        let plan = Cocoshiga::settle(&ledger).unwrap();
        assert_eq!(
            plan.transfers(),
            &[SettlementTransfer {
                from: PartyId::new("bob").unwrap(),
                to: PartyId::new("alice").unwrap(),
                units: 6,
            }]
        );
        assert!(plan.is_conserved());
    }

    #[test]
    fn transitive_karma_becomes_one_transfer() {
        let mut ledger = KarmaLedger::new();
        ledger.record("alice", "bob", 7, "").unwrap();
        ledger.record("bob", "carol", 7, "").unwrap();

        let plan = Cocoshiga::settle(&ledger).unwrap();
        assert_eq!(plan.transfers().len(), 1);
        assert_eq!(plan.transfers()[0].from().as_str(), "carol");
        assert_eq!(plan.transfers()[0].to().as_str(), "alice");
        assert_eq!(plan.transfers()[0].units(), 7);
    }

    #[test]
    fn settlement_is_deterministic_and_conserved() {
        let mut ledger = KarmaLedger::new();
        ledger.record("d", "a", 8, "").unwrap();
        ledger.record("c", "b", 5, "").unwrap();
        ledger.record("a", "c", 2, "").unwrap();

        let first = Cocoshiga::settle(&ledger).unwrap();
        let second = Cocoshiga::settle(&ledger).unwrap();
        assert_eq!(first, second);
        assert!(first.is_conserved());
    }

    #[test]
    fn invalid_entries_do_not_mutate_the_ledger() {
        let mut ledger = KarmaLedger::new();
        assert_eq!(
            ledger.record("", "bob", 1, "").unwrap_err(),
            KarmaError::EmptyParty
        );
        assert_eq!(
            ledger.record("alice", "alice", 1, "").unwrap_err(),
            KarmaError::SameParty
        );
        assert_eq!(
            ledger.record("alice", "bob", 0, "").unwrap_err(),
            KarmaError::ZeroUnits
        );
        assert!(ledger.is_empty());
    }

    #[test]
    fn empty_ledger_has_an_empty_valid_plan() {
        let plan = Cocoshiga::settle(&KarmaLedger::new()).unwrap();
        assert!(plan.transfers().is_empty());
        assert_eq!(plan.total_units(), 0);
        assert!(plan.is_conserved());
    }
}