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    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    /// Name of the chain, as found in the chain specification.
100    pub chain_name: String,
101    /// Type of chain, as found in the chain specification.
102    pub chain_ty: String,
103    /// JSON-encoded properties of the chain, as found in the chain specification.
104    pub chain_properties_json: String,
105    /// Whether the chain is a live network. Found in the chain specification.
106    pub chain_is_live: bool,
107
108    /// Value to return when the `system_name` RPC is called. Should be set to the name of the
109    /// final executable.
110    pub system_name: String,
111
112    /// Value to return when the `system_version` RPC is called. Should be set to the version of
113    /// the final executable.
114    pub system_version: String,
115
116    /// Hash of the genesis block of the chain.
117    pub genesis_block_hash: [u8; 32],
118}
119
120/// Creates a new JSON-RPC service with the given configuration.
121///
122/// Returns a handler that allows sending requests and receiving responses.
123///
124/// Destroying the [`Frontend`] automatically shuts down the service.
125pub fn service<TPlat: PlatformRef>(config: Config<TPlat>) -> Frontend<TPlat> {
126    let log_target = format!("json-rpc-{}", config.log_name);
127
128    let (requests_tx, requests_rx) = async_channel::unbounded(); // TODO: capacity?
129    let (responses_tx, responses_rx) = async_channel::bounded(16); // TODO: capacity?
130
131    let frontend = Frontend {
132        platform: config.platform.clone(),
133        log_target: log_target.clone(),
134        responses_rx: Arc::new(async_lock::Mutex::new(Box::pin(responses_rx))),
135        requests_tx,
136    };
137
138    let platform = config.platform.clone();
139    platform.spawn_task(
140        Cow::Owned(log_target.clone()),
141        background::run(
142            log_target,
143            background::Config {
144                platform: config.platform,
145                network_service: config.network_service,
146                sync_service: config.sync_service,
147                transactions_service: config.transactions_service,
148                runtime_service: config.runtime_service,
149                chain_name: config.chain_name,
150                chain_ty: config.chain_ty,
151                chain_properties_json: config.chain_properties_json,
152                chain_is_live: config.chain_is_live,
153                system_name: config.system_name,
154                system_version: config.system_version,
155                genesis_block_hash: config.genesis_block_hash,
156            },
157            requests_rx,
158            responses_tx,
159        ),
160    );
161
162    frontend
163}
164
165/// Handle that allows sending JSON-RPC requests on the service.
166///
167/// The [`Frontend`] can be cloned, in which case the clone will refer to the same JSON-RPC
168/// service.
169///
170/// Destroying all the [`Frontend`]s automatically shuts down the associated service.
171#[derive(Clone)]
172pub struct Frontend<TPlat> {
173    /// See [`Config::platform`].
174    platform: TPlat,
175
176    /// How to send requests to the background task.
177    requests_tx: async_channel::Sender<String>,
178
179    /// How to receive responses coming from the background task.
180    // TODO: we use an Arc so that it's clonable, but that's questionnable
181    responses_rx: Arc<async_lock::Mutex<Pin<Box<async_channel::Receiver<String>>>>>,
182
183    /// Target to use when emitting logs.
184    log_target: String,
185}
186
187impl<TPlat: PlatformRef> Frontend<TPlat> {
188    /// Queues the given JSON-RPC request to be processed in the background.
189    ///
190    /// An error is returned if [`Config::max_pending_requests`] is exceeded, which can happen
191    /// if the requests take a long time to process or if [`Frontend::next_json_rpc_response`]
192    /// isn't called often enough.
193    pub fn queue_rpc_request(&self, json_rpc_request: String) -> Result<(), HandleRpcError> {
194        let log_friendly_request =
195            crate::util::truncated_str(json_rpc_request.chars().filter(|c| !c.is_control()), 250)
196                .to_string();
197
198        match self.requests_tx.try_send(json_rpc_request) {
199            Ok(()) => {
200                log!(
201                    &self.platform,
202                    Debug,
203                    &self.log_target,
204                    "json-rpc-request-queued",
205                    request = log_friendly_request
206                );
207                Ok(())
208            }
209            Err(err) => Err(HandleRpcError::TooManyPendingRequests {
210                json_rpc_request: err.into_inner(),
211            }),
212        }
213    }
214
215    /// Waits until a JSON-RPC response has been generated, then returns it.
216    ///
217    /// If this function is called multiple times in parallel, the order in which the calls are
218    /// responded to is unspecified.
219    pub async fn next_json_rpc_response(&self) -> String {
220        let message = match self.responses_rx.lock().await.next().await {
221            Some(m) => m,
222            None => unreachable!(),
223        };
224
225        log!(
226            &self.platform,
227            Debug,
228            &self.log_target,
229            "json-rpc-response-yielded",
230            response =
231                crate::util::truncated_str(message.chars().filter(|c| !c.is_control()), 250,)
232        );
233
234        message
235    }
236}
237
238/// Error potentially returned when queuing a JSON-RPC request.
239#[derive(Debug, derive_more::Display, derive_more::Error)]
240pub enum HandleRpcError {
241    /// The JSON-RPC service cannot process this request, as too many requests are already being
242    /// processed.
243    #[display(
244        "The JSON-RPC service cannot process this request, as too many requests are already being processed."
245    )]
246    TooManyPendingRequests {
247        /// Request that was being queued.
248        json_rpc_request: String,
249    },
250}