/
action_data.rs
504 lines (433 loc) · 16.5 KB
/
action_data.rs
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
// Copyright 2018-2019 Kodebox, Inc.
// This file is part of CodeChain.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#[cfg(test)]
use std::collections::btree_map;
use std::collections::{btree_set, BTreeMap, BTreeSet};
use ckey::Address;
use cstate::{ActionData, ActionDataKeyBuilder, StateResult, TopLevelState, TopState, TopStateView};
use ctypes::errors::RuntimeError;
use primitives::H256;
use rlp::{Decodable, Encodable, Rlp, RlpStream};
use super::CUSTOM_ACTION_HANDLER_ID;
pub fn get_account_key(address: &Address) -> H256 {
ActionDataKeyBuilder::new(CUSTOM_ACTION_HANDLER_ID, 2).append(&"Account").append(address).into_key()
}
lazy_static! {
pub static ref STAKEHOLDER_ADDRESSES_KEY: H256 =
ActionDataKeyBuilder::new(CUSTOM_ACTION_HANDLER_ID, 1).append(&"StakeholderAddresses").into_key();
}
pub fn get_delegation_key(address: &Address) -> H256 {
ActionDataKeyBuilder::new(CUSTOM_ACTION_HANDLER_ID, 2).append(&"Delegation").append(address).into_key()
}
pub type StakeQuantity = u64;
pub struct StakeAccount<'a> {
pub address: &'a Address,
pub balance: StakeQuantity,
}
impl<'a> StakeAccount<'a> {
pub fn load_from_state(state: &TopLevelState, address: &'a Address) -> StateResult<StakeAccount<'a>> {
let account_key = get_account_key(address);
let action_data = state.action_data(&account_key)?;
let balance = match action_data {
Some(data) => Rlp::new(&data).as_val(),
None => StakeQuantity::default(),
};
Ok(StakeAccount {
address,
balance,
})
}
pub fn save_to_state(&self, state: &mut TopLevelState) -> StateResult<()> {
let account_key = get_account_key(self.address);
if self.balance != 0 {
let rlp = rlp::encode(&self.balance);
state.update_action_data(&account_key, rlp.into_vec())?;
} else {
state.remove_action_data(&account_key);
}
Ok(())
}
pub fn subtract_balance(&mut self, amount: u64) -> Result<(), RuntimeError> {
if self.balance < amount {
return Err(RuntimeError::InsufficientBalance {
address: *self.address,
cost: amount,
balance: self.balance,
})
}
self.balance -= amount;
Ok(())
}
pub fn add_balance(&mut self, amount: u64) -> Result<(), RuntimeError> {
self.balance += amount;
Ok(())
}
}
pub struct Stakeholders(BTreeSet<Address>);
impl Stakeholders {
pub fn load_from_state(state: &TopLevelState) -> StateResult<Stakeholders> {
let action_data = state.action_data(&*STAKEHOLDER_ADDRESSES_KEY)?;
let addresses = decode_set(action_data.as_ref());
Ok(Stakeholders(addresses))
}
pub fn save_to_state(&self, state: &mut TopLevelState) -> StateResult<()> {
let key = *STAKEHOLDER_ADDRESSES_KEY;
if !self.0.is_empty() {
state.update_action_data(&key, encode_set(&self.0))?;
} else {
state.remove_action_data(&key);
}
Ok(())
}
#[cfg(test)]
pub fn contains(&self, address: &Address) -> bool {
self.0.contains(address)
}
pub fn update_by_increased_balance(&mut self, account: &StakeAccount) {
if account.balance > 0 {
self.0.insert(*account.address);
}
}
pub fn update_by_decreased_balance(&mut self, account: &StakeAccount, delegation: &Delegation) {
assert!(account.address == delegation.delegator);
if account.balance == 0 && delegation.sum() == 0 {
self.0.remove(account.address);
}
}
pub fn iter(&self) -> btree_set::Iter<Address> {
self.0.iter()
}
}
pub struct Delegation<'a> {
pub delegator: &'a Address,
delegatees: BTreeMap<Address, StakeQuantity>,
}
impl<'a> Delegation<'a> {
pub fn load_from_state(state: &TopLevelState, delegator: &'a Address) -> StateResult<Delegation<'a>> {
let key = get_delegation_key(delegator);
let action_data = state.action_data(&key)?;
let delegatees = decode_map(action_data.as_ref());
Ok(Delegation {
delegator,
delegatees,
})
}
pub fn save_to_state(&self, state: &mut TopLevelState) -> StateResult<()> {
let key = get_delegation_key(self.delegator);
if !self.delegatees.is_empty() {
let encoded = encode_map(&self.delegatees);
state.update_action_data(&key, encoded)?;
} else {
state.remove_action_data(&key);
}
Ok(())
}
pub fn add_quantity(&mut self, delegatee: Address, quantity: StakeQuantity) -> StateResult<()> {
if quantity == 0 {
return Ok(())
}
*self.delegatees.entry(delegatee).or_insert(0) += quantity;
Ok(())
}
#[cfg(test)]
pub fn get_quantity(&self, delegatee: &Address) -> StakeQuantity {
self.delegatees.get(delegatee).cloned().unwrap_or(0)
}
#[cfg(test)]
pub fn iter(&self) -> btree_map::Iter<Address, StakeQuantity> {
self.delegatees.iter()
}
pub fn sum(&self) -> u64 {
self.delegatees.values().sum()
}
}
fn decode_set<V>(data: Option<&ActionData>) -> BTreeSet<V>
where
V: Ord + Decodable, {
let mut result = BTreeSet::new();
if let Some(rlp) = data.map(|x| Rlp::new(x)) {
for record in rlp.iter() {
let value: V = record.as_val();
result.insert(value);
}
}
result
}
fn encode_set<V>(set: &BTreeSet<V>) -> Vec<u8>
where
V: Ord + Encodable, {
let mut rlp = RlpStream::new();
rlp.begin_list(set.len());
for value in set.iter() {
rlp.append(value);
}
rlp.drain().into_vec()
}
fn decode_map<K, V>(data: Option<&ActionData>) -> BTreeMap<K, V>
where
K: Ord + Decodable,
V: Decodable, {
let mut result = BTreeMap::new();
if let Some(rlp) = data.map(|x| Rlp::new(x)) {
for record in rlp.iter() {
let key: K = record.val_at(0);
let value: V = record.val_at(1);
assert_eq!(2, record.item_count());
result.insert(key, value);
}
}
result
}
fn encode_map<K, V>(map: &BTreeMap<K, V>) -> Vec<u8>
where
K: Ord + Encodable,
V: Encodable, {
let mut rlp = RlpStream::new();
rlp.begin_list(map.len());
for (key, value) in map.iter() {
let record = rlp.begin_list(2);
record.append(key);
record.append(value);
}
rlp.drain().into_vec()
}
#[cfg(test)]
mod tests {
use super::*;
use cstate::tests::helpers;
use rand::{Rng, SeedableRng};
use rand_xorshift::XorShiftRng;
use std::collections::HashMap;
fn rng() -> XorShiftRng {
let seed: [u8; 16] = [0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7];
XorShiftRng::from_seed(seed)
}
#[test]
fn default_balance_is_zero() {
let state = helpers::get_temp_state();
let address = Address::random();
let account = StakeAccount::load_from_state(&state, &address).unwrap();
assert_eq!(account.address, &address);
assert_eq!(account.balance, 0);
}
#[test]
fn balance_add() {
let mut state = helpers::get_temp_state();
let address = Address::random();
{
let mut account = StakeAccount::load_from_state(&state, &address).unwrap();
account.add_balance(100).unwrap();
account.save_to_state(&mut state).unwrap();
}
let account = StakeAccount::load_from_state(&state, &address).unwrap();
assert_eq!(account.balance, 100);
}
#[test]
fn balance_subtract_error_on_low() {
let mut state = helpers::get_temp_state();
let address = Address::random();
{
let mut account = StakeAccount::load_from_state(&state, &address).unwrap();
account.add_balance(100).unwrap();
account.save_to_state(&mut state).unwrap();
}
{
let mut account = StakeAccount::load_from_state(&state, &address).unwrap();
let result = account.subtract_balance(110);
assert!(result.is_err());
assert_eq!(
result,
Err(RuntimeError::InsufficientBalance {
address,
cost: 110,
balance: 100,
})
);
}
let account = StakeAccount::load_from_state(&state, &address).unwrap();
assert_eq!(account.balance, 100);
}
#[test]
fn balance_subtract() {
let mut state = helpers::get_temp_state();
let address = Address::random();
let mut account = StakeAccount::load_from_state(&state, &address).unwrap();
account.add_balance(100).unwrap();
account.save_to_state(&mut state).unwrap();
let mut account = StakeAccount::load_from_state(&state, &address).unwrap();
let result = account.subtract_balance(90);
assert!(result.is_ok());
account.save_to_state(&mut state).unwrap();
let account = StakeAccount::load_from_state(&state, &address).unwrap();
assert_eq!(account.balance, 10);
}
#[test]
fn balance_subtract_all_should_remove_entry_from_db() {
let mut state = helpers::get_temp_state();
let address = Address::random();
let mut account = StakeAccount::load_from_state(&state, &address).unwrap();
account.add_balance(100).unwrap();
account.save_to_state(&mut state).unwrap();
let mut account = StakeAccount::load_from_state(&state, &address).unwrap();
let result = account.subtract_balance(100);
assert!(result.is_ok());
account.save_to_state(&mut state).unwrap();
let data = state.action_data(&get_account_key(&address)).unwrap();
assert_eq!(data, None);
}
#[test]
fn stakeholders_track() {
let mut rng = rng();
let mut state = helpers::get_temp_state();
let addresses: Vec<_> = (1..100).map(|_| Address::random()).collect();
let accounts: Vec<_> = addresses
.iter()
.map(|address| StakeAccount {
address,
balance: rng.gen_range(1, 100),
})
.collect();
let mut stakeholders = Stakeholders::load_from_state(&state).unwrap();
for account in &accounts {
stakeholders.update_by_increased_balance(account);
}
stakeholders.save_to_state(&mut state).unwrap();
let stakeholders = Stakeholders::load_from_state(&state).unwrap();
assert!(addresses.iter().all(|address| stakeholders.contains(address)));
}
#[test]
fn stakeholders_untrack() {
let mut rng = rng();
let mut state = helpers::get_temp_state();
let addresses: Vec<_> = (1..100).map(|_| Address::random()).collect();
let mut accounts: Vec<_> = addresses
.iter()
.map(|address| StakeAccount {
address,
balance: rng.gen_range(1, 100),
})
.collect();
let mut stakeholders = Stakeholders::load_from_state(&state).unwrap();
for account in &accounts {
stakeholders.update_by_increased_balance(account);
}
stakeholders.save_to_state(&mut state).unwrap();
let mut stakeholders = Stakeholders::load_from_state(&state).unwrap();
for account in &mut accounts {
if rand::random() {
account.balance = 0;
}
let delegation = Delegation::load_from_state(&state, account.address).unwrap();
stakeholders.update_by_decreased_balance(account, &delegation);
}
stakeholders.save_to_state(&mut state).unwrap();
let stakeholders = Stakeholders::load_from_state(&state).unwrap();
for account in &accounts {
let tracked = stakeholders.contains(account.address);
let has_balance = account.balance > 0;
assert!(tracked && has_balance || !tracked && !has_balance);
}
}
#[test]
fn stakeholders_doesnt_untrack_if_delegation_exists() {
let mut state = helpers::get_temp_state();
let addresses: Vec<_> = (1..100).map(|_| Address::random()).collect();
let mut accounts: Vec<_> = addresses
.iter()
.map(|address| StakeAccount {
address,
balance: 100,
})
.collect();
let mut stakeholders = Stakeholders::load_from_state(&state).unwrap();
for account in &accounts {
stakeholders.update_by_increased_balance(account);
}
stakeholders.save_to_state(&mut state).unwrap();
let mut stakeholders = Stakeholders::load_from_state(&state).unwrap();
for account in &mut accounts {
// like self-delegate
let mut delegation = Delegation::load_from_state(&state, account.address).unwrap();
delegation.add_quantity(*account.address, account.balance).unwrap();
account.balance = 0;
stakeholders.update_by_decreased_balance(account, &delegation);
}
stakeholders.save_to_state(&mut state).unwrap();
let stakeholders = Stakeholders::load_from_state(&state).unwrap();
for account in &accounts {
assert!(stakeholders.contains(account.address));
}
}
#[test]
fn initial_delegation_is_empty() {
let state = helpers::get_temp_state();
let delegatee = Address::random();
let delegation = Delegation::load_from_state(&state, &delegatee).unwrap();
assert_eq!(delegation.delegator, &delegatee);
assert_eq!(delegation.iter().count(), 0);
}
#[test]
fn delegation_add() {
let mut rng = rng();
let mut state = helpers::get_temp_state();
// Prepare
let delegator = Address::random();
let delegatees: Vec<_> = (0..10).map(|_| Address::random()).collect();
let delegation_amount: HashMap<&Address, StakeQuantity> =
delegatees.iter().map(|address| (address, rng.gen_range(0, 100))).collect();
// Do delegate
let mut delegation = Delegation::load_from_state(&state, &delegator).unwrap();
for delegatee in delegatees.iter() {
delegation.add_quantity(*delegatee, delegation_amount[delegatee]).unwrap()
}
delegation.save_to_state(&mut state).unwrap();
// assert
let delegation = Delegation::load_from_state(&state, &delegator).unwrap();
assert_eq!(delegation.iter().count(), delegatees.len());
for delegatee in delegatees.iter() {
assert_eq!(delegation.get_quantity(delegatee), delegation_amount[delegatee]);
}
}
#[test]
fn delegation_zero_add_should_not_be_included() {
let mut state = helpers::get_temp_state();
// Prepare
let delegator = Address::random();
let delegatee1 = Address::random();
let delegatee2 = Address::random();
// Do delegate
let mut delegation = Delegation::load_from_state(&state, &delegator).unwrap();
delegation.add_quantity(delegatee1, 100).unwrap();
delegation.add_quantity(delegatee2, 0).unwrap();
delegation.save_to_state(&mut state).unwrap();
let delegation = Delegation::load_from_state(&state, &delegator).unwrap();
let delegated = delegation.iter().collect::<Vec<_>>();
assert_eq!(&delegated, &[(&delegatee1, &100)]);
}
#[test]
fn delegation_empty_removed_from_state() {
let mut state = helpers::get_temp_state();
// Prepare
let delegator = Address::random();
let delegatee = Address::random();
// Do delegate
let mut delegation = Delegation::load_from_state(&state, &delegator).unwrap();
delegation.add_quantity(delegatee, 0).unwrap();
delegation.save_to_state(&mut state).unwrap();
let result = state.action_data(&get_delegation_key(&delegator)).unwrap();
assert_eq!(result, None);
}
}