erpc-sdk 0.11.0

Async multi-network Rust SDK for ERPC
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
use std::{
    collections::{HashMap, HashSet},
    marker::PhantomData,
    sync::{
        Arc,
        atomic::{AtomicU64, Ordering},
    },
    time::Duration,
};

use reqwest::{
    Client,
    header::{AUTHORIZATION, HeaderMap, HeaderValue},
};
use serde::{
    Deserialize, Serialize,
    de::{DeserializeOwned, IgnoredAny},
};
use serde_json::Value;
use tokio_util::sync::CancellationToken;
use url::Url;

use crate::{
    ErpcError, JsonRpcErrorObject, Result,
    config::redaction_secrets_for_headers,
    error::{invalid_response, rpc_error_with_secrets, timeout},
};

/// JSON-RPC request or response identifier.
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[serde(untagged)]
pub enum JsonRpcId {
    /// Numeric identifier used by the built-in transports.
    Number(u64),
    /// String identifier accepted from compatible servers.
    String(String),
}

/// One call in an unsplit JSON-RPC batch.
#[derive(Clone, Debug, Serialize)]
pub struct RpcBatchCall {
    /// Wire-compatible JSON-RPC method name.
    pub method: String,
    /// Positional array or named object parameters.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub params: Option<Value>,
}

impl RpcBatchCall {
    /// Creates a call and serializes its parameters.
    pub fn new(method: impl Into<String>, params: impl Serialize) -> Result<Self> {
        Ok(Self {
            method: method.into(),
            params: Some(serde_json::to_value(params).map_err(|_| {
                ErpcError::Config("RPC parameters could not be serialized".to_owned())
            })?),
        })
    }

    /// Creates a parameterless call.
    #[must_use]
    pub fn without_params(method: impl Into<String>) -> Self {
        Self {
            method: method.into(),
            params: None,
        }
    }
}

/// Per-request cancellation options.
#[derive(Clone, Debug, Default)]
pub struct RequestOptions {
    /// Cancellation token observed while connecting and awaiting a response.
    pub cancellation: Option<CancellationToken>,
}

/// Configuration for the HTTP JSON-RPC transport.
#[derive(Clone)]
pub struct HttpTransportConfig {
    /// ERPC API key.
    pub api_key: String,
    /// HTTP endpoint, without the API key query parameter.
    pub endpoint: Url,
    /// Extra request headers.
    pub headers: HeaderMap,
    /// Maximum accepted caller batch size.
    pub max_batch_size: usize,
    /// Request timeout.
    pub timeout: Duration,
    /// Configured HTTP client.
    pub client: Client,
}

/// Credential-safe HTTP JSON-RPC transport.
pub struct HttpJsonRpcTransport {
    api_key: Option<String>,
    endpoint: Url,
    headers: HeaderMap,
    redaction_secrets: Vec<String>,
    max_batch_size: usize,
    timeout: Duration,
    client: Client,
    next_id: AtomicU64,
    configured: bool,
    namespace: String,
    response_policy: ResponsePolicy,
    api_key_query: bool,
}

#[derive(Clone, Copy)]
enum ResponsePolicy {
    Strict,
    Bitcoin,
}

impl HttpJsonRpcTransport {
    /// Creates a transport. Prefer [`crate::ErpcClient`] for normal use.
    #[must_use]
    pub fn new(config: HttpTransportConfig) -> Self {
        let mut endpoint = config.endpoint;
        let api_key = (!config.api_key.is_empty()).then_some(config.api_key);
        endpoint.set_query(None);
        endpoint.set_fragment(None);
        let mut redaction_secrets = Vec::new();
        if let Some(api_key) = &api_key {
            redaction_secrets.push(api_key.clone());
        }
        Self::from_parts(
            api_key,
            endpoint,
            config.headers,
            redaction_secrets,
            config.max_batch_size,
            config.timeout,
            config.client,
            "RPC",
            true,
            ResponsePolicy::Strict,
            true,
        )
    }

    pub(crate) fn new_direct(
        endpoint: Url,
        headers: HeaderMap,
        redaction_secrets: Vec<String>,
        max_batch_size: usize,
        timeout: Duration,
        client: Client,
        namespace: impl Into<String>,
    ) -> Self {
        let redaction_secrets = merge_secrets(redaction_secrets, &headers);
        Self::from_parts(
            None,
            endpoint,
            headers,
            redaction_secrets,
            max_batch_size,
            timeout,
            client,
            namespace,
            true,
            ResponsePolicy::Strict,
            false,
        )
    }

    pub(crate) fn new_direct_bitcoin(
        endpoint: Url,
        headers: HeaderMap,
        redaction_secrets: Vec<String>,
        timeout: Duration,
        client: Client,
        namespace: impl Into<String>,
    ) -> Self {
        let redaction_secrets = merge_secrets(redaction_secrets, &headers);
        Self::from_parts(
            None,
            endpoint,
            headers,
            redaction_secrets,
            100,
            timeout,
            client,
            namespace,
            true,
            ResponsePolicy::Bitcoin,
            false,
        )
    }

    pub(crate) fn new_bitcoin(
        api_key: String,
        endpoint: Url,
        mut headers: HeaderMap,
        timeout: Duration,
        client: Client,
    ) -> Result<Self> {
        let bearer = format!("Bearer {api_key}");
        let bearer = HeaderValue::from_str(&bearer)
            .map_err(|_| ErpcError::Config("invalid Bitcoin authorization header".to_owned()))?;
        headers.remove(AUTHORIZATION);
        headers.insert(AUTHORIZATION, bearer);
        let mut redaction_secrets = vec![api_key.clone()];
        redaction_secrets = merge_secrets(redaction_secrets, &headers);
        Ok(Self::from_parts(
            Some(api_key),
            endpoint,
            headers,
            redaction_secrets,
            100,
            timeout,
            client,
            "bitcoin.rpc",
            true,
            ResponsePolicy::Bitcoin,
            false,
        ))
    }

    pub(crate) fn unavailable(
        namespace: impl Into<String>,
        timeout: Duration,
        client: Client,
    ) -> Self {
        let endpoint = Url::parse("http://127.0.0.1/").expect("static unavailable endpoint");
        Self::from_parts(
            None,
            endpoint,
            HeaderMap::new(),
            Vec::new(),
            256,
            timeout,
            client,
            namespace,
            false,
            ResponsePolicy::Strict,
            false,
        )
    }

    #[allow(clippy::too_many_arguments)]
    fn from_parts(
        api_key: Option<String>,
        endpoint: Url,
        headers: HeaderMap,
        redaction_secrets: Vec<String>,
        max_batch_size: usize,
        timeout: Duration,
        client: Client,
        namespace: impl Into<String>,
        configured: bool,
        response_policy: ResponsePolicy,
        api_key_query: bool,
    ) -> Self {
        Self {
            api_key,
            endpoint,
            headers,
            redaction_secrets,
            max_batch_size,
            timeout,
            client,
            next_id: AtomicU64::new(1),
            configured,
            namespace: namespace.into(),
            response_policy,
            api_key_query,
        }
    }

    /// Public endpoint without credentials, query, or fragment.
    #[must_use]
    pub fn endpoint(&self) -> String {
        if self.configured {
            let mut endpoint = self.endpoint.clone();
            endpoint.set_query(None);
            endpoint.set_fragment(None);
            endpoint.to_string()
        } else {
            String::new()
        }
    }

    /// Maximum number of calls in one server batch.
    #[must_use]
    pub const fn max_batch_size(&self) -> usize {
        self.max_batch_size
    }

    /// Sends one JSON-RPC request.
    pub async fn request<T: DeserializeOwned>(
        &self,
        method: &str,
        params: Option<Value>,
        options: &RequestOptions,
    ) -> Result<T> {
        self.ensure_configured()?;
        let id = self.id();
        let request = WireRequest {
            jsonrpc: "2.0",
            id: id.clone(),
            method,
            params,
        };
        let response = self.post(&request, options).await?;
        self.unwrap(&response, &id)
    }

    /// Sends one intact JSON-RPC batch and returns results in caller order.
    pub async fn batch(
        &self,
        calls: &[RpcBatchCall],
        options: &RequestOptions,
    ) -> Result<Vec<Value>> {
        self.ensure_configured()?;
        if calls.is_empty() {
            return Ok(Vec::new());
        }
        if calls.len() > self.max_batch_size {
            return Err(invalid_response(format!(
                "A batch may contain at most {} calls",
                self.max_batch_size
            )));
        }
        let requests: Vec<_> = calls
            .iter()
            .map(|call| WireRequest {
                jsonrpc: "2.0",
                id: self.id(),
                method: call.method.as_str(),
                params: call.params.clone(),
            })
            .collect();
        let response = self.post(&requests, options).await?;
        let Value::Array(responses) = response else {
            if let Ok(failure) = serde_json::from_value::<WireFailure>(response) {
                return Err(rpc_error_with_secrets(
                    failure.error,
                    &self.redaction_secrets,
                ));
            }
            return Err(invalid_response("ERPC returned a non-array batch response"));
        };
        let mut by_id = HashMap::new();
        for response in responses {
            let id = response
                .get("id")
                .cloned()
                .ok_or_else(|| invalid_response("ERPC returned an invalid batch item"))?;
            let id = parse_json_rpc_id(&id)
                .map_err(|_| invalid_response("ERPC returned an invalid batch id"))?;
            if by_id.insert(id, response).is_some() {
                return Err(invalid_response("ERPC returned a duplicate batch id"));
            }
        }
        let results = requests
            .iter()
            .map(|request| {
                let response = by_id.remove(&request.id).ok_or_else(|| {
                    invalid_response(format!("ERPC omitted batch response id {}", request.id))
                })?;
                self.unwrap(&response, &request.id)
            })
            .collect::<Result<Vec<_>>>()?;
        if !by_id.is_empty() {
            return Err(invalid_response(
                "ERPC returned an unexpected batch response id",
            ));
        }
        Ok(results)
    }

    fn id(&self) -> JsonRpcId {
        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
        if id == u64::MAX {
            self.next_id.store(1, Ordering::Relaxed);
        }
        JsonRpcId::Number(id)
    }

    async fn post(&self, body: &impl Serialize, options: &RequestOptions) -> Result<Value> {
        let mut url = self.endpoint.clone();
        if self.api_key_query {
            if let Some(api_key) = &self.api_key {
                url.query_pairs_mut().append_pair("api-key", api_key);
            }
        }
        let operation = async {
            let response = self
                .client
                .post(url)
                .headers(self.headers.clone())
                .header(reqwest::header::ACCEPT, "application/json")
                .header(reqwest::header::CONTENT_TYPE, "application/json")
                .json(body)
                .send()
                .await
                .map_err(|_| ErpcError::Transport("Unable to reach ERPC".to_owned()))?;
            if !response.status().is_success() {
                return Err(ErpcError::Http {
                    status: response.status().as_u16(),
                });
            }
            let text = response
                .text()
                .await
                .map_err(|_| ErpcError::Transport("Unable to read ERPC response".to_owned()))?;
            decode_json(&text)
        };
        let timed = tokio::time::timeout(self.timeout, operation);
        let result = if let Some(cancellation) = &options.cancellation {
            tokio::select! {
                biased;
                () = cancellation.cancelled() => return Err(ErpcError::Aborted),
                result = timed => result,
            }
        } else {
            timed.await
        };
        result.map_err(|_| timeout(self.timeout))?
    }

    fn unwrap<T: DeserializeOwned>(&self, response: &Value, expected: &JsonRpcId) -> Result<T> {
        let object = response
            .as_object()
            .ok_or_else(|| invalid_response("ERPC returned an invalid response"))?;
        let id = parse_json_rpc_id(
            object
                .get("id")
                .ok_or_else(|| invalid_response("ERPC returned an invalid response"))?,
        )
        .map_err(|_| invalid_response("ERPC returned an invalid response id"))?;
        if &id != expected {
            return Err(invalid_response("ERPC returned an unexpected response id"));
        }
        if let Some(error) = object.get("error") {
            if !matches!(self.response_policy, ResponsePolicy::Bitcoin) || !error.is_null() {
                let error: JsonRpcErrorObject = serde_json::from_value(error.clone())
                    .map_err(|_| invalid_response("ERPC returned an invalid RPC error"))?;
                return Err(rpc_error_with_secrets(error, &self.redaction_secrets));
            }
        }
        let result = object
            .get("result")
            .cloned()
            .ok_or_else(|| invalid_response("ERPC returned an invalid response"))?;
        serde_json::from_value(result)
            .map_err(|_| invalid_response("ERPC returned an unexpected result shape"))
    }

    pub(crate) fn ensure_configured(&self) -> Result<()> {
        if self.configured {
            Ok(())
        } else {
            Err(ErpcError::NotConfigured(self.namespace.clone()))
        }
    }
}

fn merge_secrets(mut secrets: Vec<String>, headers: &HeaderMap) -> Vec<String> {
    for secret in redaction_secrets_for_headers(headers) {
        if !secrets.contains(&secret) {
            secrets.push(secret);
        }
    }
    secrets
}

const SERDE_PRIVATE_NUMBER_KEY: &str = "$serde_json::private::Number";
const SERDE_PRIVATE_RAW_VALUE_KEY: &str = "$serde_json::private::RawValue";

/// Deserializes a complete JSON document after rejecting serde's private
/// serializer object keys at their original wire boundary.
pub(crate) fn decode_json<T: DeserializeOwned>(text: &str) -> Result<T> {
    serde_json::from_str::<IgnoredAny>(text)
        .map_err(|_| invalid_response("ERPC returned malformed JSON"))?;
    reject_serde_private_keys(text)?;
    serde_json::from_str(text).map_err(|_| invalid_response("ERPC returned malformed JSON"))
}

pub(crate) fn parse_json_rpc_id(value: &Value) -> Result<JsonRpcId> {
    match value {
        Value::Number(number) => number
            .as_u64()
            .map(JsonRpcId::Number)
            .ok_or_else(|| invalid_response("ERPC returned an invalid response id")),
        Value::String(value) => Ok(JsonRpcId::String(value.clone())),
        _ => Err(invalid_response("ERPC returned an invalid response id")),
    }
}

fn reject_serde_private_keys(text: &str) -> Result<()> {
    let bytes = text.as_bytes();
    let mut index = 0;
    while index < bytes.len() {
        if bytes[index] != b'"' {
            index += 1;
            continue;
        }
        let start = index;
        index += 1;
        let mut escaped = false;
        let mut closed = false;
        while index < bytes.len() {
            let byte = bytes[index];
            index += 1;
            if escaped {
                escaped = false;
            } else if byte == b'\\' {
                escaped = true;
            } else if byte == b'"' {
                closed = true;
                break;
            }
        }
        if !closed {
            return Err(invalid_response("ERPC returned malformed JSON"));
        }
        let mut next = index;
        while next < bytes.len() && is_json_whitespace(bytes[next]) {
            next += 1;
        }
        if next >= bytes.len() || bytes[next] != b':' {
            continue;
        }
        let decoded: String = serde_json::from_str(&text[start..index])
            .map_err(|_| invalid_response("ERPC returned malformed JSON"))?;
        if matches!(
            decoded.as_str(),
            SERDE_PRIVATE_NUMBER_KEY | SERDE_PRIVATE_RAW_VALUE_KEY
        ) {
            return Err(invalid_response(
                "ERPC returned unsupported serializer-private object key",
            ));
        }
    }
    Ok(())
}

const fn is_json_whitespace(byte: u8) -> bool {
    matches!(byte, b' ' | b'\n' | b'\r' | b'\t')
}

impl std::fmt::Display for JsonRpcId {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Number(id) => id.fmt(formatter),
            Self::String(id) => id.fmt(formatter),
        }
    }
}

#[derive(Serialize)]
struct WireRequest<'a> {
    jsonrpc: &'static str,
    id: JsonRpcId,
    method: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    params: Option<Value>,
}

#[derive(Deserialize)]
struct WireFailure {
    error: JsonRpcErrorObject,
}

/// An inert typed request. Network I/O begins only when `send` is awaited.
pub struct PendingRpcRequest<T> {
    transport: Arc<HttpJsonRpcTransport>,
    method: String,
    params: Option<Value>,
    marker: PhantomData<fn() -> T>,
}

impl<T: DeserializeOwned> PendingRpcRequest<T> {
    /// Sends with default options.
    pub async fn send(self) -> Result<T> {
        self.send_with(RequestOptions::default()).await
    }

    /// Sends with cancellation options.
    pub async fn send_with(self, options: RequestOptions) -> Result<T> {
        self.transport
            .request(&self.method, self.params, &options)
            .await
    }
}

/// An inert batch request that preserves one caller batch on the wire.
pub struct PendingRpcBatchRequest {
    transport: Arc<HttpJsonRpcTransport>,
    calls: Vec<RpcBatchCall>,
}

impl PendingRpcBatchRequest {
    /// Sends with default options.
    pub async fn send(self) -> Result<Vec<Value>> {
        self.send_with(RequestOptions::default()).await
    }

    /// Sends with cancellation options.
    pub async fn send_with(self, options: RequestOptions) -> Result<Vec<Value>> {
        self.transport.batch(&self.calls, &options).await
    }
}

#[derive(Clone, Copy)]
pub(crate) enum BatchPolicy {
    Any,
    SolanaStandard,
    Unsupported,
}

/// Typed request builder over one JSON-RPC endpoint and parameter mode.
#[derive(Clone)]
pub struct RpcNamespace {
    transport: Arc<HttpJsonRpcTransport>,
    policy: BatchPolicy,
}

impl RpcNamespace {
    pub(crate) const fn new(transport: Arc<HttpJsonRpcTransport>, policy: BatchPolicy) -> Self {
        Self { transport, policy }
    }

    /// Public endpoint without credentials.
    #[must_use]
    pub fn endpoint(&self) -> String {
        self.transport.endpoint()
    }

    /// Creates a typed request using wire-compatible method and parameters.
    pub fn request<T: DeserializeOwned>(
        &self,
        method: impl Into<String>,
        params: impl Serialize,
    ) -> Result<PendingRpcRequest<T>> {
        Ok(PendingRpcRequest {
            transport: Arc::clone(&self.transport),
            method: method.into(),
            params: Some(serde_json::to_value(params).map_err(|_| {
                ErpcError::Config("RPC parameters could not be serialized".to_owned())
            })?),
            marker: PhantomData,
        })
    }

    /// Creates a typed parameterless request.
    #[must_use]
    pub fn request_without_params<T: DeserializeOwned>(
        &self,
        method: impl Into<String>,
    ) -> PendingRpcRequest<T> {
        PendingRpcRequest {
            transport: Arc::clone(&self.transport),
            method: method.into(),
            params: None,
            marker: PhantomData,
        }
    }

    /// Alias for arbitrary methods not yet represented by a convenience method.
    pub fn raw<T: DeserializeOwned>(
        &self,
        method: impl Into<String>,
        params: Option<Value>,
    ) -> PendingRpcRequest<T> {
        PendingRpcRequest {
            transport: Arc::clone(&self.transport),
            method: method.into(),
            params,
            marker: PhantomData,
        }
    }

    /// Validates and creates one unsplit batch request.
    pub fn batch(&self, calls: Vec<RpcBatchCall>) -> Result<PendingRpcBatchRequest> {
        self.transport.ensure_configured()?;
        if matches!(self.policy, BatchPolicy::Unsupported) {
            if !calls.is_empty() {
                return Err(ErpcError::BatchPolicy(
                    "This RPC namespace does not support batching".to_owned(),
                ));
            }
        } else if matches!(self.policy, BatchPolicy::SolanaStandard) {
            validate_solana_standard_batch(&calls)?;
        }
        Ok(PendingRpcBatchRequest {
            transport: Arc::clone(&self.transport),
            calls,
        })
    }
}

fn validate_solana_standard_batch(calls: &[RpcBatchCall]) -> Result<()> {
    let heavy: HashSet<&str> = [
        "getPriorityFeeEstimate",
        "getProgramAccounts",
        "getProgramAccountsV2",
        "getTokenLargestAccounts",
    ]
    .into_iter()
    .collect();
    let contains_heavy = calls
        .iter()
        .any(|call| heavy.contains(call.method.as_str()));
    let contains_standard = calls
        .iter()
        .any(|call| !heavy.contains(call.method.as_str()));
    if contains_heavy && contains_standard {
        return Err(ErpcError::BatchPolicy(
            "Solana indexed and standard RPC methods cannot share a batch".to_owned(),
        ));
    }
    Ok(())
}