1use std::collections::BTreeMap;
4
5#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
7pub enum AccountType {
8 #[default]
9 Unlinked = 0,
10 Main = 1,
11 Remote = 2,
12 RemoteUnlinked = 3,
13}
14
15#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
17pub struct Snapshot {
18 pub importance: u64,
19 pub height: u64,
20}
21
22#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
24pub struct Bucket {
25 pub start_height: u64,
26 pub total_fees_paid: u64,
27 pub beneficiary_count: u32,
28 pub raw_score: u64,
29}
30
31pub const SNAPSHOTS: usize = 3;
33pub const BUCKETS: usize = 7;
35const ROLLBACK_BUFFER: usize = 2;
37
38#[derive(Clone, Copy, PartialEq, Eq, Debug)]
40pub struct VotingKey {
41 pub key: [u8; 32],
42 pub start_epoch: u32,
43 pub end_epoch: u32,
44}
45
46#[derive(Clone, PartialEq, Eq, Debug)]
47pub struct AccountState {
48 pub address: [u8; 24],
49 pub address_height: u64,
50 pub public_key: [u8; 32],
51 pub public_key_height: u64,
53 pub account_type: AccountType,
54 pub linked: Option<[u8; 32]>,
55 pub node: Option<[u8; 32]>,
56 pub vrf: Option<[u8; 32]>,
57 pub voting: Vec<VotingKey>,
59 pub snapshots: [Snapshot; SNAPSHOTS],
61 pub buckets: [Bucket; BUCKETS],
63 pub balances: BTreeMap<u64, u64>,
65}
66
67impl AccountState {
68 pub fn new(address: [u8; 24], height: u64) -> Self {
69 Self {
70 address,
71 address_height: height,
72 public_key: [0; 32],
73 public_key_height: 0,
74 account_type: AccountType::Unlinked,
75 linked: None,
76 node: None,
77 vrf: None,
78 voting: Vec::new(),
79 snapshots: [Snapshot::default(); SNAPSHOTS],
80 buckets: [Bucket::default(); BUCKETS],
81 balances: BTreeMap::new(),
82 }
83 }
84
85 pub fn balance(&self, mosaic_id: u64) -> u64 {
86 self.balances.get(&mosaic_id).copied().unwrap_or(0)
87 }
88
89 pub fn credit(&mut self, mosaic_id: u64, amount: u64) {
91 if amount > 0 {
92 *self.balances.entry(mosaic_id).or_default() += amount;
93 }
94 }
95
96 #[must_use]
98 pub fn debit(&mut self, mosaic_id: u64, amount: u64) -> bool {
99 if amount == 0 {
100 return true;
101 }
102 let Some(balance) = self.balances.get_mut(&mosaic_id) else {
103 return false;
104 };
105 let Some(rest) = balance.checked_sub(amount) else {
106 return false;
107 };
108 *balance = rest;
109 if rest == 0 {
110 self.balances.remove(&mosaic_id);
111 }
112 true
113 }
114
115 pub fn is_high_value_format(&self) -> bool {
117 self.snapshots[0].height != 0
118 }
119
120 pub fn has_history(&self) -> bool {
122 self.snapshots.iter().any(|snapshot| snapshot.height != 0)
123 || self.buckets.iter().any(|bucket| bucket.start_height != 0)
124 }
125
126 pub fn push_snapshot(&mut self, snapshot: Snapshot) {
127 self.snapshots.rotate_right(1);
128 self.snapshots[0] = snapshot;
129 }
130
131 pub fn push_bucket(&mut self, bucket: Bucket) {
132 self.buckets.rotate_right(1);
133 self.buckets[0] = bucket;
134 }
135
136 pub fn pop_bucket(&mut self) {
137 self.buckets.rotate_left(1);
138 self.buckets[BUCKETS - 1] = Bucket::default();
139 }
140
141 pub fn try_update_bucket(&mut self, height: u64, update: impl FnOnce(&mut Bucket)) {
143 if self.buckets[0].start_height == height {
144 update(&mut self.buckets[0]);
145 }
146 }
147
148 pub fn to_state_bytes(&self, currency: u64) -> Vec<u8> {
150 let mut out = 1u16.to_le_bytes().to_vec();
151 out.extend_from_slice(&self.address);
152 out.extend_from_slice(&self.address_height.to_le_bytes());
153 out.extend_from_slice(&self.public_key);
154 out.extend_from_slice(&self.public_key_height.to_le_bytes());
155 out.push(self.account_type as u8);
156 let high_value = self.is_high_value_format();
157 out.push(u8::from(high_value));
158 let mut mask = 0;
159 for (key, bit) in [(&self.linked, 1), (&self.node, 2), (&self.vrf, 4)] {
160 if key.is_some() {
161 mask |= bit;
162 }
163 }
164 out.push(mask);
165 out.push(self.voting.len() as u8);
166 for key in [&self.linked, &self.node, &self.vrf].into_iter().flatten() {
167 out.extend_from_slice(key);
168 }
169 for voting in &self.voting {
170 out.extend_from_slice(&voting.key);
171 out.extend_from_slice(&voting.start_epoch.to_le_bytes());
172 out.extend_from_slice(&voting.end_epoch.to_le_bytes());
173 }
174 if high_value {
175 for snapshot in &self.snapshots[..SNAPSHOTS - ROLLBACK_BUFFER] {
176 out.extend_from_slice(&snapshot.importance.to_le_bytes());
177 out.extend_from_slice(&snapshot.height.to_le_bytes());
178 }
179 for bucket in &self.buckets[..BUCKETS - ROLLBACK_BUFFER] {
180 out.extend_from_slice(&bucket.start_height.to_le_bytes());
181 out.extend_from_slice(&bucket.total_fees_paid.to_le_bytes());
182 out.extend_from_slice(&bucket.beneficiary_count.to_le_bytes());
183 out.extend_from_slice(&bucket.raw_score.to_le_bytes());
184 }
185 }
186 let mut mosaics: Vec<_> = self.balances.iter().collect();
187 mosaics.sort_by_key(|(id, _)| (**id != currency, **id));
188 out.extend_from_slice(&(mosaics.len() as u16).to_le_bytes());
189 for (id, amount) in mosaics {
190 out.extend_from_slice(&id.to_le_bytes());
191 out.extend_from_slice(&amount.to_le_bytes());
192 }
193 out
194 }
195}
196
197#[cfg(test)]
198mod tests {
199 use super::*;
200
201 #[test]
202 fn balances_drop_empty_mosaics_and_refuse_overdrafts() {
203 let mut account = AccountState::new([1; 24], 1);
204 account.credit(7, 0);
205 assert!(account.balances.is_empty());
206 account.credit(7, 10);
207 assert!(!account.debit(7, 11));
208 assert!(!account.debit(8, 1));
209 assert!(account.debit(7, 0));
210 assert!(account.debit(7, 10));
211 assert!(account.balances.is_empty());
212 }
213
214 #[test]
215 fn state_bytes_put_the_currency_first() {
216 let mut account = AccountState::new([1; 24], 2);
217 for id in [3, 9, 5] {
218 account.credit(id, id * 100);
219 }
220 let bytes = account.to_state_bytes(9);
221 let mosaics = &bytes[2 + 24 + 8 + 32 + 8 + 4..];
223 assert_eq!(&mosaics[..2], &3u16.to_le_bytes());
224 let ids: Vec<u64> = mosaics[2..]
225 .chunks(16)
226 .map(|pair| u64::from_le_bytes(pair[..8].try_into().unwrap()))
227 .collect();
228 assert_eq!(ids, [9, 3, 5]);
229 assert!(!account.is_high_value_format());
231 assert_eq!(mosaics.len(), 2 + 3 * 16);
232 }
233}