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
use crate::{errors::*, genesis_accounts::make_genesis_accounts};
use diem_crypto::PrivateKey;
use diem_keygen::KeyGen;
use diem_types::account_config;
use language_e2e_tests::account::{Account, AccountData, AccountRoleSpecifier};
use move_core_types::identifier::Identifier;
use once_cell::sync::Lazy;
use std::{
collections::{btree_map, BTreeMap},
str::FromStr,
};
static DEFAULT_BALANCE: Lazy<Balance> = Lazy::new(|| Balance {
amount: 1_000_000,
currency_code: account_config::from_currency_code_string(account_config::XUS_NAME).unwrap(),
});
#[derive(Debug)]
pub enum Role {
Validator,
Address,
}
#[derive(Debug, Clone)]
pub struct Balance {
pub amount: u64,
pub currency_code: Identifier,
}
impl FromStr for Balance {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
let coin_types = vec!["XDX", "XUS"];
let mut coin_type: Vec<&str> = coin_types.into_iter().filter(|x| s.ends_with(x)).collect();
let currency_code = coin_type.pop().unwrap_or("XUS");
if !coin_type.is_empty() {
return Err(ErrorKind::Other(
"Multiple coin types supplied for account. Accounts are single currency"
.to_string(),
)
.into());
}
let s = s.trim_end_matches(currency_code);
Ok(Balance {
amount: s.parse::<u64>()?,
currency_code: account_config::from_currency_code_string(currency_code)?,
})
}
}
#[derive(Debug)]
pub struct AccountDefinition {
pub name: String,
pub balance: Option<Balance>,
pub sequence_number: Option<u64>,
pub role: Option<Role>,
pub account_type_specifier: Option<AccountRoleSpecifier>,
}
impl FromStr for Role {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
match s {
"validator" => Ok(Role::Validator),
"address" => Ok(Role::Address),
other => Err(ErrorKind::Other(format!("Invalid account role {:?}", other)).into()),
}
}
}
#[derive(Debug)]
pub enum Entry {
AccountDefinition(AccountDefinition),
}
impl Entry {
pub fn is_validator(&self) -> bool {
matches!(
self,
Entry::AccountDefinition(AccountDefinition {
role: Some(Role::Validator),
..
})
)
}
pub fn is_address(&self) -> bool {
matches!(
self,
Entry::AccountDefinition(AccountDefinition {
role: Some(Role::Address),
..
})
)
}
}
impl FromStr for Entry {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
let s = s.split_whitespace().collect::<String>();
let s = &s
.strip_prefix("//!")
.ok_or_else(|| ErrorKind::Other("txn config entry must start with //!".to_string()))?
.trim_start();
if let Some(s) = s.strip_prefix("account:") {
let v: Vec<_> = s
.split(|c: char| c == ',' || c.is_whitespace())
.filter(|s| !s.is_empty())
.collect();
if v.is_empty() || v.len() > 4 {
return Err(ErrorKind::Other(
"config 'account' takes 1 to 4 parameters".to_string(),
)
.into());
}
let balance = v.get(1).and_then(|s| s.parse::<Balance>().ok());
let sequence_number = v.get(2).and_then(|s| s.parse::<u64>().ok());
let role = v.get(3).and_then(|s| s.parse::<Role>().ok());
let account_type_specifier = v
.get(3)
.and_then(|s| s.parse::<AccountRoleSpecifier>().ok());
return Ok(Entry::AccountDefinition(AccountDefinition {
name: v[0].to_string(),
balance,
sequence_number,
role,
account_type_specifier,
}));
}
Err(ErrorKind::Other(format!("failed to parse '{}' as global config entry", s)).into())
}
}
#[derive(Debug)]
pub struct Config {
pub accounts: BTreeMap<String, AccountData>,
pub genesis_accounts: BTreeMap<String, Account>,
pub addresses: BTreeMap<String, Account>,
pub validator_accounts: usize,
pub exp_mode: bool,
}
impl Config {
pub fn build(entries: &[Entry], exp_mode: bool) -> Result<Self> {
let mut accounts = BTreeMap::new();
let mut addresses = BTreeMap::new();
let mut validator_accounts = entries.iter().filter(|entry| entry.is_validator()).count();
let total_validator_accounts = validator_accounts;
let validators = if validator_accounts > 0 {
vm_genesis::TestValidator::new_test_set(Some(validator_accounts))
.into_iter()
.map(|v| (v.data.address, v.key))
.collect()
} else {
vec![]
};
let mut keygen = KeyGen::from_seed([0x1f; 32]);
for entry in entries.iter() {
match entry {
Entry::AccountDefinition(def) if entry.is_address() => {
let (privkey, pubkey) = keygen.generate_keypair();
let account = Account::with_keypair(privkey, pubkey);
let name = def.name.to_ascii_lowercase();
let entry = addresses.entry(name);
match entry {
btree_map::Entry::Vacant(entry) => {
entry.insert(account);
}
btree_map::Entry::Occupied(_) => {
return Err(ErrorKind::Other(format!(
"already has account '{}'",
def.name,
))
.into());
}
}
}
Entry::AccountDefinition(def) => {
let balance = def.balance.as_ref().unwrap_or(&DEFAULT_BALANCE).clone();
let account_data = if entry.is_validator() {
validator_accounts -= 1;
let (account, privkey) = &validators.get(validator_accounts).unwrap();
AccountData::with_account(
Account::new_validator(*account, privkey.clone(), privkey.public_key()),
balance.amount,
balance.currency_code,
def.sequence_number.unwrap_or(0),
def.account_type_specifier.unwrap_or_default(),
)
} else {
let (privkey, pubkey) = keygen.generate_keypair();
AccountData::with_keypair(
privkey,
pubkey,
balance.amount,
balance.currency_code,
def.sequence_number.unwrap_or(0),
def.account_type_specifier.unwrap_or_default(),
)
};
let name = def.name.to_ascii_lowercase();
let entry = accounts.entry(name);
match entry {
btree_map::Entry::Vacant(entry) => {
entry.insert(account_data);
}
btree_map::Entry::Occupied(_) => {
return Err(ErrorKind::Other(format!(
"already has account '{}'",
def.name,
))
.into());
}
}
}
}
}
if let btree_map::Entry::Vacant(entry) = accounts.entry("default".to_string()) {
let (privkey, pubkey) = keygen.generate_keypair();
entry.insert(AccountData::with_keypair(
privkey,
pubkey,
DEFAULT_BALANCE.amount,
DEFAULT_BALANCE.currency_code.clone(),
0,
AccountRoleSpecifier::default(),
));
}
Ok(Config {
accounts,
addresses,
genesis_accounts: make_genesis_accounts(),
validator_accounts: total_validator_accounts,
exp_mode,
})
}
pub fn get_account_for_name(&self, name: &str) -> Result<&Account> {
self.accounts
.get(name)
.map(|account_data| account_data.account())
.or_else(|| self.genesis_accounts.get(name))
.or_else(|| self.addresses.get(name))
.ok_or_else(|| ErrorKind::Other(format!("account '{}' does not exist", name)).into())
}
}