Coverage Report

Created: 2025-07-01 09:16

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/__w/smoldot/smoldot/repo/light-base/src/json_rpc_service.rs
Line
Count
Source
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
40
mod background;
41
42
use crate::{
43
    log, network_service, platform::PlatformRef, runtime_service, sync_service,
44
    transactions_service,
45
};
46
47
use alloc::{
48
    borrow::Cow,
49
    boxed::Box,
50
    format,
51
    string::{String, ToString as _},
52
    sync::Arc,
53
};
54
use core::{num::NonZero, pin::Pin};
55
use futures_lite::StreamExt as _;
56
57
/// Configuration for [`service()`].
58
pub 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.
125
0
pub fn service<TPlat: PlatformRef>(config: Config<TPlat>) -> Frontend<TPlat> {
126
0
    let log_target = format!("json-rpc-{}", config.log_name);
127
128
0
    let (requests_tx, requests_rx) = async_channel::unbounded(); // TODO: capacity?
129
0
    let (responses_tx, responses_rx) = async_channel::bounded(16); // TODO: capacity?
130
131
0
    let frontend = Frontend {
132
0
        platform: config.platform.clone(),
133
0
        log_target: log_target.clone(),
134
0
        responses_rx: Arc::new(async_lock::Mutex::new(Box::pin(responses_rx))),
135
0
        requests_tx,
136
0
    };
137
138
0
    let platform = config.platform.clone();
139
0
    platform.spawn_task(
140
0
        Cow::Owned(log_target.clone()),
141
0
        background::run(
142
0
            log_target,
143
0
            background::Config {
144
0
                platform: config.platform,
145
0
                network_service: config.network_service,
146
0
                sync_service: config.sync_service,
147
0
                transactions_service: config.transactions_service,
148
0
                runtime_service: config.runtime_service,
149
0
                chain_name: config.chain_name,
150
0
                chain_ty: config.chain_ty,
151
0
                chain_properties_json: config.chain_properties_json,
152
0
                chain_is_live: config.chain_is_live,
153
0
                system_name: config.system_name,
154
0
                system_version: config.system_version,
155
0
                genesis_block_hash: config.genesis_block_hash,
156
0
            },
157
0
            requests_rx,
158
0
            responses_tx,
159
        ),
160
    );
161
162
0
    frontend
163
0
}
Unexecuted instantiation: _RINvNtCsgnEOxJmACC4_13smoldot_light16json_rpc_service7servicepEB4_
Unexecuted instantiation: _RINvNtCs508CmrSPkZh_13smoldot_light16json_rpc_service7serviceNtNtCs7snhGEhbuap_18smoldot_light_wasm8platform11PlatformRefEB11_
Unexecuted instantiation: _RINvNtCs508CmrSPkZh_13smoldot_light16json_rpc_service7servicepEB4_
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)]
172
pub 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
187
impl<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
0
    pub fn queue_rpc_request(&self, json_rpc_request: String) -> Result<(), HandleRpcError> {
194
0
        let log_friendly_request =
195
0
            crate::util::truncated_str(json_rpc_request.chars().filter(|c| !c.is_control()), 250)
Unexecuted instantiation: _RNCNvMNtCsgnEOxJmACC4_13smoldot_light16json_rpc_serviceINtB4_8FrontendpE17queue_rpc_request0B6_
Unexecuted instantiation: _RNCNvMNtCs508CmrSPkZh_13smoldot_light16json_rpc_serviceINtB4_8FrontendNtNtCs7snhGEhbuap_18smoldot_light_wasm8platform11PlatformRefE17queue_rpc_request0B1a_
Unexecuted instantiation: _RNCNvMNtCs508CmrSPkZh_13smoldot_light16json_rpc_serviceINtB4_8FrontendpE17queue_rpc_request0B6_
196
0
                .to_string();
197
198
0
        match self.requests_tx.try_send(json_rpc_request) {
199
            Ok(()) => {
200
0
                log!(
201
0
                    &self.platform,
202
                    Debug,
203
0
                    &self.log_target,
204
                    "json-rpc-request-queued",
205
                    request = log_friendly_request
206
                );
207
0
                Ok(())
208
            }
209
0
            Err(err) => Err(HandleRpcError::TooManyPendingRequests {
210
0
                json_rpc_request: err.into_inner(),
211
0
            }),
212
        }
213
0
    }
Unexecuted instantiation: _RNvMNtCsgnEOxJmACC4_13smoldot_light16json_rpc_serviceINtB2_8FrontendpE17queue_rpc_requestB4_
Unexecuted instantiation: _RNvMNtCs508CmrSPkZh_13smoldot_light16json_rpc_serviceINtB2_8FrontendNtNtCs7snhGEhbuap_18smoldot_light_wasm8platform11PlatformRefE17queue_rpc_requestB18_
Unexecuted instantiation: _RNvMNtCs508CmrSPkZh_13smoldot_light16json_rpc_serviceINtB2_8FrontendpE17queue_rpc_requestB4_
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
0
    pub async fn next_json_rpc_response(&self) -> String {
Unexecuted instantiation: _RNvMNtCsgnEOxJmACC4_13smoldot_light16json_rpc_serviceINtB2_8FrontendpE22next_json_rpc_responseB4_
Unexecuted instantiation: _RNvMNtCs508CmrSPkZh_13smoldot_light16json_rpc_serviceINtB2_8FrontendNtNtCs7snhGEhbuap_18smoldot_light_wasm8platform11PlatformRefE22next_json_rpc_responseB18_
Unexecuted instantiation: _RNvMNtCs508CmrSPkZh_13smoldot_light16json_rpc_serviceINtB2_8FrontendpE22next_json_rpc_responseB4_
220
0
        let message = match self.responses_rx.lock().await.next().await {
221
0
            Some(m) => m,
222
0
            None => unreachable!(),
223
        };
224
225
0
        log!(
226
0
            &self.platform,
227
            Debug,
228
0
            &self.log_target,
229
            "json-rpc-response-yielded",
230
            response =
231
0
                crate::util::truncated_str(message.chars().filter(|c| !c.is_control()), 250,)
Unexecuted instantiation: _RNCNCNvMNtCsgnEOxJmACC4_13smoldot_light16json_rpc_serviceINtB6_8FrontendpE22next_json_rpc_response00B8_
Unexecuted instantiation: _RNCNCNvMNtCs508CmrSPkZh_13smoldot_light16json_rpc_serviceINtB6_8FrontendNtNtCs7snhGEhbuap_18smoldot_light_wasm8platform11PlatformRefE22next_json_rpc_response00B1c_
Unexecuted instantiation: _RNCNCNvMNtCs508CmrSPkZh_13smoldot_light16json_rpc_serviceINtB6_8FrontendpE22next_json_rpc_response00B8_
232
        );
233
234
0
        message
235
0
    }
Unexecuted instantiation: _RNCNvMNtCsgnEOxJmACC4_13smoldot_light16json_rpc_serviceINtB4_8FrontendpE22next_json_rpc_response0B6_
Unexecuted instantiation: _RNCNvMNtCs508CmrSPkZh_13smoldot_light16json_rpc_serviceINtB4_8FrontendNtNtCs7snhGEhbuap_18smoldot_light_wasm8platform11PlatformRefE22next_json_rpc_response0B1a_
Unexecuted instantiation: _RNCNvMNtCs508CmrSPkZh_13smoldot_light16json_rpc_serviceINtB4_8FrontendpE22next_json_rpc_response0B6_
236
}
237
238
/// Error potentially returned when queuing a JSON-RPC request.
239
#[derive(Debug, derive_more::Display, derive_more::Error)]
240
pub 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
}