Skip to main content

qualia_core_db/net/qdnf/economics/
reserve.rs

1//! Reserve A against remaining T − S − W − H (E17.4–E17.5). Quote O/F/A stay split.
2
3use crate::net::qdnf::errors::QdnfError;
4use crate::net::qdnf::types::StrongDigest;
5
6use super::classify::{recovery_for_class, ActingClass};
7use super::obligation::{remaining_recovery, Obligation, OpState};
8
9/// Operating cost O, fees F and positive recovery A are independent amounts.
10#[repr(C)]
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub struct Quote {
13    pub operating_o: u64,
14    pub fees_f: u64,
15    pub recovery_a: u64,
16}
17
18impl Quote {
19    pub const ZERO: Self = Self {
20        operating_o: 0,
21        fees_f: 0,
22        recovery_a: 0,
23    };
24}
25
26/// Reserve A = min(quote_a, remaining after class). Duplicate `op_id` is idempotent.
27///
28/// Overflow of S+W+H+A or A that would exceed T is Denied. Offline allotment uses
29/// the same remaining cap.
30pub fn reserve_hold(
31    ob: &mut Obligation,
32    quote_a: u64,
33    class: ActingClass,
34    op_id: StrongDigest,
35) -> Result<u64, QdnfError> {
36    if op_id.is_zero() {
37        return Err(QdnfError::Malformed);
38    }
39    if let Some(i) = ob.find_op(op_id) {
40        let rec = ob.ops[i];
41        return match rec.state {
42            OpState::Held | OpState::Finalised => Ok(rec.amount),
43            OpState::Cancelled | OpState::Reversed => Err(QdnfError::Conflict),
44            OpState::Empty => Err(QdnfError::Incomplete),
45        };
46    }
47    let remaining = remaining_recovery(ob)?;
48    let recoverable = recovery_for_class(class, ob.fulfilled, remaining);
49    let amount = quote_a.min(recoverable);
50    if quote_a > 0 && amount == 0 && recoverable == 0 && !ob.fulfilled {
51        if matches!(class, ActingClass::Corporate) {
52            return Err(QdnfError::Denied);
53        }
54        return Ok(0);
55    }
56    if amount == 0 {
57        return Ok(0);
58    }
59    let used = ob
60        .settled_s
61        .checked_add(ob.discharged_w)
62        .and_then(|x| x.checked_add(ob.holds_h))
63        .and_then(|x| x.checked_add(amount))
64        .ok_or(QdnfError::Denied)?;
65    if used > ob.target_t {
66        return Err(QdnfError::Denied);
67    }
68    ob.insert_op(op_id, amount, OpState::Held)?;
69    ob.holds_h = ob.holds_h.checked_add(amount).ok_or(QdnfError::Denied)?;
70    ob.bump_revision()?;
71    Ok(amount)
72}
73
74/// Finite offline allotment: cannot exceed remaining. Same owner and remaining cap.
75#[inline]
76pub fn allot_offline(
77    ob: &mut Obligation,
78    amount: u64,
79    class: ActingClass,
80    op_id: StrongDigest,
81) -> Result<u64, QdnfError> {
82    reserve_hold(ob, amount, class, op_id)
83}
84
85/// Release a live hold. Duplicate cancel is idempotent.
86pub fn cancel(ob: &mut Obligation, op_id: StrongDigest) -> Result<(), QdnfError> {
87    let i = ob.find_op(op_id).ok_or(QdnfError::Incomplete)?;
88    match ob.ops[i].state {
89        OpState::Held => {
90            let amt = ob.ops[i].amount;
91            ob.holds_h = ob.holds_h.checked_sub(amt).ok_or(QdnfError::Range)?;
92            ob.ops[i].state = OpState::Cancelled;
93            ob.bump_revision()
94        }
95        OpState::Cancelled => Ok(()),
96        OpState::Empty => Err(QdnfError::Incomplete),
97        OpState::Finalised | OpState::Reversed => Err(QdnfError::Denied),
98    }
99}
100
101/// Hold expiry follows the same release as cancel.
102#[inline]
103pub fn expire(ob: &mut Obligation, op_id: StrongDigest) -> Result<(), QdnfError> {
104    cancel(ob, op_id)
105}
106
107#[cfg(test)]
108mod tests {
109    use super::*;
110    use crate::crypto::network::digest::sha384;
111    use crate::net::qdnf::authority::CompensationClass;
112    use crate::net::qdnf::economics::obligation::remaining_recovery;
113    use crate::net::qdnf::economics::RemainingTarget;
114    use std::sync::{Arc, Mutex};
115    use std::thread;
116
117    fn open(t: u64) -> Obligation {
118        Obligation::open(sha384(b"reserve-ob"), t).unwrap()
119    }
120
121    fn op(tag: u8) -> StrongDigest {
122        sha384(&[tag])
123    }
124
125    #[test]
126    fn econ_c_reserve_finalise_duplicate_and_cancel() {
127        let mut ob = open(10);
128        let q = Quote {
129            operating_o: 4,
130            fees_f: 1,
131            recovery_a: 3,
132        };
133        let held = reserve_hold(&mut ob, q.recovery_a, ActingClass::Corporate, op(1)).unwrap();
134        assert_eq!(held, 3);
135        assert_eq!(ob.holds_h, 3);
136        assert_eq!(remaining_recovery(&ob).unwrap(), 7);
137        assert_eq!(
138            reserve_hold(&mut ob, 99, ActingClass::Corporate, op(1)).unwrap(),
139            3
140        );
141        assert_eq!(ob.holds_h, 3);
142        assert_eq!(ob.revision, 1);
143        cancel(&mut ob, op(1)).unwrap();
144        assert_eq!(ob.holds_h, 0);
145        expire(&mut ob, op(1)).unwrap();
146        let t = RemainingTarget {
147            milli_units: 10,
148            class: CompensationClass::CorporateDelegated,
149        };
150        let mixed = q.operating_o + q.fees_f + q.recovery_a;
151        assert_eq!(t.apply_payment(mixed), Err(QdnfError::Denied));
152    }
153
154    #[test]
155    fn exemption_reserve_is_zero_and_does_not_hold() {
156        let mut ob = open(10);
157        assert_eq!(
158            reserve_hold(&mut ob, 5, ActingClass::Personal, op(2)).unwrap(),
159            0
160        );
161        assert_eq!(
162            reserve_hold(&mut ob, 5, ActingClass::Humanitarian, op(3)).unwrap(),
163            0
164        );
165        assert_eq!(ob.holds_h, 0);
166        assert_eq!(remaining_recovery(&ob).unwrap(), 10);
167    }
168
169    #[test]
170    fn econ_d_last_unit_race_only_one_succeeds() {
171        let mut ob = open(1);
172        let a = reserve_hold(&mut ob, 1, ActingClass::Corporate, op(10));
173        let b = reserve_hold(&mut ob, 1, ActingClass::Corporate, op(11));
174        assert_eq!(a, Ok(1));
175        assert_eq!(b, Err(QdnfError::Denied));
176        assert_eq!(ob.holds_h, 1);
177        assert!(!ob.fulfilled);
178    }
179
180    #[test]
181    fn econ_d_threaded_last_unit_race() {
182        let ob = Arc::new(Mutex::new(open(1)));
183        let left = {
184            let ob = Arc::clone(&ob);
185            thread::spawn(move || {
186                reserve_hold(&mut ob.lock().unwrap(), 1, ActingClass::Corporate, op(20))
187            })
188        };
189        let right = {
190            let ob = Arc::clone(&ob);
191            thread::spawn(move || {
192                reserve_hold(&mut ob.lock().unwrap(), 1, ActingClass::Corporate, op(21))
193            })
194        };
195        let ra = left.join().unwrap();
196        let rb = right.join().unwrap();
197        let wins = [ra, rb].iter().filter(|r| **r == Ok(1)).count();
198        let denied = [ra, rb]
199            .iter()
200            .filter(|r| **r == Err(QdnfError::Denied))
201            .count();
202        assert_eq!(wins, 1);
203        assert_eq!(denied, 1);
204        assert_eq!(ob.lock().unwrap().holds_h, 1);
205    }
206
207    #[test]
208    fn offline_allotment_cannot_exceed_remaining() {
209        let mut ob = open(2);
210        assert_eq!(
211            allot_offline(&mut ob, 2, ActingClass::Corporate, op(30)).unwrap(),
212            2
213        );
214        assert_eq!(
215            allot_offline(&mut ob, 1, ActingClass::Corporate, op(31)),
216            Err(QdnfError::Denied)
217        );
218    }
219
220    #[test]
221    fn zero_op_id_is_malformed() {
222        let mut ob = open(1);
223        assert_eq!(
224            reserve_hold(&mut ob, 1, ActingClass::Corporate, StrongDigest::ZERO),
225            Err(QdnfError::Malformed)
226        );
227    }
228}