exonum-system-api 1.0.0

System API plugin for the Exonum framework
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
// Copyright 2020 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Private part of the node REST API.
//!
//! Private API includes requests that are available only to the blockchain
//! administrators, e.g. shutting down the node.
//!
//! # Table of Contents
//!
//! - [Get node info](#get-node-info)
//! - [Get node statistics](#get-node-statistics)
//! - [Add peer](#add-peer)
//! - [Change consensus status](#change-consensus-status)
//! - [Node shutdown](#node-shutdown)
//!
//! # Get Node Info
//!
//! | Property    | Value |
//! |-------------|-------|
//! | Path        | `/api/system/v1/info` |
//! | Method      | GET   |
//! | Query type  | - |
//! | Return type | [`NodeInfo`] |
//!
//! Obtains information about node.
//!
//! [`NodeInfo`]: struct.NodeInfo.html
//!
//! ```
//! use exonum_system_api::{private::NodeInfo, SystemApiPlugin};
//! use exonum_testkit::{ApiKind, TestKitBuilder};
//!
//! # #[tokio::main]
//! # async fn main() -> anyhow::Result<()> {
//! let mut testkit = TestKitBuilder::validator()
//!     .with_plugin(SystemApiPlugin)
//!     .build();
//! let api = testkit.api();
//! let info: NodeInfo = api.private(ApiKind::System).get("v1/info").await?;
//! # Ok(())
//! # }
//! ```
//!
//! # Get Node Statistics
//!
//! | Property    | Value |
//! |-------------|-------|
//! | Path        | `/api/system/v1/stats` |
//! | Method      | GET   |
//! | Query type  | - |
//! | Return type | [`NodeStats`] |
//!
//! Returns the statistics of the current node.
//!
//! [`PeersInfo`]: struct.NodeStats.html
//!
//! ```
//! use exonum_system_api::{private::NodeStats, SystemApiPlugin};
//! use exonum_testkit::{ApiKind, TestKitBuilder};
//!
//! # #[tokio::main]
//! # async fn main() -> anyhow::Result<()> {
//! let mut testkit = TestKitBuilder::validator()
//!     .with_plugin(SystemApiPlugin)
//!     .build();
//! let api = testkit.api();
//! let info: NodeStats = api.private(ApiKind::System).get("v1/stats").await?;
//! # Ok(())
//! # }
//! ```
//!
//! # Add Peer
//!
//! | Property    | Value |
//! |-------------|-------|
//! | Path        | `/api/system/v1/peers` |
//! | Method      | POST   |
//! | Query type  | [`ConnectInfo`] |
//! | Return type | - |
//!
//! Adds a peer to the Exonum node. Node will attempt to connect to this peer.
//! After adding a new peer the node config file will be rewritten.
//!
//! [`ConnectInfo`]: https://docs.rs/exonum-node/latest/exonum_node/struct.ConnectInfo.html
//!
//! ```
//! use exonum_node::ConnectInfo;
//! use exonum_system_api::SystemApiPlugin;
//! use exonum_testkit::{ApiKind, TestKitBuilder};
//!
//! # #[tokio::main]
//! # async fn main() -> anyhow::Result<()> {
//! # let address = "127.0.0.1:8080".to_owned();
//! # let public_key = Default::default();
//! // Obtaining address and public key of target node skipped...
//! let connect_info = ConnectInfo {
//!     address,
//!     public_key,
//! };
//!
//! let mut testkit = TestKitBuilder::validator()
//!     .with_plugin(SystemApiPlugin)
//!     .build();
//! let api = testkit.api();
//! api.private(ApiKind::System)
//!     .query(&connect_info)
//!     .post("v1/peers")
//!     .await?;
//! # Ok(())
//! # }
//! ```
//!
//! # Change Consensus Status
//!
//! | Property    | Value |
//! |-------------|-------|
//! | Path        | `/api/system/v1/consensus_status` |
//! | Method      | POST   |
//! | Query type  | [`ConsensusEnabledQuery`] |
//! | Return type | - |
//!
//! Enables or disables consensus on the node.
//!
//! [`ConsensusEnabledQuery`]: struct.ConsensusEnabledQuery.html
//!
//! ```
//! use exonum_system_api::{private::ConsensusEnabledQuery, SystemApiPlugin};
//! use exonum_testkit::{ApiKind, TestKitBuilder};
//!
//! # #[tokio::main]
//! # async fn main() -> anyhow::Result<()> {
//! let mut testkit = TestKitBuilder::validator()
//!     .with_plugin(SystemApiPlugin)
//!     .build();
//! let api = testkit.api();
//! let enabled = true;
//! let query = ConsensusEnabledQuery::new(enabled);
//! api.private(ApiKind::System)
//!     .query(&query)
//!     .post("v1/consensus_status")
//!     .await?;
//! # Ok(())
//! # }
//! ```
//!
//! # Node Shutdown
//!
//! | Property    | Value |
//! |-------------|-------|
//! | Path        | `/api/system/v1/shutdown` |
//! | Method      | POST   |
//! | Query type  | - |
//! | Return type | - |
//!
//! Shuts down the node.
//!
//! ```
//! use exonum_system_api::SystemApiPlugin;
//! use exonum_testkit::{ApiKind, TestKitBuilder};
//!
//! # #[tokio::main]
//! # async fn main() -> anyhow::Result<()> {
//! let mut testkit = TestKitBuilder::validator()
//!     .with_plugin(SystemApiPlugin)
//!     .build();
//! let api = testkit.api();
//! api.private(ApiKind::System)
//!     .post::<()>("v1/shutdown")
//!     .await?;
//! # Ok(())
//! # }
//! ```
// limitations under the License.

use exonum::{
    blockchain::{ApiSender, Blockchain, Schema},
    crypto::PublicKey,
    helpers::{exonum_version, os_info, rust_version},
};
use exonum_api::{self as api, ApiBackend, ApiScope};
use exonum_node::{ConnectInfo, ExternalMessage, SharedNodeState};
use futures::{future, prelude::*};
use semver::Version;
use serde::{Deserialize, Serialize};
use std::{sync::Arc, time::SystemTime};

/// Information about the current state of the node.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct NodeStats {
    /// Height of the blockchain.
    pub height: u64,
    /// Total number of uncommitted transactions stored in persistent pool.
    pub tx_pool_size: u64,
    /// Total number of transactions in the blockchain.
    pub tx_count: u64,
    /// Size of the transaction cache.
    pub tx_cache_size: usize,
    /// Work duration of the node in seconds.
    pub uptime: u64,
}

/// Consensus status of the current node.
#[derive(Deserialize, Serialize, Clone, Debug, PartialEq)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ConsensusStatus {
    /// Consensus disabled on this node.
    Disabled,
    /// Consensus enabled on this node.
    Enabled,
    /// Consensus enabled and the node has enough connected peers.
    Active,
}

/// Type of the network connection.
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ConnectDirection {
    /// Incoming connection.
    Incoming,
    /// Outgoing connection.
    Outgoing,
}

/// Info about connected peer.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct ConnectedPeerInfo {
    /// Address of the peer.
    pub address: String,
    /// Consensus public key of the peer.
    pub public_key: PublicKey,
    /// Connect direction.
    pub direction: ConnectDirection,
}

impl ConnectedPeerInfo {
    fn new(connect_info: &ConnectInfo, direction: ConnectDirection) -> Self {
        Self {
            address: connect_info.address.to_owned(),
            public_key: connect_info.public_key,
            direction,
        }
    }
}

/// Short information about the current node.
#[derive(Serialize, Deserialize, Clone, Debug)]
#[non_exhaustive]
pub struct NodeInfo {
    /// Consensus status.
    pub consensus_status: ConsensusStatus,
    /// List of connected peers.
    pub connected_peers: Vec<ConnectedPeerInfo>,
    /// Version of the `exonum` crate.
    pub exonum_version: Version,
    /// Rust version.
    pub rust_version: Version,
    /// OS info.
    pub os_info: String,
}

/// Query for setting consensus enabled or disabled.
#[derive(Serialize, Deserialize, Clone, Debug)]
#[non_exhaustive]
pub struct ConsensusEnabledQuery {
    /// Denotes if consensus should be enabled or disabled.
    pub enabled: bool,
}

impl ConsensusEnabledQuery {
    /// Creates a new consensus switch query.
    pub fn new(enabled: bool) -> Self {
        Self { enabled }
    }
}

/// Private system API.
#[derive(Clone, Debug)]
pub(super) struct SystemApi {
    blockchain: Blockchain,
    shared_api_state: SharedNodeState,
    sender: ApiSender<ExternalMessage>,
    start_time: SystemTime,
}

impl SystemApi {
    /// Create a new `private::SystemApi` instance.
    pub fn new(
        blockchain: Blockchain,
        sender: ApiSender<ExternalMessage>,
        shared_api_state: SharedNodeState,
    ) -> Self {
        Self {
            blockchain,
            sender,
            shared_api_state,
            start_time: SystemTime::now(),
        }
    }

    /// Add private system API endpoints to the corresponding scope.
    pub fn wire(self, api_scope: &mut ApiScope) -> &mut ApiScope {
        self.handle_info("v1/info", api_scope)
            .handle_stats("v1/stats", api_scope)
            .handle_peers("v1/peers", api_scope)
            .handle_consensus_status("v1/consensus_status", api_scope)
            .handle_shutdown("v1/shutdown", api_scope);
        api_scope
    }

    fn handle_info(self, name: &'static str, api_scope: &mut ApiScope) -> Self {
        let shared_api_state = self.shared_api_state.clone();
        api_scope.endpoint(name, move |_query: ()| {
            let mut connected_peers = Vec::new();

            for connect_info in shared_api_state.outgoing_connections() {
                connected_peers.push(ConnectedPeerInfo::new(
                    &connect_info,
                    ConnectDirection::Outgoing,
                ));
            }

            for connect_info in shared_api_state.incoming_connections() {
                connected_peers.push(ConnectedPeerInfo::new(
                    &connect_info,
                    ConnectDirection::Incoming,
                ));
            }

            let info = NodeInfo {
                consensus_status: Self::get_consensus_status(&shared_api_state),
                connected_peers,
                exonum_version: exonum_version().unwrap_or_else(|| Version::new(0, 0, 0)),
                rust_version: rust_version().unwrap_or_else(|| Version::new(0, 0, 0)),
                os_info: os_info(),
            };

            future::ok(info)
        });
        self
    }

    fn handle_stats(self, name: &'static str, api_scope: &mut ApiScope) -> Self {
        let this = self.clone();
        api_scope.endpoint(name, move |_query: ()| {
            let snapshot = this.blockchain.snapshot();
            let schema = Schema::new(&snapshot);
            let uptime = SystemTime::now()
                .duration_since(this.start_time)
                .unwrap_or_default()
                .as_secs();
            let stats = NodeStats {
                height: schema.height().into(),
                tx_pool_size: schema.transactions_pool_len(),
                tx_count: schema.transactions_len(),
                tx_cache_size: this.shared_api_state.tx_cache_size(),
                uptime,
            };

            future::ok(stats)
        });
        self
    }

    fn handle_peers(self, name: &'static str, api_scope: &mut ApiScope) -> Self {
        let sender = self.sender.clone();
        api_scope.endpoint_mut(name, move |connect_info: ConnectInfo| {
            let mut sender = sender.clone();
            async move {
                sender
                    .send_message(ExternalMessage::PeerAdd(connect_info))
                    .await
                    .map_err(|e| api::Error::internal(e).title("Failed to add peer"))
            }
        });
        self
    }

    fn handle_consensus_status(self, name: &'static str, api_scope: &mut ApiScope) -> Self {
        let sender = self.sender.clone();
        api_scope.endpoint_mut(name, move |query: ConsensusEnabledQuery| {
            let mut sender = sender.clone();
            async move {
                sender
                    .send_message(ExternalMessage::Enable(query.enabled))
                    .await
                    .map_err(|e| api::Error::internal(e).title("Failed to set consensus enabled"))
            }
        });
        self
    }

    fn handle_shutdown(self, name: &'static str, api_scope: &mut ApiScope) -> Self {
        // These backend-dependent uses are needed to provide realization of the support of empty
        // request which is not easy in the generic approach, so it will be harder to misuse
        // those features (and as a result get a completely backend-dependent code).
        use actix_web::HttpResponse;
        use exonum_api::backends::actix::{RawHandler, RequestHandler};

        let sender = self.sender.clone();
        let index = move |_, _| {
            let mut sender = sender.clone();
            async move {
                sender
                    .send_message(ExternalMessage::Shutdown)
                    .await
                    .map(|_| HttpResponse::Ok().json(()))
                    .map_err(|e| {
                        api::Error::internal(e)
                            .title("Failed to handle shutdown")
                            .into()
                    })
            }
            .boxed_local()
        };

        let handler = RequestHandler {
            name: name.to_owned(),
            method: actix_web::http::Method::POST,
            inner: Arc::new(index) as Arc<RawHandler>,
        };
        api_scope.web_backend().raw_handler(handler);

        self
    }

    fn get_consensus_status(state: &SharedNodeState) -> ConsensusStatus {
        if state.is_enabled() {
            if state.consensus_status() {
                ConsensusStatus::Active
            } else {
                ConsensusStatus::Enabled
            }
        } else {
            ConsensusStatus::Disabled
        }
    }
}