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
// Copyright 2018 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.

//! API and corresponding utilities.

pub use self::error::Error;
pub use self::state::ServiceApiState;
pub use self::with::{FutureResult, Immutable, Mutable, NamedWith, Result, With};

use serde::{de::DeserializeOwned, Serialize};

use std::{collections::BTreeMap, fmt};

use self::backends::actix;
use blockchain::{Blockchain, SharedNodeState};
use crypto::PublicKey;
use node::ApiSender;

pub mod backends;
pub mod error;
pub mod node;
mod state;
mod with;

/// Defines object that could be used as an API backend.
pub trait ServiceApiBackend: Sized {
    /// Concrete endpoint handler in the backend.
    type Handler;
    /// Concrete backend API builder.
    type Backend;

    /// Adds the given endpoint handler to the backend.
    fn endpoint<N, Q, I, R, F, E>(&mut self, name: N, endpoint: E) -> &mut Self
    where
        N: Into<String>,
        Q: DeserializeOwned + 'static,
        I: Serialize + 'static,
        F: for<'r> Fn(&'r ServiceApiState, Q) -> R + 'static + Clone,
        E: Into<With<Q, I, R, F>>,
        Self::Handler: From<NamedWith<Q, I, R, F, Immutable>>,
    {
        let named_with = NamedWith::new(name, endpoint);
        self.raw_handler(Self::Handler::from(named_with))
    }

    /// Adds the given mutable endpoint handler to the backend.
    fn endpoint_mut<N, Q, I, R, F, E>(&mut self, name: N, endpoint: E) -> &mut Self
    where
        N: Into<String>,
        Q: DeserializeOwned + 'static,
        I: Serialize + 'static,
        F: for<'r> Fn(&'r ServiceApiState, Q) -> R + 'static + Clone,
        E: Into<With<Q, I, R, F>>,
        Self::Handler: From<NamedWith<Q, I, R, F, Mutable>>,
    {
        let named_with = NamedWith::new(name, endpoint);
        self.raw_handler(Self::Handler::from(named_with))
    }

    /// Adds the raw endpoint handler for the given backend.
    fn raw_handler(&mut self, handler: Self::Handler) -> &mut Self;

    /// Binds API handlers to the given backend.
    fn wire(&self, output: Self::Backend) -> Self::Backend;
}

/// Service API builder for the concrete API scope or in other words
/// access level (public or private).
#[derive(Debug, Clone, Default)]
pub struct ServiceApiScope {
    pub(crate) actix_backend: actix::ApiBuilder,
}

impl ServiceApiScope {
    /// Creates a new instance.
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds the given endpoint handler to the API scope.
    ///
    /// For now there is only web backend and it has the following requirements:
    ///
    /// - Query parameters should be decodable via `serde_urlencoded`, i.e. from the
    ///   "first_param=value1&second_param=value2" form.
    /// - Response items should be encodable via `serde_json` crate.
    pub fn endpoint<Q, I, R, F, E>(&mut self, name: &'static str, endpoint: E) -> &mut Self
    where
        Q: DeserializeOwned + 'static,
        I: Serialize + 'static,
        F: for<'r> Fn(&'r ServiceApiState, Q) -> R + 'static + Clone,
        E: Into<With<Q, I, R, F>>,
        actix::RequestHandler: From<NamedWith<Q, I, R, F, Immutable>>,
    {
        self.actix_backend.endpoint(name, endpoint);
        self
    }

    /// Adds the given mutable endpoint handler to the API scope.
    ///
    /// For now there is only web backend and it has the following requirements:
    ///
    /// - Query parameters should be decodable via `serde_json`.
    /// - Response items also should be encodable via `serde_json` crate.
    pub fn endpoint_mut<Q, I, R, F, E>(&mut self, name: &'static str, endpoint: E) -> &mut Self
    where
        Q: DeserializeOwned + 'static,
        I: Serialize + 'static,
        F: for<'r> Fn(&'r ServiceApiState, Q) -> R + 'static + Clone,
        E: Into<With<Q, I, R, F>>,
        actix::RequestHandler: From<NamedWith<Q, I, R, F, Mutable>>,
    {
        self.actix_backend.endpoint_mut(name, endpoint);
        self
    }

    /// Returns a mutable reference to the underlying web backend.
    pub fn web_backend(&mut self) -> &mut actix::ApiBuilder {
        &mut self.actix_backend
    }
}

/// Service API builder, which is used to add service-specific endpoints to the node API.
///
/// # Examples
///
/// The example below shows a common practice of API implementation.
///
/// ```rust
/// #[macro_use] extern crate exonum;
/// #[macro_use] extern crate serde_derive;
/// extern crate futures;
///
/// use futures::Future;
///
/// use std::net::SocketAddr;
///
/// use exonum::api::{self, ServiceApiBuilder, ServiceApiState};
/// use exonum::blockchain::{Schema};
/// use exonum::crypto::Hash;
///
/// // Declares a type which describes an API specification and implementation.
/// pub struct MyApi;
///
/// // Declares structures for requests and responses.
///
/// // For the web backend `MyQuery` will be deserialized from the `block_height={number}` string.
/// #[derive(Deserialize, Clone, Copy)]
/// pub struct MyQuery {
///     pub block_height: u64
/// }
///
/// // For the web backend `BlockInfo` will be serialized into the JSON string.
/// #[derive(Serialize, Clone, Copy)]
/// pub struct BlockInfo {
///     pub hash: Hash,
/// }
///
/// // Creates API handlers.
/// impl MyApi {
///     // Immutable handler, which returns a hash of the block at the given height.
///     pub fn block_hash(state: &ServiceApiState, query: MyQuery) -> api::Result<Option<BlockInfo>> {
///         let schema = Schema::new(state.snapshot());
///         Ok(schema.block_hashes_by_height()
///             .get(query.block_height)
///             .map(|hash| BlockInfo { hash })
///         )
///     }
///
///     // Mutable handler which removes peer with the given address from the cache.
///     pub fn remove_peer(state: &ServiceApiState, query: SocketAddr) -> api::Result<()> {
///         let mut blockchain = state.blockchain().clone();
///         Ok(blockchain.remove_peer_with_addr(&query))
///     }
///
///     // Simple handler without any params.
///     pub fn ping(_state: &ServiceApiState, _query: ()) -> api::Result<()> {
///         Ok(())
///     }
///
///     // You may also creates an asynchronous handlers for the long requests.
///     pub fn block_hash_async(state: &ServiceApiState, query: MyQuery)
///      -> api::FutureResult<Option<Hash>> {
///         let blockchain = state.blockchain().clone();
///         Box::new(futures::lazy(move || {
///             let schema = Schema::new(blockchain.snapshot());
///             Ok(schema.block_hashes_by_height().get(query.block_height))
///         }))
///     }
/// }
///
/// # let mut builder = ServiceApiBuilder::default();
/// // Adds `MyApi` handlers to the corresponding builder.
/// builder.public_scope()
///     .endpoint("v1/ping", MyApi::ping)
///     .endpoint("v1/block_hash", MyApi::block_hash)
///     .endpoint("v1/block_hash_async", MyApi::block_hash_async);
/// // Adds a mutable endpoint for to the private API.
/// builder.private_scope()
///     .endpoint_mut("v1/remove_peer", MyApi::remove_peer);
/// ```
#[derive(Debug, Clone, Default)]
pub struct ServiceApiBuilder {
    blockchain: Option<Blockchain>,
    public_scope: ServiceApiScope,
    private_scope: ServiceApiScope,
}

impl ServiceApiBuilder {
    /// Creates a new service API builder.
    pub fn new() -> Self {
        Self {
            blockchain: None,
            ..Default::default()
        }
    }

    fn with_blockchain(blockchain: Blockchain) -> Self {
        Self {
            blockchain: Some(blockchain),
            ..Default::default()
        }
    }

    /// Returns a mutable reference to the public API scope builder.
    pub fn public_scope(&mut self) -> &mut ServiceApiScope {
        &mut self.public_scope
    }

    /// Returns a mutable reference to the private API scope builder.
    pub fn private_scope(&mut self) -> &mut ServiceApiScope {
        &mut self.private_scope
    }

    /// Returns an optional reference to the Blockchain.
    pub fn blockchain(&self) -> Option<&Blockchain> {
        self.blockchain.as_ref()
    }

    /// Returns an optional reference to the ApiSender.
    pub fn api_sender(&self) -> Option<&ApiSender> {
        self.blockchain().map(|blockchain| &blockchain.api_sender)
    }

    /// Returns an optional value to the PublicKey.
    pub fn public_key(&self) -> Option<PublicKey> {
        self.blockchain()
            .map(|blockchain| blockchain.service_keypair.0)
    }
}

/// Exonum API access level.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ApiAccess {
    /// Public API for end users.
    Public,
    /// Private API for maintainers.
    Private,
}

impl fmt::Display for ApiAccess {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            ApiAccess::Public => f.write_str("public"),
            ApiAccess::Private => f.write_str("private"),
        }
    }
}

/// API backend extender.
pub trait ExtendApiBackend {
    /// Extends API backend by the given scopes.
    fn extend<'a, I>(self, items: I) -> Self
    where
        I: IntoIterator<Item = (&'a str, &'a ServiceApiScope)>;
}

/// Exonum node API aggregator. Currently only HTTP v1 backend is available.
#[derive(Debug, Clone)]
pub struct ApiAggregator {
    blockchain: Blockchain,
    node_state: SharedNodeState,
    inner: BTreeMap<String, ServiceApiBuilder>,
}

impl ApiAggregator {
    /// Aggregates API for the given blockchain and node state.
    pub fn new(blockchain: Blockchain, node_state: SharedNodeState) -> Self {
        let mut inner = BTreeMap::new();
        // Adds built-in APIs.
        inner.insert(
            "system".to_owned(),
            Self::system_api(&blockchain, node_state.clone()),
        );
        inner.insert("explorer".to_owned(), Self::explorer_api());
        // Adds services APIs.
        inner.extend(blockchain.service_map().iter().map(|(_, service)| {
            let mut builder = ServiceApiBuilder::with_blockchain(blockchain.clone());
            service.wire_api(&mut builder);
            // TODO think about prefixes for non web backends. (ECR-1758)
            let prefix = format!("services/{}", service.service_name());
            (prefix, builder)
        }));

        Self {
            inner,
            blockchain,
            node_state,
        }
    }

    /// Returns a reference to the blockchain used by the aggregator.
    pub fn blockchain(&self) -> &Blockchain {
        &self.blockchain
    }

    /// Extends given API backend by the handlers with the given access level.
    pub fn extend_backend<B: ExtendApiBackend>(&self, access: ApiAccess, backend: B) -> B {
        match access {
            ApiAccess::Public => backend.extend(
                self.inner
                    .iter()
                    .map(|(name, builder)| (name.as_ref(), &builder.public_scope)),
            ),
            ApiAccess::Private => backend.extend(
                self.inner
                    .iter()
                    .map(|(name, builder)| (name.as_ref(), &builder.private_scope)),
            ),
        }
    }

    /// Adds API factory with given prefix to the aggregator.
    pub fn insert<S: Into<String>>(&mut self, prefix: S, builder: ServiceApiBuilder) {
        self.inner.insert(prefix.into(), builder);
    }

    fn explorer_api() -> ServiceApiBuilder {
        let mut builder = ServiceApiBuilder::new();
        self::node::public::ExplorerApi::wire(builder.public_scope());
        builder
    }

    fn system_api(blockchain: &Blockchain, shared_api_state: SharedNodeState) -> ServiceApiBuilder {
        let mut builder = ServiceApiBuilder::new();
        let node_info = self::node::private::NodeInfo::new(
            blockchain.service_map().iter().map(|(_, service)| service),
        );
        self::node::private::SystemApi::new(node_info, shared_api_state.clone())
            .wire(builder.private_scope());
        self::node::public::SystemApi::new(shared_api_state).wire(builder.public_scope());
        builder
    }
}