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
mod bad_transaction;
mod create_account;
mod peer_to_peer;
mod rotate_key;
mod universe;
pub use bad_transaction::*;
pub use create_account::*;
pub use peer_to_peer::*;
pub use rotate_key::*;
pub use universe::*;
use crate::{
account::{self, xus_currency_code, Account, AccountData},
executor::FakeExecutor,
gas_costs, transaction_status_eq,
};
use diem_crypto::ed25519::{Ed25519PrivateKey, Ed25519PublicKey};
use diem_types::{
transaction::{SignedTransaction, TransactionStatus},
vm_status::{known_locations, KeptVMStatus, StatusCode},
};
use once_cell::sync::Lazy;
use proptest::{prelude::*, strategy::Union};
use std::{fmt, sync::Arc};
static UNIVERSE_SIZE: Lazy<usize> = Lazy::new(|| {
use std::{env, process::abort};
match env::var("UNIVERSE_SIZE") {
Ok(s) => match s.parse::<usize>() {
Ok(val) => val,
Err(err) => {
println!("Could not parse universe size, aborting: {:?}", err);
abort();
}
},
Err(env::VarError::NotPresent) => 20,
Err(err) => {
println!(
"Could not read universe size from the environment, aborting: {:?}",
err
);
abort();
}
}
});
#[inline]
pub fn default_num_accounts() -> usize {
*UNIVERSE_SIZE
}
#[inline]
pub fn default_num_transactions() -> usize {
*UNIVERSE_SIZE * 2
}
pub trait AUTransactionGen: fmt::Debug {
fn apply(
&self,
universe: &mut AccountUniverse,
) -> (SignedTransaction, (TransactionStatus, u64));
fn arced(self) -> Arc<dyn AUTransactionGen>
where
Self: 'static + Sized,
{
Arc::new(self)
}
}
impl AUTransactionGen for Arc<dyn AUTransactionGen> {
fn apply(
&self,
universe: &mut AccountUniverse,
) -> (SignedTransaction, (TransactionStatus, u64)) {
(**self).apply(universe)
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AccountCurrent {
initial_data: AccountData,
balance: u64,
sequence_number: u64,
sent_events_count: u64,
received_events_count: u64,
event_counter_created: bool,
}
impl AccountCurrent {
fn new(initial_data: AccountData) -> Self {
let balance = initial_data.balance(&xus_currency_code());
let sequence_number = initial_data.sequence_number();
let sent_events_count = initial_data.sent_events_count();
let received_events_count = initial_data.received_events_count();
Self {
initial_data,
balance,
sequence_number,
sent_events_count,
received_events_count,
event_counter_created: false,
}
}
pub fn account(&self) -> &Account {
self.initial_data.account()
}
pub fn rotate_key(&mut self, privkey: Ed25519PrivateKey, pubkey: Ed25519PublicKey) {
self.initial_data.rotate_key(privkey, pubkey);
}
pub fn balance(&self) -> u64 {
self.balance
}
pub fn sequence_number(&self) -> u64 {
self.sequence_number
}
pub fn sent_events_count(&self) -> u64 {
self.sent_events_count
}
pub fn received_events_count(&self) -> u64 {
self.received_events_count
}
pub fn create_account_gas_cost(&self) -> u64 {
if self.event_counter_created {
*gas_costs::CREATE_ACCOUNT_NEXT
} else {
*gas_costs::CREATE_ACCOUNT_FIRST
}
}
pub fn create_account_low_balance_gas_cost(&self) -> u64 {
if self.event_counter_created {
*gas_costs::CREATE_ACCOUNT_TOO_LOW_NEXT
} else {
*gas_costs::CREATE_ACCOUNT_TOO_LOW_FIRST
}
}
pub fn create_existing_account_gas_cost(&self) -> u64 {
if self.event_counter_created {
*gas_costs::CREATE_EXISTING_ACCOUNT_NEXT
} else {
*gas_costs::CREATE_EXISTING_ACCOUNT_FIRST
}
}
pub fn peer_to_peer_gas_cost(&self) -> u64 {
*gas_costs::PEER_TO_PEER
}
pub fn peer_to_peer_too_low_gas_cost(&self) -> u64 {
*gas_costs::PEER_TO_PEER_TOO_LOW
}
pub fn peer_to_peer_new_receiver_gas_cost(&self) -> u64 {
if self.event_counter_created {
*gas_costs::PEER_TO_PEER_NEW_RECEIVER_NEXT
} else {
*gas_costs::PEER_TO_PEER_NEW_RECEIVER_FIRST
}
}
pub fn peer_to_peer_new_receiver_too_low_gas_cost(&self) -> u64 {
if self.event_counter_created {
*gas_costs::PEER_TO_PEER_NEW_RECEIVER_TOO_LOW_NEXT
} else {
*gas_costs::PEER_TO_PEER_NEW_RECEIVER_TOO_LOW_FIRST
}
}
pub fn rotate_key_gas_cost(&self) -> u64 {
*gas_costs::ROTATE_KEY
}
}
pub fn txn_one_account_result(
sender: &mut AccountCurrent,
amount: u64,
gas_price: u64,
gas_used: u64,
low_gas_used: u64,
) -> (TransactionStatus, bool) {
let enough_max_gas = sender.balance >= gas_costs::TXN_RESERVED * gas_price;
let enough_to_transfer = sender.balance >= amount;
let to_deduct = amount + gas_used * gas_price;
let enough_to_succeed = sender.balance >= to_deduct;
match (enough_max_gas, enough_to_transfer, enough_to_succeed) {
(true, true, true) => {
sender.sequence_number += 1;
sender.sent_events_count += 1;
sender.balance -= to_deduct;
(TransactionStatus::Keep(KeptVMStatus::Executed), true)
}
(true, true, false) => {
sender.sequence_number += 1;
sender.balance -= gas_used * gas_price;
(
TransactionStatus::Keep(KeptVMStatus::MoveAbort(
known_locations::account_module_abort(),
6,
)),
false,
)
}
(true, false, _) => {
sender.sequence_number += 1;
sender.balance -= low_gas_used * gas_price;
(
TransactionStatus::Keep(KeptVMStatus::MoveAbort(
known_locations::account_module_abort(),
10,
)),
false,
)
}
(false, _, _) => {
(
TransactionStatus::Discard(StatusCode::INSUFFICIENT_BALANCE_FOR_TRANSACTION_FEE),
false,
)
}
}
}
pub fn log_balance_strategy(max_balance: u64) -> impl Strategy<Value = u64> {
let minimum = gas_costs::TXN_RESERVED.next_power_of_two();
assert!(max_balance >= minimum, "minimum to make sense");
let mut strategies = vec![];
let mut lower_bound: u64 = 0;
let mut upper_bound: u64 = minimum;
loop {
strategies.push(lower_bound..upper_bound);
if upper_bound >= max_balance {
break;
}
lower_bound = upper_bound;
upper_bound = (upper_bound * 2).min(max_balance);
}
Union::new(strategies)
}
pub fn all_transactions_strategy(
min: u64,
max: u64,
) -> impl Strategy<Value = Arc<dyn AUTransactionGen + 'static>> {
prop_oneof![
8 => p2p_strategy(min, max),
1 => any::<RotateKeyGen>().prop_map(RotateKeyGen::arced),
1 => bad_txn_strategy(),
]
}
pub fn run_and_assert_gas_cost_stability(
universe: AccountUniverseGen,
transaction_gens: Vec<impl AUTransactionGen + Clone>,
) -> Result<(), TestCaseError> {
let mut executor = FakeExecutor::from_genesis_file();
let mut universe = universe.setup_gas_cost_stability(&mut executor);
let (transactions, expected_values): (Vec<_>, Vec<_>) = transaction_gens
.iter()
.map(|transaction_gen| transaction_gen.clone().apply(&mut universe))
.unzip();
let outputs = executor.execute_block(transactions).unwrap();
for (idx, (output, expected_value)) in outputs.iter().zip(&expected_values).enumerate() {
prop_assert!(
transaction_status_eq(output.status(), &expected_value.0),
"unexpected status for transaction {}",
idx
);
prop_assert_eq!(
output.gas_used(),
expected_value.1,
"transaction at idx {} did not have expected gas cost",
idx,
);
}
Ok(())
}
pub fn run_and_assert_universe(
universe: AccountUniverseGen,
transaction_gens: Vec<impl AUTransactionGen + Clone>,
) -> Result<(), TestCaseError> {
let mut executor = FakeExecutor::from_genesis_file();
let mut universe = universe.setup(&mut executor);
let (transactions, expected_values): (Vec<_>, Vec<_>) = transaction_gens
.iter()
.map(|transaction_gen| transaction_gen.clone().apply(&mut universe))
.unzip();
let outputs = executor.execute_block(transactions).unwrap();
prop_assert_eq!(outputs.len(), expected_values.len());
for (idx, (output, expected)) in outputs.iter().zip(&expected_values).enumerate() {
prop_assert!(
transaction_status_eq(output.status(), &expected.0),
"unexpected status for transaction {}",
idx
);
executor.apply_write_set(output.write_set());
}
assert_accounts_match(&universe, &executor)
}
pub fn assert_accounts_match(
universe: &AccountUniverse,
executor: &FakeExecutor,
) -> Result<(), TestCaseError> {
for (idx, account) in universe.accounts().iter().enumerate() {
let resource = executor
.read_account_resource(account.account())
.expect("account resource must exist");
let resource_balance = executor
.read_balance_resource(account.account(), account::xus_currency_code())
.expect("account balance resource must exist");
let auth_key = account.account().auth_key();
prop_assert_eq!(
auth_key.as_slice(),
resource.authentication_key(),
"account {} should have correct auth key",
idx
);
prop_assert_eq!(
account.balance(),
resource_balance.coin(),
"account {} should have correct balance",
idx
);
prop_assert_eq!(
account.sequence_number(),
resource.sequence_number(),
"account {} should have correct sequence number",
idx
);
}
Ok(())
}