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;
41mod statement;
42
43use crate::{
44 bitswap_service, log, network_service, platform::PlatformRef, runtime_service, sync_service,
45 transactions_service,
46};
47
48use alloc::{
49 borrow::Cow,
50 boxed::Box,
51 format,
52 string::{String, ToString as _},
53 sync::Arc,
54};
55use core::{num::NonZero, pin::Pin};
56use futures_lite::StreamExt as _;
57
58pub use statement::StatementProtocolConfig;
59
60/// Configuration for [`service()`].
61pub struct Config<TPlat: PlatformRef> {
62 /// Access to the platform's capabilities.
63 pub platform: TPlat,
64
65 /// Name of the chain, for logging purposes.
66 ///
67 /// > **Note**: This name will be directly printed out. Any special character should already
68 /// > have been filtered out from this name.
69 pub log_name: String,
70
71 /// Maximum number of JSON-RPC requests that can be added to a queue if it is not ready to be
72 /// processed immediately. Any additional request will be immediately rejected.
73 ///
74 /// This parameter is necessary in order to prevent users from using up too much memory within
75 /// the client.
76 // TODO: unused at the moment
77 #[allow(unused)]
78 pub max_pending_requests: NonZero<u32>,
79
80 /// Maximum number of active subscriptions. Any additional subscription will be immediately
81 /// rejected.
82 ///
83 /// This parameter is necessary in order to prevent users from using up too much memory within
84 /// the client.
85 // TODO: unused at the moment
86 #[allow(unused)]
87 pub max_subscriptions: u32,
88
89 /// Access to the network, and identifier of the chain from the point of view of the network
90 /// service.
91 pub network_service: Arc<network_service::NetworkServiceChain<TPlat>>,
92
93 /// Service responsible for synchronizing the chain.
94 pub sync_service: Arc<sync_service::SyncService<TPlat>>,
95
96 /// Service responsible for emitting transactions and tracking their state.
97 pub transactions_service: Arc<transactions_service::TransactionsService<TPlat>>,
98
99 /// Service that provides a ready-to-be-called runtime for the current best block.
100 pub runtime_service: Arc<runtime_service::RuntimeService<TPlat>>,
101
102 /// Service that fulfills IPFS CID requests.
103 pub bitswap_service: Arc<bitswap_service::BitswapService>,
104
105 /// Name of the chain, as found in the chain specification.
106 pub chain_name: String,
107 /// Type of chain, as found in the chain specification.
108 pub chain_ty: String,
109 /// JSON-encoded properties of the chain, as found in the chain specification.
110 pub chain_properties_json: String,
111 /// Whether the chain is a live network. Found in the chain specification.
112 pub chain_is_live: bool,
113
114 /// Value to return when the `system_name` RPC is called. Should be set to the name of the
115 /// final executable.
116 pub system_name: String,
117
118 /// Value to return when the `system_version` RPC is called. Should be set to the version of
119 /// the final executable.
120 pub system_version: String,
121
122 /// Hash of the genesis block of the chain.
123 pub genesis_block_hash: [u8; 32],
124
125 /// Statement protocol configuration. `None` if the statement protocol is disabled.
126 pub statement_protocol_config: Option<StatementProtocolConfig>,
127}
128
129/// Creates a new JSON-RPC service with the given configuration.
130///
131/// Returns a handler that allows sending requests and receiving responses.
132///
133/// Destroying the [`Frontend`] automatically shuts down the service.
134pub fn service<TPlat: PlatformRef>(config: Config<TPlat>) -> Frontend<TPlat> {
135 let log_target = format!("json-rpc-{}", config.log_name);
136
137 let (requests_tx, requests_rx) = async_channel::unbounded(); // TODO: capacity?
138 let (responses_tx, responses_rx) = async_channel::bounded(16); // TODO: capacity?
139
140 let frontend = Frontend {
141 platform: config.platform.clone(),
142 log_target: log_target.clone(),
143 responses_rx: Arc::new(async_lock::Mutex::new(Box::pin(responses_rx))),
144 requests_tx,
145 };
146
147 let platform = config.platform.clone();
148 platform.spawn_task(
149 Cow::Owned(log_target.clone()),
150 background::run(
151 log_target,
152 background::Config {
153 platform: config.platform,
154 network_service: config.network_service,
155 sync_service: config.sync_service,
156 transactions_service: config.transactions_service,
157 runtime_service: config.runtime_service,
158 bitswap_service: config.bitswap_service,
159 chain_name: config.chain_name,
160 chain_ty: config.chain_ty,
161 chain_properties_json: config.chain_properties_json,
162 chain_is_live: config.chain_is_live,
163 system_name: config.system_name,
164 system_version: config.system_version,
165 genesis_block_hash: config.genesis_block_hash,
166 statement_protocol_config: config.statement_protocol_config,
167 },
168 requests_rx,
169 responses_tx,
170 ),
171 );
172
173 frontend
174}
175
176/// Handle that allows sending JSON-RPC requests on the service.
177///
178/// The [`Frontend`] can be cloned, in which case the clone will refer to the same JSON-RPC
179/// service.
180///
181/// Destroying all the [`Frontend`]s automatically shuts down the associated service.
182#[derive(Clone)]
183pub struct Frontend<TPlat> {
184 /// See [`Config::platform`].
185 platform: TPlat,
186
187 /// How to send requests to the background task.
188 requests_tx: async_channel::Sender<String>,
189
190 /// How to receive responses coming from the background task.
191 // TODO: we use an Arc so that it's clonable, but that's questionnable
192 responses_rx: Arc<async_lock::Mutex<Pin<Box<async_channel::Receiver<String>>>>>,
193
194 /// Target to use when emitting logs.
195 log_target: String,
196}
197
198impl<TPlat: PlatformRef> Frontend<TPlat> {
199 /// Queues the given JSON-RPC request to be processed in the background.
200 ///
201 /// An error is returned if [`Config::max_pending_requests`] is exceeded, which can happen
202 /// if the requests take a long time to process or if [`Frontend::next_json_rpc_response`]
203 /// isn't called often enough.
204 pub fn queue_rpc_request(&self, json_rpc_request: String) -> Result<(), HandleRpcError> {
205 let log_friendly_request =
206 crate::util::truncated_str(json_rpc_request.chars().filter(|c| !c.is_control()), 250)
207 .to_string();
208
209 match self.requests_tx.try_send(json_rpc_request) {
210 Ok(()) => {
211 log!(
212 &self.platform,
213 Debug,
214 &self.log_target,
215 "json-rpc-request-queued",
216 request = log_friendly_request
217 );
218 Ok(())
219 }
220 Err(err) => Err(HandleRpcError::TooManyPendingRequests {
221 json_rpc_request: err.into_inner(),
222 }),
223 }
224 }
225
226 /// Waits until a JSON-RPC response has been generated, then returns it.
227 ///
228 /// If this function is called multiple times in parallel, the order in which the calls are
229 /// responded to is unspecified.
230 pub async fn next_json_rpc_response(&self) -> String {
231 let message = match self.responses_rx.lock().await.next().await {
232 Some(m) => m,
233 None => unreachable!(),
234 };
235
236 log!(
237 &self.platform,
238 Debug,
239 &self.log_target,
240 "json-rpc-response-yielded",
241 response =
242 crate::util::truncated_str(message.chars().filter(|c| !c.is_control()), 250,)
243 );
244
245 message
246 }
247}
248
249/// Error potentially returned when queuing a JSON-RPC request.
250#[derive(Debug, derive_more::Display, derive_more::Error)]
251pub enum HandleRpcError {
252 /// The JSON-RPC service cannot process this request, as too many requests are already being
253 /// processed.
254 #[display(
255 "The JSON-RPC service cannot process this request, as too many requests are already being processed."
256 )]
257 TooManyPendingRequests {
258 /// Request that was being queued.
259 json_rpc_request: String,
260 },
261}