casper-node 0.6.3

The Casper blockchain node
Documentation
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
//! RPCs related to finding information about currently supported RPCs.

// TODO - remove once schemars stops causing warning.
#![allow(clippy::field_reassign_with_default)]

use futures::{future::BoxFuture, FutureExt};
use http::Response;
use hyper::Body;
use once_cell::sync::Lazy;
use schemars::{
    gen::{SchemaGenerator, SchemaSettings},
    schema::Schema,
    JsonSchema, Map, MapEntry,
};
use semver::Version;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use warp_json_rpc::Builder;

use super::{
    account::PutDeploy,
    chain::{GetBlock, GetBlockTransfers, GetStateRootHash},
    info::{GetDeploy, GetPeers, GetStatus},
    state::{GetAuctionInfo, GetBalance, GetItem},
    Error, ReactorEventT, RpcWithOptionalParams, RpcWithParams, RpcWithoutParams,
    RpcWithoutParamsExt,
};
use crate::{
    components::CLIENT_API_VERSION, effect::EffectBuilder, rpcs::chain::GetEraInfoBySwitchBlock,
};

const DEFINITIONS_PATH: &str = "#/components/schemas/";

// As per https://spec.open-rpc.org/#service-discovery-method.
static OPEN_RPC_SCHEMA: Lazy<OpenRpcSchema> = Lazy::new(|| {
    let contact = OpenRpcContactField {
        name: "CasperLabs".to_string(),
        url: "https://casperlabs.io".to_string(),
    };
    let license = OpenRpcLicenseField {
        name: "CasperLabs Open Source License Version 1.0".to_string(),
        url: "https://raw.githubusercontent.com/CasperLabs/casper-node/master/LICENSE".to_string(),
    };
    let info = OpenRpcInfoField {
        version: CLIENT_API_VERSION.to_string(),
        title: "Client API of Casper Node".to_string(),
        description: "This describes the JSON-RPC 2.0 API of a node on the Casper network."
            .to_string(),
        contact,
        license,
    };

    let server = OpenRpcServerEntry {
        name: "any Casper Network node".to_string(),
        url: "http://IP:PORT/rpc/".to_string(),
    };

    let mut schema = OpenRpcSchema {
        openrpc: "1.0.0-rc1".to_string(),
        info,
        servers: vec![server],
        methods: vec![],
        components: Components {
            schemas: Map::new(),
        },
    };

    schema.push_with_params::<PutDeploy>("receives a Deploy to be executed by the network");
    schema.push_with_params::<GetDeploy>("returns a Deploy from the network");
    schema.push_without_params::<GetPeers>("returns a list of peers connected to the node");
    schema.push_without_params::<GetStatus>("returns the current status of the node");
    schema.push_with_optional_params::<GetBlock>("returns a Block from the network");
    schema.push_with_optional_params::<GetBlockTransfers>(
        "returns all transfers for a Block from the network",
    );
    schema.push_with_optional_params::<GetStateRootHash>(
        "returns a state root hash at a given Block",
    );
    schema.push_with_params::<GetItem>("returns a stored value from the network");
    schema.push_with_params::<GetBalance>("returns a purse's balance from the network");
    schema.push_with_optional_params::<GetEraInfoBySwitchBlock>(
        "returns an EraInfo from the network",
    );
    schema.push_without_params::<GetAuctionInfo>(
        "returns the bids and validators as of the most recently added Block",
    );

    schema
});
static LIST_RPCS_RESULT: Lazy<ListRpcsResult> = Lazy::new(|| ListRpcsResult {
    api_version: CLIENT_API_VERSION.clone(),
    name: "OpenRPC Schema".to_string(),
    schema: OPEN_RPC_SCHEMA.clone(),
});

/// A trait used to generate a static hardcoded example of `Self`.
pub trait DocExample {
    /// Generates a hardcoded example of `Self`.
    fn doc_example() -> &'static Self;
}

/// The main schema for the casper node's RPC server, compliant with https://spec.open-rpc.org.
#[derive(Clone, Serialize, Deserialize, Debug)]
struct OpenRpcSchema {
    openrpc: String,
    info: OpenRpcInfoField,
    servers: Vec<OpenRpcServerEntry>,
    methods: Vec<Method>,
    components: Components,
}

impl OpenRpcSchema {
    fn new_generator() -> SchemaGenerator {
        let settings = SchemaSettings::default().with(|settings| {
            settings.definitions_path = DEFINITIONS_PATH.to_string();
        });
        settings.into_generator()
    }

    fn push_with_params<T: RpcWithParams>(&mut self, summary: &str) {
        let mut generator = Self::new_generator();

        let params_schema = T::RequestParams::json_schema(&mut generator);
        let params = Self::make_params(params_schema);

        let result_schema = T::ResponseResult::json_schema(&mut generator);
        let result = ResponseResult {
            name: format!("{}_result", T::METHOD),
            schema: result_schema,
        };

        let examples = vec![Example::from_rpc_with_params::<T>()];

        let method = Method {
            name: T::METHOD.to_string(),
            summary: summary.to_string(),
            params,
            result,
            examples,
        };

        self.methods.push(method);
        self.update_schemas::<T::RequestParams>();
        self.update_schemas::<T::ResponseResult>();
    }

    fn push_without_params<T: RpcWithoutParams>(&mut self, summary: &str) {
        let mut generator = Self::new_generator();

        let result_schema = T::ResponseResult::json_schema(&mut generator);
        let result = ResponseResult {
            name: format!("{}_result", T::METHOD),
            schema: result_schema,
        };

        let examples = vec![Example::from_rpc_without_params::<T>()];

        let method = Method {
            name: T::METHOD.to_string(),
            summary: summary.to_string(),
            params: vec![],
            result,
            examples,
        };

        self.methods.push(method);
        self.update_schemas::<T::ResponseResult>();
    }

    fn push_with_optional_params<T: RpcWithOptionalParams>(&mut self, summary: &str) {
        let mut generator = Self::new_generator();

        let params_schema = T::OptionalRequestParams::json_schema(&mut generator);
        let params = Self::make_params(params_schema);

        let result_schema = T::ResponseResult::json_schema(&mut generator);
        let result = ResponseResult {
            name: format!("{}_result", T::METHOD),
            schema: result_schema,
        };

        let examples = vec![Example::from_rpc_with_optional_params::<T>()];

        // TODO - handle adding a description that the params may be omitted if desired.
        let method = Method {
            name: T::METHOD.to_string(),
            summary: summary.to_string(),
            params,
            result,
            examples,
        };

        self.methods.push(method);
        self.update_schemas::<T::OptionalRequestParams>();
        self.update_schemas::<T::ResponseResult>();
    }

    /// Convert the schema for the params type for T into the OpenRpc-compatible map of name, value
    /// pairs.
    ///
    /// As per the standard, the required params must be sorted before the optional ones.
    fn make_params(schema: Schema) -> Vec<SchemaParam> {
        let schema_object = schema.into_object().object.expect("should be object");
        let mut required_params = schema_object
            .properties
            .iter()
            .filter(|(name, _)| schema_object.required.contains(*name))
            .map(|(name, schema)| SchemaParam {
                name: name.clone(),
                schema: schema.clone(),
                required: true,
            })
            .collect::<Vec<_>>();
        let optional_params = schema_object
            .properties
            .iter()
            .filter(|(name, _)| !schema_object.required.contains(*name))
            .map(|(name, schema)| SchemaParam {
                name: name.clone(),
                schema: schema.clone(),
                required: false,
            })
            .collect::<Vec<_>>();
        required_params.extend(optional_params);
        required_params
    }

    /// Insert the new entries into the #/components/schemas/ map.  Panic if we try to overwrite an
    /// entry with a different value.
    fn update_schemas<S: JsonSchema>(&mut self) {
        let generator = Self::new_generator();
        let mut root_schema = generator.into_root_schema_for::<S>();
        for (key, value) in root_schema.definitions.drain(..) {
            match self.components.schemas.entry(key) {
                MapEntry::Occupied(current_value) => {
                    assert_eq!(
                        current_value.get().clone().into_object().metadata,
                        value.into_object().metadata
                    )
                }
                MapEntry::Vacant(vacant) => {
                    let _ = vacant.insert(value);
                }
            }
        }
    }
}

#[derive(Clone, Serialize, Deserialize, Debug)]
struct OpenRpcInfoField {
    version: String,
    title: String,
    description: String,
    contact: OpenRpcContactField,
    license: OpenRpcLicenseField,
}

#[derive(Clone, Serialize, Deserialize, Debug)]
struct OpenRpcContactField {
    name: String,
    url: String,
}

#[derive(Clone, Serialize, Deserialize, Debug)]
struct OpenRpcLicenseField {
    name: String,
    url: String,
}

#[derive(Clone, Serialize, Deserialize, Debug)]
struct OpenRpcServerEntry {
    name: String,
    url: String,
}

/// The struct containing the documentation for the RPCs.
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct Method {
    name: String,
    summary: String,
    params: Vec<SchemaParam>,
    result: ResponseResult,
    examples: Vec<Example>,
}

#[derive(Clone, Serialize, Deserialize, Debug)]
struct SchemaParam {
    name: String,
    schema: Schema,
    required: bool,
}

#[derive(Clone, Serialize, Deserialize, Debug)]
struct ResponseResult {
    name: String,
    schema: Schema,
}

/// An example pair of request params and response result.
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct Example {
    name: String,
    params: Vec<ExampleParam>,
    result: ExampleResult,
}

impl Example {
    fn new(method_name: &str, maybe_params_obj: Option<Value>, result_value: Value) -> Self {
        // Break the params struct into an array of param name and value pairs.
        let params = match maybe_params_obj {
            Some(params_obj) => params_obj
                .as_object()
                .unwrap()
                .iter()
                .map(|(name, value)| ExampleParam {
                    name: name.clone(),
                    value: value.clone(),
                })
                .collect(),
            None => vec![],
        };

        Example {
            name: format!("{}_example", method_name),
            params,
            result: ExampleResult {
                name: format!("{}_example_result", method_name),
                value: result_value,
            },
        }
    }

    fn from_rpc_with_params<T: RpcWithParams>() -> Self {
        Self::new(
            T::METHOD,
            Some(json!(T::RequestParams::doc_example())),
            json!(T::ResponseResult::doc_example()),
        )
    }

    fn from_rpc_without_params<T: RpcWithoutParams>() -> Self {
        Self::new(T::METHOD, None, json!(T::ResponseResult::doc_example()))
    }

    fn from_rpc_with_optional_params<T: RpcWithOptionalParams>() -> Self {
        Self::new(
            T::METHOD,
            Some(json!(T::OptionalRequestParams::doc_example())),
            json!(T::ResponseResult::doc_example()),
        )
    }
}

#[derive(Clone, Serialize, Deserialize, Debug)]
struct ExampleParam {
    name: String,
    value: Value,
}

#[derive(Clone, Serialize, Deserialize, Debug)]
struct ExampleResult {
    name: String,
    value: Value,
}

#[derive(Clone, Serialize, Deserialize, Debug)]
struct Components {
    schemas: Map<String, Schema>,
}

/// Result for "rpc.discover" RPC response.
//
// Fields named as per https://spec.open-rpc.org/#service-discovery-method.
#[derive(Clone, Serialize, Deserialize, JsonSchema, Debug)]
#[serde(deny_unknown_fields)]
pub struct ListRpcsResult {
    /// The RPC API version.
    #[schemars(with = "String")]
    api_version: Version,
    name: String,
    /// The list of supported RPCs.
    #[schemars(skip)]
    schema: OpenRpcSchema,
}

impl DocExample for ListRpcsResult {
    fn doc_example() -> &'static Self {
        &*LIST_RPCS_RESULT
    }
}

/// "rpc.discover" RPC.
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct ListRpcs {}

impl RpcWithoutParams for ListRpcs {
    // Named as per https://spec.open-rpc.org/#service-discovery-method.
    const METHOD: &'static str = "rpc.discover";
    type ResponseResult = ListRpcsResult;
}

impl RpcWithoutParamsExt for ListRpcs {
    fn handle_request<REv: ReactorEventT>(
        _effect_builder: EffectBuilder<REv>,
        response_builder: Builder,
    ) -> BoxFuture<'static, Result<Response<Body>, Error>> {
        async move { Ok(response_builder.success(ListRpcsResult::doc_example().clone())?) }.boxed()
    }
}