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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
use crate::{
error::{Error, Result},
request::MethodRequest,
response::{MethodResponse, Response},
state::State,
};
use diem_json_rpc_types::views::{
AccountStateWithProofView, AccountView, CurrencyInfoView, EventView, MetadataView,
TransactionListView,
};
use diem_types::{
account_address::AccountAddress,
account_config::{diem_root_address, NewBlockEvent},
account_state::AccountState,
account_state_blob::AccountStateWithProof,
block_metadata::new_block_event_key,
contract_event::{EventByVersionWithProof, EventWithProof},
event::EventKey,
ledger_info::LedgerInfo,
proof::{AccumulatorConsistencyProof, TransactionAccumulatorSummary},
state_proof::StateProof,
transaction::{AccountTransactionsWithProof, Version},
trusted_state::TrustedState,
};
use std::convert::TryFrom;
pub(crate) struct VerifyingBatch {
requests: Vec<VerifyingRequest>,
}
impl VerifyingBatch {
pub(crate) fn from_batch(requests: Vec<MethodRequest>) -> Self {
Self {
requests: requests.into_iter().map(VerifyingRequest::from).collect(),
}
}
pub(crate) fn num_requests(&self, request_trusted_state: &TrustedState) -> usize {
let num_client_requests = self
.requests
.iter()
.map(|request| request.subrequests.len())
.sum::<usize>();
num_client_requests
+ 1 + request_trusted_state.need_accumulator() as usize }
pub(crate) fn collect_requests(
&self,
request_trusted_state: &TrustedState,
) -> Vec<MethodRequest> {
let request_version = request_trusted_state.version();
let mut requests = self
.requests
.iter()
.flat_map(|request| request.subrequests.iter().cloned())
.collect::<Vec<_>>();
if request_trusted_state.need_accumulator() {
requests.push(MethodRequest::get_accumulator_consistency_proof(
None,
Some(request_version),
));
}
requests.push(MethodRequest::get_state_proof(request_version));
requests
}
pub(crate) fn verify_responses(
self,
request_trusted_state: &TrustedState,
mut responses: Vec<Result<Response<MethodResponse>>>,
) -> Result<(
Option<TrustedState>,
Option<Vec<Result<Response<MethodResponse>>>>,
)> {
let request_version = request_trusted_state.version();
let num_requests = self.num_requests(request_trusted_state);
if num_requests != responses.len() {
return Err(Error::rpc_response(format!(
"expected {} responses, received {} responses in batch",
num_requests,
responses.len()
)));
}
let (state_proof_response, state) = responses.pop().unwrap()?.into_parts();
let state_proof_view = state_proof_response.try_into_get_state_proof()?;
let state_proof = StateProof::try_from(&state_proof_view).map_err(Error::decode)?;
verify_latest_li_matches_state(state_proof.latest_ledger_info(), &state)?;
for response in responses.iter().flatten() {
if response.state() != &state {
return Err(Error::rpc_response(format!(
"expected all responses in batch to have the same metadata: {:?}, \
received unexpected response metadata: {:?}",
state,
response.state(),
)));
}
}
let maybe_accumulator = if request_trusted_state.need_accumulator() {
let response = responses.pop().unwrap()?.into_inner();
let consistency_proof_view = response.try_into_get_accumulator_consistency_proof()?;
let consistency_proof = AccumulatorConsistencyProof::try_from(&consistency_proof_view)
.map_err(Error::decode)?;
let accumulator_summary = TransactionAccumulatorSummary::try_from_genesis_proof(
consistency_proof,
request_version,
)
.map_err(Error::invalid_proof)?;
Some(accumulator_summary)
} else {
None
};
let new_state = request_trusted_state
.verify_and_ratchet(&state_proof, maybe_accumulator.as_ref())
.map_err(Error::invalid_proof)?
.new_state();
if state_proof.epoch_changes().more {
return Ok((new_state, None));
}
let mut responses_iter = responses.into_iter();
let validated_responses = self
.requests
.into_iter()
.map(|request| {
let n = request.subrequests.len();
let subresponses = responses_iter.by_ref().take(n).collect();
request.validate_subresponses(&state, &state_proof, subresponses)
})
.collect::<Vec<_>>();
Ok((new_state, Some(validated_responses)))
}
}
fn verify_latest_li_matches_state(latest_li: &LedgerInfo, state: &State) -> Result<()> {
if latest_li.version() != state.version {
return Err(Error::invalid_proof(format!(
"latest LedgerInfo version ({}) doesn't match response version ({})",
latest_li.version(),
state.version,
)));
}
if latest_li.timestamp_usecs() != state.timestamp_usecs {
return Err(Error::invalid_proof(format!(
"latest LedgerInfo timestamp ({}) doesn't match response timestamp ({})",
latest_li.timestamp_usecs(),
state.timestamp_usecs,
)));
}
Ok(())
}
#[derive(Clone, Copy)]
struct RequestContext<'a> {
state: &'a State,
state_proof: &'a StateProof,
}
type RequestCallback =
Box<dyn FnOnce(RequestContext<'_>, &[MethodResponse]) -> Result<MethodResponse>>;
struct VerifyingRequest {
request: MethodRequest,
subrequests: Vec<MethodRequest>,
callback: RequestCallback,
}
impl VerifyingRequest {
fn new(
request: MethodRequest,
subrequests: Vec<MethodRequest>,
callback: RequestCallback,
) -> Self {
Self {
request,
subrequests,
callback,
}
}
fn map<F>(self, f: F) -> VerifyingRequest
where
F: FnOnce(RequestContext<'_>, MethodResponse) -> MethodResponse + 'static,
{
let inner = self.callback;
let callback: RequestCallback = Box::new(move |ctxt, subresponses| {
let response = inner(ctxt, subresponses)?;
Ok(f(ctxt, response))
});
Self::new(self.request, self.subrequests, callback)
}
fn validate_subresponses(
self,
state: &State,
state_proof: &StateProof,
subresponses: Vec<Result<Response<MethodResponse>>>,
) -> Result<Response<MethodResponse>> {
if subresponses.len() != self.subrequests.len() {
return Err(Error::rpc_response(format!(
"expected {} subresponses for our request {:?}, received {} subresponses in batch",
self.subrequests.len(),
self.request.method(),
subresponses.len(),
)));
}
let ctxt = RequestContext { state, state_proof };
let subresponses_only = subresponses
.into_iter()
.map(|result| result.map(Response::into_inner))
.collect::<Result<Vec<_>>>()?;
let response = (self.callback)(ctxt, subresponses_only.as_slice())?;
Ok(Response::new(response, state.clone()))
}
}
impl From<MethodRequest> for VerifyingRequest {
fn from(request: MethodRequest) -> Self {
match request {
MethodRequest::Submit((txn,)) => submit(txn),
MethodRequest::GetMetadata((None,)) => get_latest_metadata(),
MethodRequest::GetMetadata((Some(version),)) => get_historical_metadata(version),
MethodRequest::GetAccount(address, version) => get_account(address, version),
MethodRequest::GetTransactions(start_version, limit, include_events) => {
get_transactions(start_version, limit, include_events)
}
MethodRequest::GetAccountTransactions(
address,
start_seq_num,
limit,
include_events,
) => get_account_transactions(address, start_seq_num, limit, include_events),
MethodRequest::GetAccountTransaction(address, seq_num, include_events) => {
get_account_transaction(address, seq_num, include_events)
}
MethodRequest::GetEvents(key, start_seq, limit) => get_events(key, start_seq, limit),
MethodRequest::GetCurrencies([]) => get_currencies(),
MethodRequest::GetNetworkStatus([]) => get_network_status(),
_ => panic!(
"unsupported verifying client method: {:?}",
request.method()
),
}
}
}
fn submit(txn: String) -> VerifyingRequest {
let request = MethodRequest::Submit((txn,));
let subrequests = vec![request.clone()];
let callback: RequestCallback = Box::new(move |_ctxt, subresponses| {
match subresponses {
[MethodResponse::Submit] => (),
subresponses => {
return Err(Error::rpc_response(format!(
"expected [Submit] subresponses, received: {:?}",
subresponses,
)))
}
};
Ok(MethodResponse::Submit)
});
VerifyingRequest::new(request, subrequests, callback)
}
fn get_latest_metadata() -> VerifyingRequest {
let request = MethodRequest::GetMetadata((None,));
let subrequests = vec![MethodRequest::GetAccountStateWithProof(
diem_root_address(),
None,
None,
)];
let callback: RequestCallback = Box::new(move |ctxt, subresponses| {
let diem_root = match subresponses {
[MethodResponse::GetAccountStateWithProof(ref account)] => account,
subresponses => {
return Err(Error::rpc_response(format!(
"expected [GetAccountStateWithProof] subresponses, received: {:?}",
subresponses,
)))
}
};
let latest_li = ctxt.state_proof.latest_ledger_info();
let diem_root = verify_account_state(ctxt, diem_root, diem_root_address(), None)?
.ok_or_else(|| Error::rpc_response("DiemRoot account is missing"))?;
let version = latest_li.version();
let accumulator_root_hash = latest_li.transaction_accumulator_hash();
let timestamp = latest_li.timestamp_usecs();
let chain_id = ctxt.state.chain_id;
let mut metadata_view =
MetadataView::new(version, accumulator_root_hash, timestamp, chain_id);
metadata_view
.with_diem_root(&diem_root)
.map_err(Error::rpc_response)?;
Ok(MethodResponse::GetMetadata(metadata_view))
});
VerifyingRequest::new(request, subrequests, callback)
}
fn get_historical_metadata(version: Version) -> VerifyingRequest {
let request = MethodRequest::GetMetadata((Some(version),));
let subrequests = vec![
MethodRequest::GetAccumulatorConsistencyProof(None, Some(version)),
MethodRequest::GetAccumulatorConsistencyProof(Some(version), None),
MethodRequest::GetEventByVersionWithProof(new_block_event_key(), Some(version)),
];
let callback: RequestCallback = Box::new(move |ctxt, subresponses| {
let (consistency_pg2v, consistency_v2li, block_event) = match subresponses {
[MethodResponse::GetAccumulatorConsistencyProof(ref c1), MethodResponse::GetAccumulatorConsistencyProof(ref c2), MethodResponse::GetEventByVersionWithProof(ref e)] => (c1, c2, e),
subresponses => {
return Err(Error::rpc_response(format!(
"expected [GetAccumulatorConsistencyProof, GetAccumulatorConsistencyProof, GetEventByVersionWithProof] subresponses, received: {:?}",
subresponses,
)))
}
};
let latest_li = ctxt.state_proof.latest_ledger_info();
let consistency_pg2v =
AccumulatorConsistencyProof::try_from(consistency_pg2v).map_err(Error::decode)?;
let consistency_v2li =
AccumulatorConsistencyProof::try_from(consistency_v2li).map_err(Error::decode)?;
let block_event = EventByVersionWithProof::try_from(block_event).map_err(Error::decode)?;
let accumulator_summary =
TransactionAccumulatorSummary::try_from_genesis_proof(consistency_pg2v, version)
.map_err(Error::invalid_proof)?;
let accumulator_root_hash = accumulator_summary.root_hash();
let _ = accumulator_summary
.try_extend_with_proof(&consistency_v2li, latest_li)
.map_err(Error::invalid_proof)?;
let event_count = None;
block_event
.verify(latest_li, &new_block_event_key(), event_count, version)
.map_err(Error::invalid_proof)?;
let timestamp = match (block_event.lower_bound_incl, block_event.upper_bound_excl) {
(None, None) | (None, Some(_)) => {
if version == 0 {
0 } else {
return Err(Error::rpc_response("not genesis"));
}
}
(Some(block_event), Some(_)) => {
let block_event =
NewBlockEvent::try_from(&block_event.event).map_err(Error::decode)?;
block_event.proposed_time()
}
(Some(block_event), None) => {
let block_event =
NewBlockEvent::try_from(&block_event.event).map_err(Error::decode)?;
let timestamp = block_event.proposed_time();
if block_event.round() != latest_li.round()
|| timestamp != latest_li.timestamp_usecs()
{
return Err(Error::rpc_response("not latest block"));
}
timestamp
}
};
let chain_id = ctxt.state.chain_id;
let metadata_view = MetadataView::new(version, accumulator_root_hash, timestamp, chain_id);
Ok(MethodResponse::GetMetadata(metadata_view))
});
VerifyingRequest::new(request, subrequests, callback)
}
fn get_account(address: AccountAddress, version: Option<Version>) -> VerifyingRequest {
let request = MethodRequest::GetAccount(address, version);
let subrequests = vec![MethodRequest::GetAccountStateWithProof(
address, version, None,
)];
let callback: RequestCallback = Box::new(move |ctxt, subresponses| {
let account = match subresponses {
[MethodResponse::GetAccountStateWithProof(ref account)] => account,
subresponses => {
return Err(Error::rpc_response(format!(
"expected [GetAccountStateWithProof] subresponses, received: {:?}",
subresponses,
)))
}
};
let ledger_version = ctxt.state_proof.latest_ledger_info().version();
let version = version.unwrap_or(ledger_version);
let maybe_account_state = verify_account_state(ctxt, account, address, Some(version))?;
let maybe_account_view = maybe_account_state
.map(|account_state| {
AccountView::try_from_account_state(address, account_state, version)
.map_err(Error::decode)
})
.transpose()?;
Ok(MethodResponse::GetAccount(maybe_account_view))
});
VerifyingRequest::new(request, subrequests, callback)
}
fn get_transactions(start_version: Version, limit: u64, include_events: bool) -> VerifyingRequest {
let request = MethodRequest::GetTransactions(start_version, limit, include_events);
let subrequests = vec![MethodRequest::GetTransactionsWithProofs(
start_version,
limit,
include_events,
)];
let callback: RequestCallback = Box::new(move |ctxt, subresponses| {
let maybe_txs_with_proofs_view = match subresponses {
[MethodResponse::GetTransactionsWithProofs(ref txs)] => txs,
subresponses => {
return Err(Error::rpc_response(format!(
"expected [GetTransactionsWithProofs] subresponses, received: {:?}",
subresponses,
)))
}
};
let txs_with_proofs_view = if let Some(txs_with_proofs_view) = maybe_txs_with_proofs_view {
txs_with_proofs_view
} else {
return Ok(MethodResponse::GetTransactions(Vec::new()));
};
let has_events = txs_with_proofs_view.serialized_events.is_some();
if include_events != has_events {
return Err(Error::rpc_response(format!(
"expected events: {}, received events: {}",
include_events, has_events
)));
}
let txn_list_with_proof = txs_with_proofs_view
.try_into_txn_list_with_proof(start_version)
.map_err(Error::decode)?;
let latest_li = ctxt.state_proof.latest_ledger_info();
txn_list_with_proof
.verify(latest_li, Some(start_version))
.map_err(Error::invalid_proof)?;
let txn_list_view =
TransactionListView::try_from(txn_list_with_proof).map_err(Error::decode)?;
Ok(MethodResponse::GetTransactions(txn_list_view.0))
});
VerifyingRequest::new(request, subrequests, callback)
}
fn get_account_transactions(
address: AccountAddress,
start_seq_num: u64,
limit: u64,
include_events: bool,
) -> VerifyingRequest {
let request =
MethodRequest::GetAccountTransactions(address, start_seq_num, limit, include_events);
let subrequests = vec![MethodRequest::GetAccountTransactionsWithProofs(
address,
start_seq_num,
limit,
include_events,
None, )];
let callback: RequestCallback = Box::new(move |ctxt, subresponses| {
let acct_txns_with_proof_view = match subresponses {
[MethodResponse::GetAccountTransactionsWithProofs(ref txs)] => txs,
subresponses => {
return Err(Error::rpc_response(format!(
"expected [GetAccountTransactionsWithProofs] subresponses, received: {:?}",
subresponses,
)))
}
};
let acct_txns_with_proof =
AccountTransactionsWithProof::try_from(acct_txns_with_proof_view)
.map_err(Error::decode)?;
let latest_li = ctxt.state_proof.latest_ledger_info();
let ledger_version = latest_li.version();
acct_txns_with_proof
.verify(
latest_li,
address,
start_seq_num,
limit,
include_events,
ledger_version,
)
.map_err(Error::invalid_proof)?;
let txs = TransactionListView::try_from(acct_txns_with_proof).map_err(Error::decode)?;
Ok(MethodResponse::GetAccountTransactions(txs.0))
});
VerifyingRequest::new(request, subrequests, callback)
}
fn get_account_transaction(
address: AccountAddress,
seq_num: u64,
include_events: bool,
) -> VerifyingRequest {
get_account_transactions(address, seq_num, 1, include_events).map(|_ctxt, response| {
match response {
MethodResponse::GetAccountTransactions(txns) => {
MethodResponse::GetAccountTransaction(txns.into_iter().next())
}
response => panic!(
"expected GetAccountTransactions response, got: {:?}",
response
),
}
})
}
fn get_events(key: EventKey, start_seq: u64, limit: u64) -> VerifyingRequest {
let request = MethodRequest::GetEvents(key, start_seq, limit);
let subrequests = vec![MethodRequest::GetEventsWithProofs(key, start_seq, limit)];
let callback: RequestCallback = Box::new(move |ctxt, subresponses| {
let event_with_proof_views = match subresponses {
[MethodResponse::GetEventsWithProofs(ref inner)] => inner,
subresponses => {
return Err(Error::rpc_response(format!(
"expected [GetEventsWithProofs] subresponses, received: {:?}",
subresponses,
)))
}
};
let num_received = event_with_proof_views.len() as u64;
if num_received > limit {
return Err(Error::rpc_response(format!(
"more events than limit: limit {} events, received {} events",
limit, num_received,
)));
}
let latest_li = ctxt.state_proof.latest_ledger_info();
let event_views = event_with_proof_views
.iter()
.enumerate()
.map(|(offset, event_with_proof_view)| {
let event_with_proof =
EventWithProof::try_from(event_with_proof_view).map_err(Error::decode)?;
let txn_version = event_with_proof.transaction_version;
event_with_proof
.verify(
latest_li,
&key,
start_seq + offset as u64,
txn_version,
event_with_proof.event_index,
)
.map_err(Error::invalid_proof)?;
let event_view = EventView::try_from((txn_version, event_with_proof.event))
.map_err(Error::decode)?;
Ok(event_view)
})
.collect::<Result<Vec<_>>>()?;
Ok(MethodResponse::GetEvents(event_views))
});
VerifyingRequest::new(request, subrequests, callback)
}
fn get_currencies() -> VerifyingRequest {
let request = MethodRequest::GetCurrencies([]);
let subrequests = vec![MethodRequest::GetAccountStateWithProof(
diem_root_address(),
None,
None,
)];
let callback: RequestCallback = Box::new(|ctxt, subresponses| {
let diem_root = match subresponses {
[MethodResponse::GetAccountStateWithProof(ref diem_root)] => diem_root,
subresponses => {
return Err(Error::rpc_response(format!(
"expected [GetAccountStateWithProof] subresponses, received: {:?}",
subresponses,
)))
}
};
let diem_root = verify_account_state(ctxt, diem_root, diem_root_address(), None)?
.ok_or_else(|| Error::rpc_response("DiemRoot account is missing"))?;
let currency_infos = diem_root
.get_registered_currency_info_resources()
.map_err(Error::decode)?;
let currency_views = currency_infos.iter().map(CurrencyInfoView::from).collect();
Ok(MethodResponse::GetCurrencies(currency_views))
});
VerifyingRequest::new(request, subrequests, callback)
}
fn get_network_status() -> VerifyingRequest {
let request = MethodRequest::get_network_status();
let subrequests = vec![MethodRequest::get_network_status()];
let callback: RequestCallback = Box::new(|_ctxt, subresponses| {
let status = match subresponses {
[MethodResponse::GetNetworkStatus(ref status)] => *status,
subresponses => {
return Err(Error::rpc_response(format!(
"expected [GetNetworkStatus] subresponses, received: {:?}",
subresponses,
)))
}
};
Ok(MethodResponse::GetNetworkStatus(status))
});
VerifyingRequest::new(request, subrequests, callback)
}
fn verify_account_state(
ctxt: RequestContext<'_>,
view: &AccountStateWithProofView,
address: AccountAddress,
version: Option<Version>,
) -> Result<Option<AccountState>> {
let account_state_with_proof = AccountStateWithProof::try_from(view).map_err(Error::decode)?;
let latest_li = ctxt.state_proof.latest_ledger_info();
let ledger_version = latest_li.version();
let version = version.unwrap_or(ledger_version);
account_state_with_proof
.verify(latest_li, version, address)
.map_err(Error::invalid_proof)?;
account_state_with_proof
.blob
.map(|blob| AccountState::try_from(&blob).map_err(Error::decode))
.transpose()
}