qualia_core_db/net/qdnf/economics/
roles.rs1use crate::net::peer::runtime::ResourceBudget;
4use crate::net::qdnf::errors::QdnfError;
5use crate::net::qdnf::types::StrongDigest;
6
7#[repr(u8)]
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
10pub enum FundedRole {
11 Routing = 1,
12 Relay = 2,
13 Resolution = 3,
14 Custody = 4,
15 Storage = 5,
16 Compute = 6,
17}
18
19#[repr(C)]
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22pub struct RoleGrant {
23 pub role: FundedRole,
24 pub budget: ResourceBudget,
25 pub funding_source: StrongDigest,
26}
27
28pub fn activate_role(
30 role: FundedRole,
31 budget: ResourceBudget,
32 funding_source: StrongDigest,
33) -> Result<RoleGrant, QdnfError> {
34 if funding_source.is_zero() {
35 return Err(QdnfError::Malformed);
36 }
37 Ok(RoleGrant {
38 role,
39 budget,
40 funding_source,
41 })
42}
43
44#[inline]
46pub fn natural_person_wallet_required() -> bool {
47 false
48}
49
50pub fn role_admits_router(grant: &RoleGrant) -> Result<(), QdnfError> {
52 if grant.role != FundedRole::Routing {
53 return Err(QdnfError::Denied);
54 }
55 if grant.funding_source.is_zero() {
56 return Err(QdnfError::Malformed);
57 }
58 if grant.budget.bytes == 0 && grant.budget.work == 0 && grant.budget.io == 0 {
59 return Err(QdnfError::BudgetExhausted);
60 }
61 Ok(())
62}
63
64#[cfg(test)]
65mod tests {
66 use super::*;
67 use crate::crypto::network::digest::sha384;
68
69 #[test]
70 fn zero_funding_source_is_malformed() {
71 let budget = ResourceBudget {
72 bytes: 64,
73 work: 1,
74 io: 1,
75 };
76 assert_eq!(
77 activate_role(FundedRole::Routing, budget, StrongDigest::ZERO),
78 Err(QdnfError::Malformed)
79 );
80 let grant = activate_role(FundedRole::Relay, budget, sha384(b"commons-fund")).unwrap();
81 assert_eq!(grant.role, FundedRole::Relay);
82 assert_eq!(grant.budget.bytes, 64);
83 assert_ne!(grant.funding_source, StrongDigest::ZERO);
84 assert!(!natural_person_wallet_required());
85 }
86
87 #[test]
88 fn all_roles_activate_with_funding() {
89 let src = sha384(b"fund-1");
90 let budget = ResourceBudget::ZERO;
91 let roles = [
92 FundedRole::Routing,
93 FundedRole::Relay,
94 FundedRole::Resolution,
95 FundedRole::Custody,
96 FundedRole::Storage,
97 FundedRole::Compute,
98 ];
99 let mut i = 0;
100 while i < roles.len() {
101 assert!(activate_role(roles[i], budget, src).is_ok());
102 i += 1;
103 }
104 }
105
106 #[test]
107 fn routing_grant_requires_budget_and_role() {
108 let src = sha384(b"fund-2");
109 let budget = ResourceBudget {
110 bytes: 8,
111 work: 1,
112 io: 1,
113 };
114 let routing = activate_role(FundedRole::Routing, budget, src).unwrap();
115 assert!(role_admits_router(&routing).is_ok());
116 let relay = activate_role(FundedRole::Relay, budget, src).unwrap();
117 assert_eq!(role_admits_router(&relay), Err(QdnfError::Denied));
118 let empty = activate_role(FundedRole::Routing, ResourceBudget::ZERO, src).unwrap();
119 assert_eq!(role_admits_router(&empty), Err(QdnfError::BudgetExhausted));
120 }
121}