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
#![allow(clippy::field_reassign_with_default)]
mod era_summary;
use std::{num::ParseIntError, str};
use futures::{future::BoxFuture, FutureExt};
use http::Response;
use hyper::Body;
use once_cell::sync::Lazy;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use tracing::info;
use warp_json_rpc::Builder;
use casper_hashing::Digest;
use casper_types::{Key, ProtocolVersion, Transfer};
use super::{
docs::{DocExample, DOCS_EXAMPLE_PROTOCOL_VERSION},
Error, ErrorCode, ReactorEventT, RpcRequest, RpcWithOptionalParams, RpcWithOptionalParamsExt,
};
use crate::{
effect::EffectBuilder,
reactor::QueueKind,
rpcs::common,
types::{Block, BlockHash, BlockSignatures, Item, JsonBlock},
};
pub use era_summary::EraSummary;
use era_summary::ERA_SUMMARY;
static GET_BLOCK_PARAMS: Lazy<GetBlockParams> = Lazy::new(|| GetBlockParams {
block_identifier: BlockIdentifier::Hash(Block::doc_example().id()),
});
static GET_BLOCK_RESULT: Lazy<GetBlockResult> = Lazy::new(|| GetBlockResult {
api_version: DOCS_EXAMPLE_PROTOCOL_VERSION,
block: Some(JsonBlock::doc_example().clone()),
});
static GET_BLOCK_TRANSFERS_PARAMS: Lazy<GetBlockTransfersParams> =
Lazy::new(|| GetBlockTransfersParams {
block_identifier: BlockIdentifier::Hash(Block::doc_example().id()),
});
static GET_BLOCK_TRANSFERS_RESULT: Lazy<GetBlockTransfersResult> =
Lazy::new(|| GetBlockTransfersResult {
api_version: DOCS_EXAMPLE_PROTOCOL_VERSION,
block_hash: Some(Block::doc_example().id()),
transfers: Some(vec![Transfer::default()]),
});
static GET_STATE_ROOT_HASH_PARAMS: Lazy<GetStateRootHashParams> =
Lazy::new(|| GetStateRootHashParams {
block_identifier: BlockIdentifier::Height(Block::doc_example().header().height()),
});
static GET_STATE_ROOT_HASH_RESULT: Lazy<GetStateRootHashResult> =
Lazy::new(|| GetStateRootHashResult {
api_version: DOCS_EXAMPLE_PROTOCOL_VERSION,
state_root_hash: Some(*Block::doc_example().header().state_root_hash()),
});
static GET_ERA_INFO_PARAMS: Lazy<GetEraInfoParams> = Lazy::new(|| GetEraInfoParams {
block_identifier: BlockIdentifier::Hash(Block::doc_example().id()),
});
static GET_ERA_INFO_RESULT: Lazy<GetEraInfoResult> = Lazy::new(|| GetEraInfoResult {
api_version: DOCS_EXAMPLE_PROTOCOL_VERSION,
era_summary: Some(ERA_SUMMARY.clone()),
});
#[derive(Serialize, Deserialize, Debug, Clone, Copy, JsonSchema)]
#[serde(deny_unknown_fields)]
pub enum BlockIdentifier {
Hash(BlockHash),
Height(u64),
}
impl str::FromStr for BlockIdentifier {
type Err = ParseBlockIdentifierError;
fn from_str(maybe_block_identifier: &str) -> Result<Self, Self::Err> {
if maybe_block_identifier.is_empty() {
return Err(ParseBlockIdentifierError::EmptyString);
}
if maybe_block_identifier.len() == (Digest::LENGTH * 2) {
let hash = Digest::from_hex(maybe_block_identifier)
.map_err(ParseBlockIdentifierError::FromHexError)?;
Ok(BlockIdentifier::Hash(BlockHash::new(hash)))
} else {
let height = maybe_block_identifier
.parse()
.map_err(ParseBlockIdentifierError::ParseIntError)?;
Ok(BlockIdentifier::Height(height))
}
}
}
#[derive(thiserror::Error, Debug)]
pub enum ParseBlockIdentifierError {
#[error("Empty string is not a valid block identifier.")]
EmptyString,
#[error("Unable to parse height from string. {0}")]
ParseIntError(ParseIntError),
#[error("Unable to parse digest from string. {0}")]
FromHexError(casper_hashing::Error),
}
#[derive(Serialize, Deserialize, Debug, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct GetBlockParams {
pub block_identifier: BlockIdentifier,
}
impl DocExample for GetBlockParams {
fn doc_example() -> &'static Self {
&*GET_BLOCK_PARAMS
}
}
#[derive(Serialize, Deserialize, Debug, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct GetBlockResult {
#[schemars(with = "String")]
pub api_version: ProtocolVersion,
pub block: Option<JsonBlock>,
}
impl DocExample for GetBlockResult {
fn doc_example() -> &'static Self {
&*GET_BLOCK_RESULT
}
}
pub struct GetBlock {}
impl RpcWithOptionalParams for GetBlock {
const METHOD: &'static str = "chain_get_block";
type OptionalRequestParams = GetBlockParams;
type ResponseResult = GetBlockResult;
}
impl RpcWithOptionalParamsExt for GetBlock {
fn handle_request<REv: ReactorEventT>(
effect_builder: EffectBuilder<REv>,
response_builder: Builder,
maybe_params: Option<Self::OptionalRequestParams>,
api_version: ProtocolVersion,
) -> BoxFuture<'static, Result<Response<Body>, Error>> {
async move {
let maybe_block_id = maybe_params.map(|params| params.block_identifier);
let (block, signatures) =
match get_block_with_metadata(maybe_block_id, effect_builder).await {
Ok(Some((block, signatures))) => (block, signatures),
Ok(None) => {
let error = warp_json_rpc::Error::custom(
ErrorCode::NoSuchBlock as i64,
"block not known",
);
return Ok(response_builder.error(error)?);
}
Err(error) => return Ok(response_builder.error(error)?),
};
let json_block = JsonBlock::new(block, Some(signatures));
let result = Self::ResponseResult {
api_version,
block: Some(json_block),
};
Ok(response_builder.success(result)?)
}
.boxed()
}
}
#[derive(Serialize, Deserialize, Debug, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct GetBlockTransfersParams {
pub block_identifier: BlockIdentifier,
}
impl DocExample for GetBlockTransfersParams {
fn doc_example() -> &'static Self {
&*GET_BLOCK_TRANSFERS_PARAMS
}
}
#[derive(Serialize, Deserialize, Debug, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct GetBlockTransfersResult {
#[schemars(with = "String")]
pub api_version: ProtocolVersion,
pub block_hash: Option<BlockHash>,
pub transfers: Option<Vec<Transfer>>,
}
impl GetBlockTransfersResult {
pub fn new(
api_version: ProtocolVersion,
block_hash: Option<BlockHash>,
transfers: Option<Vec<Transfer>>,
) -> Self {
GetBlockTransfersResult {
api_version,
block_hash,
transfers,
}
}
}
impl DocExample for GetBlockTransfersResult {
fn doc_example() -> &'static Self {
&*GET_BLOCK_TRANSFERS_RESULT
}
}
pub struct GetBlockTransfers {}
impl RpcWithOptionalParams for GetBlockTransfers {
const METHOD: &'static str = "chain_get_block_transfers";
type OptionalRequestParams = GetBlockTransfersParams;
type ResponseResult = GetBlockTransfersResult;
}
impl RpcWithOptionalParamsExt for GetBlockTransfers {
fn handle_request<REv: ReactorEventT>(
effect_builder: EffectBuilder<REv>,
response_builder: Builder,
maybe_params: Option<Self::OptionalRequestParams>,
api_version: ProtocolVersion,
) -> BoxFuture<'static, Result<Response<Body>, Error>> {
async move {
let maybe_block_id = maybe_params.map(|params| params.block_identifier);
let block_hash = match get_block(maybe_block_id, effect_builder).await {
Ok(Some(block)) => *block.hash(),
Ok(None) => {
return Ok(response_builder.success(Self::ResponseResult::new(
api_version,
None,
None,
))?)
}
Err(error) => return Ok(response_builder.error(error)?),
};
let transfers = effect_builder
.make_request(
|responder| RpcRequest::GetBlockTransfers {
block_hash,
responder,
},
QueueKind::Api,
)
.await;
let result = Self::ResponseResult::new(api_version, Some(block_hash), transfers);
Ok(response_builder.success(result)?)
}
.boxed()
}
}
#[derive(Serialize, Deserialize, Debug, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct GetStateRootHashParams {
pub block_identifier: BlockIdentifier,
}
impl DocExample for GetStateRootHashParams {
fn doc_example() -> &'static Self {
&*GET_STATE_ROOT_HASH_PARAMS
}
}
#[derive(Serialize, Deserialize, Debug, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct GetStateRootHashResult {
#[schemars(with = "String")]
pub api_version: ProtocolVersion,
pub state_root_hash: Option<Digest>,
}
impl DocExample for GetStateRootHashResult {
fn doc_example() -> &'static Self {
&*GET_STATE_ROOT_HASH_RESULT
}
}
pub struct GetStateRootHash {}
impl RpcWithOptionalParams for GetStateRootHash {
const METHOD: &'static str = "chain_get_state_root_hash";
type OptionalRequestParams = GetStateRootHashParams;
type ResponseResult = GetStateRootHashResult;
}
impl RpcWithOptionalParamsExt for GetStateRootHash {
fn handle_request<REv: ReactorEventT>(
effect_builder: EffectBuilder<REv>,
response_builder: Builder,
maybe_params: Option<Self::OptionalRequestParams>,
api_version: ProtocolVersion,
) -> BoxFuture<'static, Result<Response<Body>, Error>> {
async move {
let maybe_block_id = maybe_params.map(|params| params.block_identifier);
let maybe_block = match get_block(maybe_block_id, effect_builder).await {
Ok(maybe_block) => maybe_block,
Err(error) => return Ok(response_builder.error(error)?),
};
let result = Self::ResponseResult {
api_version,
state_root_hash: maybe_block.map(|block| *block.state_root_hash()),
};
Ok(response_builder.success(result)?)
}
.boxed()
}
}
#[derive(Serialize, Deserialize, Debug, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct GetEraInfoParams {
pub block_identifier: BlockIdentifier,
}
impl DocExample for GetEraInfoParams {
fn doc_example() -> &'static Self {
&*GET_ERA_INFO_PARAMS
}
}
#[derive(Serialize, Deserialize, Debug, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct GetEraInfoResult {
#[schemars(with = "String")]
pub api_version: ProtocolVersion,
pub era_summary: Option<EraSummary>,
}
impl DocExample for GetEraInfoResult {
fn doc_example() -> &'static Self {
&*GET_ERA_INFO_RESULT
}
}
pub struct GetEraInfoBySwitchBlock {}
impl RpcWithOptionalParams for GetEraInfoBySwitchBlock {
const METHOD: &'static str = "chain_get_era_info_by_switch_block";
type OptionalRequestParams = GetEraInfoParams;
type ResponseResult = GetEraInfoResult;
}
impl RpcWithOptionalParamsExt for GetEraInfoBySwitchBlock {
fn handle_request<REv: ReactorEventT>(
effect_builder: EffectBuilder<REv>,
response_builder: Builder,
maybe_params: Option<Self::OptionalRequestParams>,
api_version: ProtocolVersion,
) -> BoxFuture<'static, Result<Response<Body>, Error>> {
async move {
let maybe_block_id = maybe_params.map(|params| params.block_identifier);
let maybe_block = match get_block(maybe_block_id, effect_builder).await {
Ok(maybe_block) => maybe_block,
Err(error) => return Ok(response_builder.error(error)?),
};
let block = match maybe_block {
Some(block) => block,
None => {
return Ok(response_builder.success(Self::ResponseResult {
api_version,
era_summary: None,
})?)
}
};
let era_id = match block.header().era_end() {
Some(_) => block.header().era_id(),
None => {
return Ok(response_builder.success(Self::ResponseResult {
api_version,
era_summary: None,
})?)
}
};
let state_root_hash = block.state_root_hash().to_owned();
let base_key = Key::EraInfo(era_id);
let path = Vec::new();
let query_result = effect_builder
.make_request(
|responder| RpcRequest::QueryGlobalState {
state_root_hash,
base_key,
path,
responder,
},
QueueKind::Api,
)
.await;
let (stored_value, proof_bytes) = match common::extract_query_result(query_result) {
Ok(tuple) => tuple,
Err((error_code, error_msg)) => {
info!("{}", error_msg);
return Ok(response_builder
.error(warp_json_rpc::Error::custom(error_code as i64, error_msg))?);
}
};
let block_hash = block.hash().to_owned();
let result = Self::ResponseResult {
api_version,
era_summary: Some(EraSummary {
block_hash,
era_id,
stored_value,
state_root_hash,
merkle_proof: base16::encode_lower(&proof_bytes),
}),
};
Ok(response_builder.success(result)?)
}
.boxed()
}
}
async fn get_block<REv: ReactorEventT>(
maybe_id: Option<BlockIdentifier>,
effect_builder: EffectBuilder<REv>,
) -> Result<Option<Block>, warp_json_rpc::Error> {
match get_block_with_metadata(maybe_id, effect_builder).await {
Ok(Some((block, _))) => Ok(Some(block)),
Ok(None) => Err(warp_json_rpc::Error::custom(
ErrorCode::NoSuchBlock as i64,
"block not known",
)),
Err(error) => Err(error),
}
}
async fn get_block_with_metadata<REv: ReactorEventT>(
maybe_id: Option<BlockIdentifier>,
effect_builder: EffectBuilder<REv>,
) -> Result<Option<(Block, BlockSignatures)>, warp_json_rpc::Error> {
let getting_specific_block = maybe_id.is_some();
let maybe_result = effect_builder
.make_request(
|responder| RpcRequest::GetBlock {
maybe_id,
responder,
},
QueueKind::Api,
)
.await;
if maybe_result.is_none() && getting_specific_block {
info!("failed to get {:?} from storage", maybe_id.unwrap());
return Err(warp_json_rpc::Error::custom(
ErrorCode::NoSuchBlock as i64,
"block not known",
));
}
Ok(maybe_result)
}