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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
#![allow(dead_code)]
use anyhow::{ensure, format_err, Context, Result};
use diem_client::{
views::{AccountRoleView, AccountView, AmountView, CurrencyInfoView, MetadataView},
Response,
};
use diem_crypto::HashValue;
use diem_types::{
account_address::AccountAddress, account_config::constants::from_currency_code_string,
account_state::AccountState, account_state_blob::AccountStateBlob, chain_id::ChainId,
diem_id_identifier::DiemIdVaspDomainIdentifier, transaction::Version,
};
use move_core_types::identifier::Identifier;
use serde::Serialize;
use std::{collections::BTreeMap, convert::TryFrom, iter, ops::AddAssign};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
#[structopt(about = "todo")]
pub struct Args {
#[structopt(subcommand)]
cmd: Command,
}
#[derive(Debug, StructOpt)]
pub enum Command {
Collect(CollectOptions),
}
#[derive(Debug, StructOpt)]
pub struct CommonOptions {
#[structopt(short = "i", long)]
chain_id: Option<ChainId>,
#[structopt(short = "j", long)]
json_server: String,
#[structopt(short = "v", long)]
verbose: bool,
}
#[derive(Debug, StructOpt)]
pub struct CollectOptions {
#[structopt(flatten)]
common: CommonOptions,
#[structopt(short = "p", long)]
parent_vasp: AccountAddress,
#[structopt(short = "c", long)]
child_vasps: Vec<AccountAddress>,
#[structopt(short = "t", long)]
timestamp_usecs: Option<u64>,
#[structopt(long)]
version: Option<Version>,
}
#[derive(Debug, Serialize)]
pub struct ParentVASPView {
address: AccountAddress,
balances: BalancesView,
human_name: String,
base_url: String,
num_children: u64,
vasp_domains: Option<Vec<DiemIdVaspDomainIdentifier>>,
}
impl TryFrom<AccountView> for ParentVASPView {
type Error = anyhow::Error;
fn try_from(account: AccountView) -> Result<Self> {
ensure!(
!account.is_frozen,
"account is currently frozen by Diem treasury compliance"
);
match account.role {
AccountRoleView::ParentVASP {
human_name,
base_url,
num_children,
vasp_domains,
..
} => Ok(ParentVASPView {
address: account.address,
balances: BalancesView::new(account.balances),
human_name,
base_url,
num_children,
vasp_domains,
}),
_ => Err(format_err!(
"expected parent VASP account, actual account type: {:?}",
account.role
)),
}
}
}
#[derive(Debug, Serialize)]
pub struct ChildVASPView {
balances: BalancesView,
#[serde(skip_serializing)]
address: AccountAddress,
#[serde(skip_serializing)]
parent_vasp_address: AccountAddress,
}
impl TryFrom<AccountView> for ChildVASPView {
type Error = anyhow::Error;
fn try_from(account: AccountView) -> Result<Self> {
ensure!(
!account.is_frozen,
"account is currently frozen by Diem treasury compliance"
);
match account.role {
AccountRoleView::ChildVASP {
parent_vasp_address,
..
} => Ok(ChildVASPView {
address: account.address,
balances: BalancesView::new(account.balances),
parent_vasp_address,
}),
_ => Err(format_err!(
"expected child VASP account, actual account type: {:?}",
account.role
)),
}
}
}
#[derive(Debug, Serialize)]
pub struct SimpleCurrencyView {
#[serde(skip_serializing)]
currency: Identifier,
scaling_factor: u64,
fractional_part: u64,
to_xdx_exchange_rate: f32,
}
impl TryFrom<CurrencyInfoView> for SimpleCurrencyView {
type Error = anyhow::Error;
fn try_from(currency: CurrencyInfoView) -> Result<Self> {
let code = from_currency_code_string(¤cy.code)?;
Ok(SimpleCurrencyView {
currency: code,
scaling_factor: currency.scaling_factor,
fractional_part: currency.fractional_part,
to_xdx_exchange_rate: currency.to_xdx_exchange_rate,
})
}
}
#[derive(Clone, Debug, Serialize)]
pub struct BalancesView(BTreeMap<String, u64>);
impl BalancesView {
pub fn empty() -> Self {
Self(BTreeMap::new())
}
pub fn new(balances: Vec<AmountView>) -> Self {
Self(
balances
.into_iter()
.map(|balance| (balance.currency, balance.amount))
.collect(),
)
}
pub fn merge(mut self, other: BalancesView) -> Self {
for (currency, amount) in other.0.into_iter() {
self.0.entry(currency).or_default().add_assign(amount);
}
self
}
}
#[derive(Debug, Serialize)]
pub struct SimpleMetadataView {
diem_chain_id: ChainId,
diem_ledger_version: Version,
diem_ledger_timestampusec: u64,
accumulator_root_hash: HashValue,
}
impl From<MetadataView> for SimpleMetadataView {
fn from(metadata: MetadataView) -> Self {
SimpleMetadataView {
diem_chain_id: ChainId::new(metadata.chain_id),
diem_ledger_version: metadata.version,
diem_ledger_timestampusec: metadata.timestamp,
accumulator_root_hash: metadata.accumulator_root_hash,
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ResultWrapper<T> {
Result(T),
Error(String),
}
impl<T> ResultWrapper<T> {
pub fn new(result: Result<T>) -> ResultWrapper<T> {
match result {
Ok(val) => Self::Result(val),
Err(err) => Self::Error(format!("{:#}", err)),
}
}
pub fn is_error(&self) -> bool {
match self {
Self::Result(_) => false,
Self::Error(_) => true,
}
}
}
#[derive(Debug, Serialize)]
pub struct AssetsProof {
#[serde(flatten)]
metadata: SimpleMetadataView,
all_child_vasps_valid: bool,
total_unfrozen_balances: BalancesView,
currencies: BTreeMap<Identifier, SimpleCurrencyView>,
parent_vasp: ParentVASPView,
child_vasps: BTreeMap<AccountAddress, ResultWrapper<ChildVASPView>>,
}
impl Args {
pub fn exec(self) -> Result<String> {
match self.cmd {
Command::Collect(opts) => pretty_print(opts.exec()),
}
}
}
impl CollectOptions {
fn exec(&self) -> Result<AssetsProof> {
let client = diem_client::BlockingClient::new(self.common.json_server.clone());
self.exec_with_client(client)
}
fn exec_with_client(&self, client: impl Client) -> Result<AssetsProof> {
let metadata = self
.resolve_metadata(&client)
.context("Failed to resolve current chain metadata")?;
let target_version = metadata.diem_ledger_version;
if let Some(expected_chain_id) = self.common.chain_id {
ensure!(
expected_chain_id == metadata.diem_chain_id,
"Remote service's chain doesn't match our expected chain id: actual: {}, expected: {}",
metadata.diem_chain_id,
expected_chain_id,
);
}
let currencies = client
.get_currencies()?
.into_inner()
.into_iter()
.map(SimpleCurrencyView::try_from)
.collect::<Result<Vec<_>>>()
.context("Invalid currency metadata")?;
let parent_vasp = client
.get_account_by_version(self.parent_vasp, target_version)
.context("Failed to retrieve parent VASP account")?
.into_inner()
.ok_or_else(|| {
format_err!(
"No parent VASP account at the address: '{}'",
self.parent_vasp
)
})
.and_then(ParentVASPView::try_from)
.context("Invalid parent VASP account")?;
let mut all_child_vasps_valid = true;
if parent_vasp.num_children != self.child_vasps.len() as u64 {
all_child_vasps_valid = false;
eprintln!(
"WARNING: The actual number of child VASP accounts on-chain \
doesn't match the expected number: actual: {}, expected: {}",
parent_vasp.num_children,
self.child_vasps.len(),
);
}
let child_vasps = self
.child_vasps
.iter()
.map(|child_vasp_address| -> (AccountAddress, ResultWrapper<ChildVASPView>) {
let maybe_account_view = client
.get_account_by_version(*child_vasp_address, target_version)
.context("Failed to retrieve child VASP account")
.map(Response::into_inner)
.and_then(|opt_account_view| opt_account_view.ok_or_else(|| format_err!("no child VASP account at the address")));
let maybe_child_vasp = maybe_account_view
.and_then(|account_view| ChildVASPView::try_from(account_view).context("invalid child VASP account"))
.and_then(|child_vasp| {
ensure!(
child_vasp.parent_vasp_address == parent_vasp.address,
"Child VASP's parent VASP account doesn't match: child_vasp.parent_vasp_address: '{}'",
child_vasp.parent_vasp_address,
);
Ok(child_vasp)
});
if maybe_child_vasp.is_err() {
all_child_vasps_valid = false;
}
(*child_vasp_address, ResultWrapper::new(maybe_child_vasp))
})
.collect::<BTreeMap<_, _>>();
let child_vasp_balances = child_vasps.values().filter_map(|maybe_child_vasp| {
let child_vasp = match maybe_child_vasp {
ResultWrapper::Result(child_vasp) => child_vasp,
ResultWrapper::Error(_) => return None,
};
Some(child_vasp.balances.clone())
});
let vasp_balances = iter::once(parent_vasp.balances.clone()).chain(child_vasp_balances);
let total_unfrozen_balances =
vasp_balances.fold(BalancesView::empty(), BalancesView::merge);
let currencies = currencies
.into_iter()
.map(|currency_info| (currency_info.currency.clone(), currency_info))
.collect::<BTreeMap<_, _>>();
Ok(AssetsProof {
metadata,
all_child_vasps_valid,
total_unfrozen_balances,
currencies,
parent_vasp,
child_vasps,
})
}
fn resolve_metadata(&self, client: &impl Client) -> Result<SimpleMetadataView> {
let maybe_response = if let Some(version) = self.version {
client.get_metadata_by_version(version)
} else if let Some(timestamp_usecs) = self.timestamp_usecs {
let current_metadata = client.get_metadata()?;
let latest_version = current_metadata.state().version;
let past_version =
client.get_last_version_before_timestamp(timestamp_usecs, latest_version)?;
client.get_metadata_by_version(past_version)
} else {
client.get_metadata()
};
let metadata = maybe_response?.into_inner();
Ok(SimpleMetadataView::from(metadata))
}
}
pub trait Client {
fn get_last_version_before_timestamp(
&self,
timestamp_usecs: u64,
version: Version,
) -> Result<Version>;
fn get_metadata(&self) -> Result<Response<MetadataView>>;
fn get_metadata_by_version(&self, version: Version) -> Result<Response<MetadataView>>;
fn get_currencies(&self) -> Result<Response<Vec<CurrencyInfoView>>>;
fn get_account_by_version(
&self,
address: AccountAddress,
version: Version,
) -> Result<Response<Option<AccountView>>>;
}
impl Client for diem_client::BlockingClient {
fn get_last_version_before_timestamp(
&self,
_timestamp_usecs: u64,
_version: Version,
) -> Result<Version> {
todo!()
}
fn get_metadata(&self) -> Result<Response<MetadataView>> {
self.get_metadata().context("Failed to get ledger metadata")
}
fn get_metadata_by_version(&self, version: Version) -> Result<Response<MetadataView>> {
self.get_metadata_by_version(version)
.with_context(|| format!("Failed to get ledger metadata: version={}", version))
}
fn get_currencies(&self) -> Result<Response<Vec<CurrencyInfoView>>> {
self.get_currencies()
.context("Failed to get current supported ledger currencies")
}
fn get_account_by_version(
&self,
address: AccountAddress,
version: Version,
) -> Result<Response<Option<AccountView>>> {
let response =
self.get_account_state_with_proof(address, Some(version), None )?;
let (account_state_with_proof, response_state) = response.into_parts();
let account_blob_view = match account_state_with_proof.blob {
Some(account_blob) => account_blob,
None => return Ok(Response::new(None, response_state)),
};
let account_blob: AccountStateBlob = bcs::from_bytes(account_blob_view.as_ref())
.context("Failed to deserialize AccountStateBlob")?;
let account_state =
AccountState::try_from(&account_blob).context("Failed to deserialize account state")?;
let account_view = AccountView::try_from_account_state(address, account_state, version)
.context("Failed to project account state into account view")?;
Ok(Response::new(Some(account_view), response_state))
}
}
pub fn pretty_print<T: Serialize>(result: Result<T>) -> Result<String> {
result.map(|val| serde_json::to_string_pretty(&val).unwrap())
}