Skip to main content

zebra_rpc/
server.rs

1//! A JSON-RPC 1.0 & 2.0 endpoint for Zebra.
2//!
3//! This endpoint is compatible with clients that incorrectly send
4//! `"jsonrpc" = 1.0` fields in JSON-RPC 1.0 requests,
5//! such as `lightwalletd`.
6//!
7//! See the full list of
8//! [Differences between JSON-RPC 1.0 and 2.0.](https://www.simple-is-better.org/rpc/#differences-between-1-0-and-2-0)
9
10use std::{collections::HashSet, fmt, panic, sync::Arc};
11
12use cookie::Cookie;
13use jsonrpsee::server::{middleware::rpc::RpcServiceBuilder, Server, ServerHandle};
14use tokio::task::JoinHandle;
15use tracing::*;
16
17use zebra_chain::{
18    block::MAX_BLOCK_BYTES, chain_sync_status::ChainSyncStatus, chain_tip::ChainTip,
19    parameters::Network,
20};
21use zebra_consensus::router::service_trait::BlockVerifierService;
22use zebra_network::AddressBookPeers;
23use zebra_node_services::mempool::MempoolService;
24use zebra_state::{ReadState as ReadStateService, State as StateService};
25
26use crate::{
27    config,
28    methods::{RpcImpl, RpcServer as _},
29    server::{
30        http_request_compatibility::{HttpRequestMiddlewareLayer, RpcAuth},
31        rpc_call_compatibility::FixRpcResponseMiddleware,
32        rpc_metrics::RpcMetricsMiddleware,
33        rpc_tracing::RpcTracingMiddleware,
34    },
35};
36
37pub mod cookie;
38pub mod error;
39pub mod http_request_compatibility;
40pub mod rpc_call_compatibility;
41pub mod rpc_metrics;
42pub mod rpc_tracing;
43
44#[cfg(test)]
45mod tests;
46
47/// Zebra RPC Server
48#[derive(Clone)]
49pub struct RpcServer {
50    /// The RPC config.
51    config: config::rpc::Config,
52
53    /// The configured network.
54    network: Network,
55
56    /// Zebra's application version, with build metadata.
57    build_version: String,
58
59    /// A server handle used to shuts down the RPC server.
60    close_handle: ServerHandle,
61}
62
63impl fmt::Debug for RpcServer {
64    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65        f.debug_struct("RpcServer")
66            .field("config", &self.config)
67            .field("network", &self.network)
68            .field("build_version", &self.build_version)
69            .field(
70                "close_handle",
71                // TODO: when it stabilises, use std::any::type_name_of_val(&self.close_handle)
72                &"ServerHandle",
73            )
74            .finish()
75    }
76}
77
78/// The message to log when logging the RPC server's listen address
79pub const OPENED_RPC_ENDPOINT_MSG: &str = "Opened RPC endpoint at ";
80
81/// The message to log when logging the lightwalletd gRPC server's listen address.
82///
83/// Deliberately distinct from [`OPENED_RPC_ENDPOINT_MSG`], and not a superstring of it:
84/// tests find listen addresses by scraping these messages out of the log, and some read
85/// several in a row and rely on their order.
86pub const OPENED_LIGHTWALLETD_ENDPOINT_MSG: &str = "Opened lightwalletd gRPC endpoint at ";
87
88type ServerTask = JoinHandle<Result<(), tower::BoxError>>;
89
90impl RpcServer {
91    /// Starts the RPC server.
92    ///
93    /// `build_version` and `user_agent` are version strings for the application,
94    /// which are used in RPC responses.
95    ///
96    /// Returns [`JoinHandle`]s for the RPC server and `sendrawtransaction` queue tasks,
97    /// and a [`RpcServer`] handle, which can be used to shut down the RPC server task.
98    ///
99    /// # Panics
100    ///
101    /// - If [`Config::listen_addr`](config::rpc::Config::listen_addr) is `None`.
102    //
103    // TODO:
104    // - replace VersionString with semver::Version, and update the tests to provide valid versions
105    #[allow(clippy::too_many_arguments)]
106    pub async fn start<
107        Mempool,
108        State,
109        ReadState,
110        Tip,
111        BlockVerifierRouter,
112        SyncStatus,
113        AddressBook,
114    >(
115        rpc: RpcImpl<Mempool, State, ReadState, Tip, AddressBook, BlockVerifierRouter, SyncStatus>,
116        conf: config::rpc::Config,
117    ) -> Result<ServerTask, tower::BoxError>
118    where
119        Mempool: MempoolService,
120        State: StateService,
121        ReadState: ReadStateService,
122        Tip: ChainTip + Clone + Send + Sync + 'static,
123        AddressBook: AddressBookPeers + Clone + Send + Sync + 'static,
124        BlockVerifierRouter: BlockVerifierService,
125        SyncStatus: ChainSyncStatus + Clone + Send + Sync + 'static,
126    {
127        let listen_addr = conf
128            .listen_addr
129            .expect("caller should make sure listen_addr is set");
130
131        // The largest RPC request is submitblock, which sends a full block
132        // as a hex string (2x MAX_BLOCK_BYTES) plus a small JSON-RPC wrapper.
133        let max_request_body_size = (MAX_BLOCK_BYTES as usize) * 2 + 1024;
134        // Static credentials take precedence over the cookie, then the cookie
135        // over no authentication at all.
136        let auth = if let Some((user, password)) = conf.static_credentials()? {
137            info!("RPC server requires static user/password authentication");
138            Some(RpcAuth::static_credentials(&user, password.as_str()))
139        } else if conf.enable_cookie_auth {
140            let cookie = Cookie::default();
141            cookie::write_to_disk(&cookie, &conf.cookie_dir)
142                .expect("Zebra must be able to write the auth cookie to the disk");
143            Some(RpcAuth::Cookie(cookie))
144        } else {
145            None
146        };
147        let http_middleware_layer =
148            HttpRequestMiddlewareLayer::with_auth(auth, max_request_body_size);
149
150        let http_middleware = tower::ServiceBuilder::new().layer(http_middleware_layer);
151
152        let rpc = rpc.into_rpc();
153        let registered_methods: Arc<HashSet<_>> = Arc::new(rpc.method_names().collect());
154        let traced_methods = registered_methods.clone();
155
156        let rpc_middleware = RpcServiceBuilder::new()
157            .rpc_logger(1024)
158            .layer_fn(FixRpcResponseMiddleware::new)
159            .layer_fn(move |service| RpcMetricsMiddleware::new(service, registered_methods.clone()))
160            .layer_fn(move |service| RpcTracingMiddleware::new(service, traced_methods.clone()));
161
162        let server = Server::builder()
163            .http_only()
164            .set_http_middleware(http_middleware)
165            .set_rpc_middleware(rpc_middleware)
166            .max_response_body_size(conf.max_response_body_size)
167            .build(listen_addr)
168            .await?;
169
170        info!("{OPENED_RPC_ENDPOINT_MSG}{}", server.local_addr()?);
171
172        Ok(tokio::spawn(async move {
173            server.start(rpc).stopped().await;
174            Ok(())
175        }))
176    }
177
178    /// Shut down this RPC server, blocking the current thread.
179    ///
180    /// This method can be called from within a tokio executor without panicking.
181    /// But it is blocking, so `shutdown()` should be used instead.
182    pub fn shutdown_blocking(&self) {
183        Self::shutdown_blocking_inner(self.close_handle.clone(), self.config.clone())
184    }
185
186    /// Shut down this RPC server asynchronously.
187    /// Returns a task that completes when the server is shut down.
188    pub fn shutdown(&self) -> JoinHandle<()> {
189        let close_handle = self.close_handle.clone();
190        let config = self.config.clone();
191        let span = Span::current();
192
193        tokio::task::spawn_blocking(move || {
194            span.in_scope(|| Self::shutdown_blocking_inner(close_handle, config))
195        })
196    }
197
198    /// Shuts down this RPC server using its `close_handle`.
199    ///
200    /// See `shutdown_blocking()` for details.
201    fn shutdown_blocking_inner(close_handle: ServerHandle, config: config::rpc::Config) {
202        // The server is a blocking task, so it can't run inside a tokio thread.
203        // See the note at wait_on_server.
204        let span = Span::current();
205        let wait_on_shutdown = move || {
206            span.in_scope(|| {
207                // Static credentials never write a cookie, so there is nothing to remove.
208                if config.enable_cookie_auth && !config.uses_static_auth() {
209                    if let Err(err) = cookie::remove_from_disk(&config.cookie_dir) {
210                        warn!(
211                            ?err,
212                            "unexpectedly could not remove the rpc auth cookie from the disk"
213                        )
214                    }
215                }
216
217                info!("Stopping RPC server");
218                let _ = close_handle.stop();
219                debug!("Stopped RPC server");
220            })
221        };
222
223        let span = Span::current();
224        let thread_handle = std::thread::spawn(wait_on_shutdown);
225
226        // Propagate panics from the inner std::thread to the outer tokio blocking task
227        span.in_scope(|| match thread_handle.join() {
228            Ok(()) => (),
229            Err(panic_object) => panic::resume_unwind(panic_object),
230        })
231    }
232}
233
234impl Drop for RpcServer {
235    fn drop(&mut self) {
236        // Block on shutting down, propagating panics.
237        // This can take around 150 seconds.
238        //
239        // Without this shutdown, Zebra's RPC unit tests sometimes crashed with memory errors.
240        self.shutdown_blocking();
241    }
242}