Skip to main content

smoldot_light/
json_rpc_service.rs

1// Smoldot
2// Copyright (C) 2019-2022  Parity Technologies (UK) Ltd.
3// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
4
5// This program is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9
10// This program is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13// GNU General Public License for more details.
14
15// You should have received a copy of the GNU General Public License
16// along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18//! Background JSON-RPC service.
19//!
20//! # Usage
21//!
22//! Create a new JSON-RPC service by calling [`service()`].
23//! Creating a JSON-RPC service spawns a background task (through [`PlatformRef::spawn_task`])
24//! dedicated to processing JSON-RPC requests.
25//!
26//! In order to process a JSON-RPC request, call [`Frontend::queue_rpc_request`]. Later, the
27//! JSON-RPC service can queue a response or, in the case of subscriptions, a notification. They
28//! can be retrieved by calling [`Frontend::next_json_rpc_response`].
29//!
30//! In the situation where an attacker finds a JSON-RPC request that takes a long time to be
31//! processed and continuously submits this same expensive request over and over again, the queue
32//! of pending requests will start growing and use more and more memory. For this reason, if this
33//! queue grows past [`Config::max_pending_requests`] items, [`Frontend::queue_rpc_request`]
34//! will instead return an error.
35//!
36
37// TODO: doc
38// TODO: re-review this once finished
39
40mod background;
41
42use crate::{
43    bitswap_service, log, network_service, platform::PlatformRef, runtime_service, sync_service,
44    transactions_service,
45};
46
47use alloc::{
48    borrow::Cow,
49    boxed::Box,
50    format,
51    string::{String, ToString as _},
52    sync::Arc,
53};
54use core::{num::NonZero, pin::Pin};
55use futures_lite::StreamExt as _;
56
57/// Configuration for [`service()`].
58pub struct Config<TPlat: PlatformRef> {
59    /// Access to the platform's capabilities.
60    pub platform: TPlat,
61
62    /// Name of the chain, for logging purposes.
63    ///
64    /// > **Note**: This name will be directly printed out. Any special character should already
65    /// >           have been filtered out from this name.
66    pub log_name: String,
67
68    /// Maximum number of JSON-RPC requests that can be added to a queue if it is not ready to be
69    /// processed immediately. Any additional request will be immediately rejected.
70    ///
71    /// This parameter is necessary in order to prevent users from using up too much memory within
72    /// the client.
73    // TODO: unused at the moment
74    #[allow(unused)]
75    pub max_pending_requests: NonZero<u32>,
76
77    /// Maximum number of active subscriptions. Any additional subscription will be immediately
78    /// rejected.
79    ///
80    /// This parameter is necessary in order to prevent users from using up too much memory within
81    /// the client.
82    // TODO: unused at the moment
83    #[allow(unused)]
84    pub max_subscriptions: u32,
85
86    /// Access to the network, and identifier of the chain from the point of view of the network
87    /// service.
88    pub network_service: Arc<network_service::NetworkServiceChain<TPlat>>,
89
90    /// Service responsible for synchronizing the chain.
91    pub sync_service: Arc<sync_service::SyncService<TPlat>>,
92
93    /// Service responsible for emitting transactions and tracking their state.
94    pub transactions_service: Arc<transactions_service::TransactionsService<TPlat>>,
95
96    /// Service that provides a ready-to-be-called runtime for the current best block.
97    pub runtime_service: Arc<runtime_service::RuntimeService<TPlat>>,
98
99    /// Service that fulfills IPFS CID requests.
100    pub bitswap_service: Arc<bitswap_service::BitswapService>,
101
102    /// Name of the chain, as found in the chain specification.
103    pub chain_name: String,
104    /// Type of chain, as found in the chain specification.
105    pub chain_ty: String,
106    /// JSON-encoded properties of the chain, as found in the chain specification.
107    pub chain_properties_json: String,
108    /// Whether the chain is a live network. Found in the chain specification.
109    pub chain_is_live: bool,
110
111    /// Value to return when the `system_name` RPC is called. Should be set to the name of the
112    /// final executable.
113    pub system_name: String,
114
115    /// Value to return when the `system_version` RPC is called. Should be set to the version of
116    /// the final executable.
117    pub system_version: String,
118
119    /// Hash of the genesis block of the chain.
120    pub genesis_block_hash: [u8; 32],
121
122    /// Statement protocol configuration. `None` if the statement protocol is disabled.
123    pub statement_protocol_config: Option<network_service::StatementProtocolConfig>,
124
125    /// Maximum number of seen statement hashes tracked per subscription for dedup.
126    /// `None` if the statement protocol is disabled.
127    pub max_seen_statements: Option<NonZero<usize>>,
128}
129
130/// Creates a new JSON-RPC service with the given configuration.
131///
132/// Returns a handler that allows sending requests and receiving responses.
133///
134/// Destroying the [`Frontend`] automatically shuts down the service.
135pub fn service<TPlat: PlatformRef>(config: Config<TPlat>) -> Frontend<TPlat> {
136    let log_target = format!("json-rpc-{}", config.log_name);
137
138    let (requests_tx, requests_rx) = async_channel::unbounded(); // TODO: capacity?
139    let (responses_tx, responses_rx) = async_channel::bounded(16); // TODO: capacity?
140
141    let frontend = Frontend {
142        platform: config.platform.clone(),
143        log_target: log_target.clone(),
144        responses_rx: Arc::new(async_lock::Mutex::new(Box::pin(responses_rx))),
145        requests_tx,
146    };
147
148    let platform = config.platform.clone();
149    platform.spawn_task(
150        Cow::Owned(log_target.clone()),
151        background::run(
152            log_target,
153            background::Config {
154                platform: config.platform,
155                network_service: config.network_service,
156                sync_service: config.sync_service,
157                transactions_service: config.transactions_service,
158                runtime_service: config.runtime_service,
159                bitswap_service: config.bitswap_service,
160                chain_name: config.chain_name,
161                chain_ty: config.chain_ty,
162                chain_properties_json: config.chain_properties_json,
163                chain_is_live: config.chain_is_live,
164                system_name: config.system_name,
165                system_version: config.system_version,
166                genesis_block_hash: config.genesis_block_hash,
167                statement_protocol_config: config.statement_protocol_config,
168                max_seen_statements: config.max_seen_statements,
169            },
170            requests_rx,
171            responses_tx,
172        ),
173    );
174
175    frontend
176}
177
178/// Handle that allows sending JSON-RPC requests on the service.
179///
180/// The [`Frontend`] can be cloned, in which case the clone will refer to the same JSON-RPC
181/// service.
182///
183/// Destroying all the [`Frontend`]s automatically shuts down the associated service.
184#[derive(Clone)]
185pub struct Frontend<TPlat> {
186    /// See [`Config::platform`].
187    platform: TPlat,
188
189    /// How to send requests to the background task.
190    requests_tx: async_channel::Sender<String>,
191
192    /// How to receive responses coming from the background task.
193    // TODO: we use an Arc so that it's clonable, but that's questionnable
194    responses_rx: Arc<async_lock::Mutex<Pin<Box<async_channel::Receiver<String>>>>>,
195
196    /// Target to use when emitting logs.
197    log_target: String,
198}
199
200impl<TPlat: PlatformRef> Frontend<TPlat> {
201    /// Queues the given JSON-RPC request to be processed in the background.
202    ///
203    /// An error is returned if [`Config::max_pending_requests`] is exceeded, which can happen
204    /// if the requests take a long time to process or if [`Frontend::next_json_rpc_response`]
205    /// isn't called often enough.
206    pub fn queue_rpc_request(&self, json_rpc_request: String) -> Result<(), HandleRpcError> {
207        let log_friendly_request =
208            crate::util::truncated_str(json_rpc_request.chars().filter(|c| !c.is_control()), 250)
209                .to_string();
210
211        match self.requests_tx.try_send(json_rpc_request) {
212            Ok(()) => {
213                log!(
214                    &self.platform,
215                    Debug,
216                    &self.log_target,
217                    "json-rpc-request-queued",
218                    request = log_friendly_request
219                );
220                Ok(())
221            }
222            Err(err) => Err(HandleRpcError::TooManyPendingRequests {
223                json_rpc_request: err.into_inner(),
224            }),
225        }
226    }
227
228    /// Waits until a JSON-RPC response has been generated, then returns it.
229    ///
230    /// If this function is called multiple times in parallel, the order in which the calls are
231    /// responded to is unspecified.
232    pub async fn next_json_rpc_response(&self) -> String {
233        let message = match self.responses_rx.lock().await.next().await {
234            Some(m) => m,
235            None => unreachable!(),
236        };
237
238        log!(
239            &self.platform,
240            Debug,
241            &self.log_target,
242            "json-rpc-response-yielded",
243            response =
244                crate::util::truncated_str(message.chars().filter(|c| !c.is_control()), 250,)
245        );
246
247        message
248    }
249}
250
251/// Error potentially returned when queuing a JSON-RPC request.
252#[derive(Debug, derive_more::Display, derive_more::Error)]
253pub enum HandleRpcError {
254    /// The JSON-RPC service cannot process this request, as too many requests are already being
255    /// processed.
256    #[display(
257        "The JSON-RPC service cannot process this request, as too many requests are already being processed."
258    )]
259    TooManyPendingRequests {
260        /// Request that was being queued.
261        json_rpc_request: String,
262    },
263}