Skip to main content

erpc_sdk/
rpc.rs

1use std::{
2    collections::{HashMap, HashSet},
3    marker::PhantomData,
4    sync::{
5        Arc,
6        atomic::{AtomicU64, Ordering},
7    },
8    time::Duration,
9};
10
11use reqwest::{
12    Client,
13    header::{AUTHORIZATION, HeaderMap, HeaderValue},
14};
15use serde::{
16    Deserialize, Serialize,
17    de::{DeserializeOwned, IgnoredAny},
18};
19use serde_json::Value;
20use tokio_util::sync::CancellationToken;
21use url::Url;
22
23use crate::{
24    ErpcError, JsonRpcErrorObject, Result,
25    config::redaction_secrets_for_headers,
26    error::{invalid_response, rpc_error_with_secrets, timeout},
27};
28
29/// JSON-RPC request or response identifier.
30#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
31#[serde(untagged)]
32pub enum JsonRpcId {
33    /// Numeric identifier used by the built-in transports.
34    Number(u64),
35    /// String identifier accepted from compatible servers.
36    String(String),
37}
38
39/// One call in an unsplit JSON-RPC batch.
40#[derive(Clone, Debug, Serialize)]
41pub struct RpcBatchCall {
42    /// Wire-compatible JSON-RPC method name.
43    pub method: String,
44    /// Positional array or named object parameters.
45    #[serde(skip_serializing_if = "Option::is_none")]
46    pub params: Option<Value>,
47}
48
49impl RpcBatchCall {
50    /// Creates a call and serializes its parameters.
51    pub fn new(method: impl Into<String>, params: impl Serialize) -> Result<Self> {
52        Ok(Self {
53            method: method.into(),
54            params: Some(serde_json::to_value(params).map_err(|_| {
55                ErpcError::Config("RPC parameters could not be serialized".to_owned())
56            })?),
57        })
58    }
59
60    /// Creates a parameterless call.
61    #[must_use]
62    pub fn without_params(method: impl Into<String>) -> Self {
63        Self {
64            method: method.into(),
65            params: None,
66        }
67    }
68}
69
70/// Per-request cancellation options.
71#[derive(Clone, Debug, Default)]
72pub struct RequestOptions {
73    /// Cancellation token observed while connecting and awaiting a response.
74    pub cancellation: Option<CancellationToken>,
75}
76
77/// Configuration for the HTTP JSON-RPC transport.
78#[derive(Clone)]
79pub struct HttpTransportConfig {
80    /// ERPC API key.
81    pub api_key: String,
82    /// HTTP endpoint, without the API key query parameter.
83    pub endpoint: Url,
84    /// Extra request headers.
85    pub headers: HeaderMap,
86    /// Maximum accepted caller batch size.
87    pub max_batch_size: usize,
88    /// Request timeout.
89    pub timeout: Duration,
90    /// Configured HTTP client.
91    pub client: Client,
92}
93
94/// Credential-safe HTTP JSON-RPC transport.
95pub struct HttpJsonRpcTransport {
96    api_key: Option<String>,
97    endpoint: Url,
98    headers: HeaderMap,
99    redaction_secrets: Vec<String>,
100    max_batch_size: usize,
101    timeout: Duration,
102    client: Client,
103    next_id: AtomicU64,
104    configured: bool,
105    namespace: String,
106    response_policy: ResponsePolicy,
107    api_key_query: bool,
108}
109
110#[derive(Clone, Copy)]
111enum ResponsePolicy {
112    Strict,
113    Bitcoin,
114}
115
116impl HttpJsonRpcTransport {
117    /// Creates a transport. Prefer [`crate::ErpcClient`] for normal use.
118    #[must_use]
119    pub fn new(config: HttpTransportConfig) -> Self {
120        let mut endpoint = config.endpoint;
121        let api_key = (!config.api_key.is_empty()).then_some(config.api_key);
122        endpoint.set_query(None);
123        endpoint.set_fragment(None);
124        let mut redaction_secrets = Vec::new();
125        if let Some(api_key) = &api_key {
126            redaction_secrets.push(api_key.clone());
127        }
128        Self::from_parts(
129            api_key,
130            endpoint,
131            config.headers,
132            redaction_secrets,
133            config.max_batch_size,
134            config.timeout,
135            config.client,
136            "RPC",
137            true,
138            ResponsePolicy::Strict,
139            true,
140        )
141    }
142
143    pub(crate) fn new_direct(
144        endpoint: Url,
145        headers: HeaderMap,
146        redaction_secrets: Vec<String>,
147        max_batch_size: usize,
148        timeout: Duration,
149        client: Client,
150        namespace: impl Into<String>,
151    ) -> Self {
152        let redaction_secrets = merge_secrets(redaction_secrets, &headers);
153        Self::from_parts(
154            None,
155            endpoint,
156            headers,
157            redaction_secrets,
158            max_batch_size,
159            timeout,
160            client,
161            namespace,
162            true,
163            ResponsePolicy::Strict,
164            false,
165        )
166    }
167
168    pub(crate) fn new_direct_bitcoin(
169        endpoint: Url,
170        headers: HeaderMap,
171        redaction_secrets: Vec<String>,
172        timeout: Duration,
173        client: Client,
174        namespace: impl Into<String>,
175    ) -> Self {
176        let redaction_secrets = merge_secrets(redaction_secrets, &headers);
177        Self::from_parts(
178            None,
179            endpoint,
180            headers,
181            redaction_secrets,
182            100,
183            timeout,
184            client,
185            namespace,
186            true,
187            ResponsePolicy::Bitcoin,
188            false,
189        )
190    }
191
192    pub(crate) fn new_bitcoin(
193        api_key: String,
194        endpoint: Url,
195        mut headers: HeaderMap,
196        timeout: Duration,
197        client: Client,
198    ) -> Result<Self> {
199        let bearer = format!("Bearer {api_key}");
200        let bearer = HeaderValue::from_str(&bearer)
201            .map_err(|_| ErpcError::Config("invalid Bitcoin authorization header".to_owned()))?;
202        headers.remove(AUTHORIZATION);
203        headers.insert(AUTHORIZATION, bearer);
204        let mut redaction_secrets = vec![api_key.clone()];
205        redaction_secrets = merge_secrets(redaction_secrets, &headers);
206        Ok(Self::from_parts(
207            Some(api_key),
208            endpoint,
209            headers,
210            redaction_secrets,
211            100,
212            timeout,
213            client,
214            "bitcoin.rpc",
215            true,
216            ResponsePolicy::Bitcoin,
217            false,
218        ))
219    }
220
221    pub(crate) fn unavailable(
222        namespace: impl Into<String>,
223        timeout: Duration,
224        client: Client,
225    ) -> Self {
226        let endpoint = Url::parse("http://127.0.0.1/").expect("static unavailable endpoint");
227        Self::from_parts(
228            None,
229            endpoint,
230            HeaderMap::new(),
231            Vec::new(),
232            256,
233            timeout,
234            client,
235            namespace,
236            false,
237            ResponsePolicy::Strict,
238            false,
239        )
240    }
241
242    #[allow(clippy::too_many_arguments)]
243    fn from_parts(
244        api_key: Option<String>,
245        endpoint: Url,
246        headers: HeaderMap,
247        redaction_secrets: Vec<String>,
248        max_batch_size: usize,
249        timeout: Duration,
250        client: Client,
251        namespace: impl Into<String>,
252        configured: bool,
253        response_policy: ResponsePolicy,
254        api_key_query: bool,
255    ) -> Self {
256        Self {
257            api_key,
258            endpoint,
259            headers,
260            redaction_secrets,
261            max_batch_size,
262            timeout,
263            client,
264            next_id: AtomicU64::new(1),
265            configured,
266            namespace: namespace.into(),
267            response_policy,
268            api_key_query,
269        }
270    }
271
272    /// Public endpoint without credentials, query, or fragment.
273    #[must_use]
274    pub fn endpoint(&self) -> String {
275        if self.configured {
276            let mut endpoint = self.endpoint.clone();
277            endpoint.set_query(None);
278            endpoint.set_fragment(None);
279            endpoint.to_string()
280        } else {
281            String::new()
282        }
283    }
284
285    /// Maximum number of calls in one server batch.
286    #[must_use]
287    pub const fn max_batch_size(&self) -> usize {
288        self.max_batch_size
289    }
290
291    /// Sends one JSON-RPC request.
292    pub async fn request<T: DeserializeOwned>(
293        &self,
294        method: &str,
295        params: Option<Value>,
296        options: &RequestOptions,
297    ) -> Result<T> {
298        self.ensure_configured()?;
299        let id = self.id();
300        let request = WireRequest {
301            jsonrpc: "2.0",
302            id: id.clone(),
303            method,
304            params,
305        };
306        let response = self.post(&request, options).await?;
307        self.unwrap(&response, &id)
308    }
309
310    /// Sends one intact JSON-RPC batch and returns results in caller order.
311    pub async fn batch(
312        &self,
313        calls: &[RpcBatchCall],
314        options: &RequestOptions,
315    ) -> Result<Vec<Value>> {
316        self.ensure_configured()?;
317        if calls.is_empty() {
318            return Ok(Vec::new());
319        }
320        if calls.len() > self.max_batch_size {
321            return Err(invalid_response(format!(
322                "A batch may contain at most {} calls",
323                self.max_batch_size
324            )));
325        }
326        let requests: Vec<_> = calls
327            .iter()
328            .map(|call| WireRequest {
329                jsonrpc: "2.0",
330                id: self.id(),
331                method: call.method.as_str(),
332                params: call.params.clone(),
333            })
334            .collect();
335        let response = self.post(&requests, options).await?;
336        let Value::Array(responses) = response else {
337            if let Ok(failure) = serde_json::from_value::<WireFailure>(response) {
338                return Err(rpc_error_with_secrets(
339                    failure.error,
340                    &self.redaction_secrets,
341                ));
342            }
343            return Err(invalid_response("ERPC returned a non-array batch response"));
344        };
345        let mut by_id = HashMap::new();
346        for response in responses {
347            let id = response
348                .get("id")
349                .cloned()
350                .ok_or_else(|| invalid_response("ERPC returned an invalid batch item"))?;
351            let id = parse_json_rpc_id(&id)
352                .map_err(|_| invalid_response("ERPC returned an invalid batch id"))?;
353            if by_id.insert(id, response).is_some() {
354                return Err(invalid_response("ERPC returned a duplicate batch id"));
355            }
356        }
357        let results = requests
358            .iter()
359            .map(|request| {
360                let response = by_id.remove(&request.id).ok_or_else(|| {
361                    invalid_response(format!("ERPC omitted batch response id {}", request.id))
362                })?;
363                self.unwrap(&response, &request.id)
364            })
365            .collect::<Result<Vec<_>>>()?;
366        if !by_id.is_empty() {
367            return Err(invalid_response(
368                "ERPC returned an unexpected batch response id",
369            ));
370        }
371        Ok(results)
372    }
373
374    fn id(&self) -> JsonRpcId {
375        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
376        if id == u64::MAX {
377            self.next_id.store(1, Ordering::Relaxed);
378        }
379        JsonRpcId::Number(id)
380    }
381
382    async fn post(&self, body: &impl Serialize, options: &RequestOptions) -> Result<Value> {
383        let mut url = self.endpoint.clone();
384        if self.api_key_query {
385            if let Some(api_key) = &self.api_key {
386                url.query_pairs_mut().append_pair("api-key", api_key);
387            }
388        }
389        let operation = async {
390            let response = self
391                .client
392                .post(url)
393                .headers(self.headers.clone())
394                .header(reqwest::header::ACCEPT, "application/json")
395                .header(reqwest::header::CONTENT_TYPE, "application/json")
396                .json(body)
397                .send()
398                .await
399                .map_err(|_| ErpcError::Transport("Unable to reach ERPC".to_owned()))?;
400            if !response.status().is_success() {
401                return Err(ErpcError::Http {
402                    status: response.status().as_u16(),
403                });
404            }
405            let text = response
406                .text()
407                .await
408                .map_err(|_| ErpcError::Transport("Unable to read ERPC response".to_owned()))?;
409            decode_json(&text)
410        };
411        let timed = tokio::time::timeout(self.timeout, operation);
412        let result = if let Some(cancellation) = &options.cancellation {
413            tokio::select! {
414                biased;
415                () = cancellation.cancelled() => return Err(ErpcError::Aborted),
416                result = timed => result,
417            }
418        } else {
419            timed.await
420        };
421        result.map_err(|_| timeout(self.timeout))?
422    }
423
424    fn unwrap<T: DeserializeOwned>(&self, response: &Value, expected: &JsonRpcId) -> Result<T> {
425        let object = response
426            .as_object()
427            .ok_or_else(|| invalid_response("ERPC returned an invalid response"))?;
428        let id = parse_json_rpc_id(
429            object
430                .get("id")
431                .ok_or_else(|| invalid_response("ERPC returned an invalid response"))?,
432        )
433        .map_err(|_| invalid_response("ERPC returned an invalid response id"))?;
434        if &id != expected {
435            return Err(invalid_response("ERPC returned an unexpected response id"));
436        }
437        if let Some(error) = object.get("error") {
438            if !matches!(self.response_policy, ResponsePolicy::Bitcoin) || !error.is_null() {
439                let error: JsonRpcErrorObject = serde_json::from_value(error.clone())
440                    .map_err(|_| invalid_response("ERPC returned an invalid RPC error"))?;
441                return Err(rpc_error_with_secrets(error, &self.redaction_secrets));
442            }
443        }
444        let result = object
445            .get("result")
446            .cloned()
447            .ok_or_else(|| invalid_response("ERPC returned an invalid response"))?;
448        serde_json::from_value(result)
449            .map_err(|_| invalid_response("ERPC returned an unexpected result shape"))
450    }
451
452    pub(crate) fn ensure_configured(&self) -> Result<()> {
453        if self.configured {
454            Ok(())
455        } else {
456            Err(ErpcError::NotConfigured(self.namespace.clone()))
457        }
458    }
459}
460
461fn merge_secrets(mut secrets: Vec<String>, headers: &HeaderMap) -> Vec<String> {
462    for secret in redaction_secrets_for_headers(headers) {
463        if !secrets.contains(&secret) {
464            secrets.push(secret);
465        }
466    }
467    secrets
468}
469
470const SERDE_PRIVATE_NUMBER_KEY: &str = "$serde_json::private::Number";
471const SERDE_PRIVATE_RAW_VALUE_KEY: &str = "$serde_json::private::RawValue";
472
473/// Deserializes a complete JSON document after rejecting serde's private
474/// serializer object keys at their original wire boundary.
475pub(crate) fn decode_json<T: DeserializeOwned>(text: &str) -> Result<T> {
476    serde_json::from_str::<IgnoredAny>(text)
477        .map_err(|_| invalid_response("ERPC returned malformed JSON"))?;
478    reject_serde_private_keys(text)?;
479    serde_json::from_str(text).map_err(|_| invalid_response("ERPC returned malformed JSON"))
480}
481
482pub(crate) fn parse_json_rpc_id(value: &Value) -> Result<JsonRpcId> {
483    match value {
484        Value::Number(number) => number
485            .as_u64()
486            .map(JsonRpcId::Number)
487            .ok_or_else(|| invalid_response("ERPC returned an invalid response id")),
488        Value::String(value) => Ok(JsonRpcId::String(value.clone())),
489        _ => Err(invalid_response("ERPC returned an invalid response id")),
490    }
491}
492
493fn reject_serde_private_keys(text: &str) -> Result<()> {
494    let bytes = text.as_bytes();
495    let mut index = 0;
496    while index < bytes.len() {
497        if bytes[index] != b'"' {
498            index += 1;
499            continue;
500        }
501        let start = index;
502        index += 1;
503        let mut escaped = false;
504        let mut closed = false;
505        while index < bytes.len() {
506            let byte = bytes[index];
507            index += 1;
508            if escaped {
509                escaped = false;
510            } else if byte == b'\\' {
511                escaped = true;
512            } else if byte == b'"' {
513                closed = true;
514                break;
515            }
516        }
517        if !closed {
518            return Err(invalid_response("ERPC returned malformed JSON"));
519        }
520        let mut next = index;
521        while next < bytes.len() && is_json_whitespace(bytes[next]) {
522            next += 1;
523        }
524        if next >= bytes.len() || bytes[next] != b':' {
525            continue;
526        }
527        let decoded: String = serde_json::from_str(&text[start..index])
528            .map_err(|_| invalid_response("ERPC returned malformed JSON"))?;
529        if matches!(
530            decoded.as_str(),
531            SERDE_PRIVATE_NUMBER_KEY | SERDE_PRIVATE_RAW_VALUE_KEY
532        ) {
533            return Err(invalid_response(
534                "ERPC returned unsupported serializer-private object key",
535            ));
536        }
537    }
538    Ok(())
539}
540
541const fn is_json_whitespace(byte: u8) -> bool {
542    matches!(byte, b' ' | b'\n' | b'\r' | b'\t')
543}
544
545impl std::fmt::Display for JsonRpcId {
546    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
547        match self {
548            Self::Number(id) => id.fmt(formatter),
549            Self::String(id) => id.fmt(formatter),
550        }
551    }
552}
553
554#[derive(Serialize)]
555struct WireRequest<'a> {
556    jsonrpc: &'static str,
557    id: JsonRpcId,
558    method: &'a str,
559    #[serde(skip_serializing_if = "Option::is_none")]
560    params: Option<Value>,
561}
562
563#[derive(Deserialize)]
564struct WireFailure {
565    error: JsonRpcErrorObject,
566}
567
568/// An inert typed request. Network I/O begins only when `send` is awaited.
569pub struct PendingRpcRequest<T> {
570    transport: Arc<HttpJsonRpcTransport>,
571    method: String,
572    params: Option<Value>,
573    marker: PhantomData<fn() -> T>,
574}
575
576impl<T: DeserializeOwned> PendingRpcRequest<T> {
577    /// Sends with default options.
578    pub async fn send(self) -> Result<T> {
579        self.send_with(RequestOptions::default()).await
580    }
581
582    /// Sends with cancellation options.
583    pub async fn send_with(self, options: RequestOptions) -> Result<T> {
584        self.transport
585            .request(&self.method, self.params, &options)
586            .await
587    }
588}
589
590/// An inert batch request that preserves one caller batch on the wire.
591pub struct PendingRpcBatchRequest {
592    transport: Arc<HttpJsonRpcTransport>,
593    calls: Vec<RpcBatchCall>,
594}
595
596impl PendingRpcBatchRequest {
597    /// Sends with default options.
598    pub async fn send(self) -> Result<Vec<Value>> {
599        self.send_with(RequestOptions::default()).await
600    }
601
602    /// Sends with cancellation options.
603    pub async fn send_with(self, options: RequestOptions) -> Result<Vec<Value>> {
604        self.transport.batch(&self.calls, &options).await
605    }
606}
607
608#[derive(Clone, Copy)]
609pub(crate) enum BatchPolicy {
610    Any,
611    SolanaStandard,
612    Unsupported,
613}
614
615/// Typed request builder over one JSON-RPC endpoint and parameter mode.
616#[derive(Clone)]
617pub struct RpcNamespace {
618    transport: Arc<HttpJsonRpcTransport>,
619    policy: BatchPolicy,
620}
621
622impl RpcNamespace {
623    pub(crate) const fn new(transport: Arc<HttpJsonRpcTransport>, policy: BatchPolicy) -> Self {
624        Self { transport, policy }
625    }
626
627    /// Public endpoint without credentials.
628    #[must_use]
629    pub fn endpoint(&self) -> String {
630        self.transport.endpoint()
631    }
632
633    /// Creates a typed request using wire-compatible method and parameters.
634    pub fn request<T: DeserializeOwned>(
635        &self,
636        method: impl Into<String>,
637        params: impl Serialize,
638    ) -> Result<PendingRpcRequest<T>> {
639        Ok(PendingRpcRequest {
640            transport: Arc::clone(&self.transport),
641            method: method.into(),
642            params: Some(serde_json::to_value(params).map_err(|_| {
643                ErpcError::Config("RPC parameters could not be serialized".to_owned())
644            })?),
645            marker: PhantomData,
646        })
647    }
648
649    /// Creates a typed parameterless request.
650    #[must_use]
651    pub fn request_without_params<T: DeserializeOwned>(
652        &self,
653        method: impl Into<String>,
654    ) -> PendingRpcRequest<T> {
655        PendingRpcRequest {
656            transport: Arc::clone(&self.transport),
657            method: method.into(),
658            params: None,
659            marker: PhantomData,
660        }
661    }
662
663    /// Alias for arbitrary methods not yet represented by a convenience method.
664    pub fn raw<T: DeserializeOwned>(
665        &self,
666        method: impl Into<String>,
667        params: Option<Value>,
668    ) -> PendingRpcRequest<T> {
669        PendingRpcRequest {
670            transport: Arc::clone(&self.transport),
671            method: method.into(),
672            params,
673            marker: PhantomData,
674        }
675    }
676
677    /// Validates and creates one unsplit batch request.
678    pub fn batch(&self, calls: Vec<RpcBatchCall>) -> Result<PendingRpcBatchRequest> {
679        self.transport.ensure_configured()?;
680        if matches!(self.policy, BatchPolicy::Unsupported) {
681            if !calls.is_empty() {
682                return Err(ErpcError::BatchPolicy(
683                    "This RPC namespace does not support batching".to_owned(),
684                ));
685            }
686        } else if matches!(self.policy, BatchPolicy::SolanaStandard) {
687            validate_solana_standard_batch(&calls)?;
688        }
689        Ok(PendingRpcBatchRequest {
690            transport: Arc::clone(&self.transport),
691            calls,
692        })
693    }
694}
695
696fn validate_solana_standard_batch(calls: &[RpcBatchCall]) -> Result<()> {
697    let heavy: HashSet<&str> = [
698        "getPriorityFeeEstimate",
699        "getProgramAccounts",
700        "getProgramAccountsV2",
701        "getTokenLargestAccounts",
702    ]
703    .into_iter()
704    .collect();
705    let contains_heavy = calls
706        .iter()
707        .any(|call| heavy.contains(call.method.as_str()));
708    let contains_standard = calls
709        .iter()
710        .any(|call| !heavy.contains(call.method.as_str()));
711    if contains_heavy && contains_standard {
712        return Err(ErpcError::BatchPolicy(
713            "Solana indexed and standard RPC methods cannot share a batch".to_owned(),
714        ));
715    }
716    Ok(())
717}