sc_mixnet/api.rs
1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
5
6// This program is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10
11// This program is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// You should have received a copy of the GNU General Public License
17// along with this program. If not, see <https://www.gnu.org/licenses/>.
18
19use super::{config::Config, error::Error, request::Request};
20use futures::{
21 channel::{mpsc, oneshot},
22 SinkExt,
23};
24use sp_core::Bytes;
25use std::future::Future;
26
27/// The other end of an [`Api`]. This should be passed to [`run`](super::run::run).
28pub struct ApiBackend {
29 pub(super) request_receiver: mpsc::Receiver<Request>,
30}
31
32/// Interface to the mixnet service.
33#[derive(Clone)]
34pub struct Api {
35 request_sender: mpsc::Sender<Request>,
36}
37
38impl Api {
39 /// Create a new `Api`. The [`ApiBackend`] should be passed to [`run`](super::run::run).
40 pub fn new(config: &Config) -> (Self, ApiBackend) {
41 let (request_sender, request_receiver) = mpsc::channel(config.substrate.request_buffer);
42 (Self { request_sender }, ApiBackend { request_receiver })
43 }
44
45 /// Submit an extrinsic via the mixnet.
46 ///
47 /// Returns a [`Future`] which returns another `Future`.
48 ///
49 /// The first `Future` resolves as soon as there is space in the mixnet service queue. The
50 /// second `Future` resolves once a reply is received over the mixnet (or sooner if there is an
51 /// error).
52 ///
53 /// The first `Future` references `self`, but the second does not. This makes it possible to
54 /// submit concurrent mixnet requests using a single `Api` instance.
55 pub async fn submit_extrinsic(
56 &mut self,
57 extrinsic: Bytes,
58 ) -> impl Future<Output = Result<(), Error>> {
59 let (reply_sender, reply_receiver) = oneshot::channel();
60 let res = self
61 .request_sender
62 .feed(Request::SubmitExtrinsic { extrinsic, reply_sender })
63 .await;
64 async move {
65 res.map_err(|_| Error::ServiceUnavailable)?;
66 reply_receiver.await.map_err(|_| Error::ServiceUnavailable)?
67 }
68 }
69}