cfx_rpc_builder/
id_provider.rs

1// Copyright 2023-2024 Paradigm.xyz
2// This file is part of reth.
3// Reth is a modular, contributor-friendly and blazing-fast implementation of
4// the Ethereum protocol
5
6// Permission is hereby granted, free of charge, to any
7// person obtaining a copy of this software and associated
8// documentation files (the "Software"), to deal in the
9// Software without restriction, including without
10// limitation the rights to use, copy, modify, merge,
11// publish, distribute, sublicense, and/or sell copies of
12// the Software, and to permit persons to whom the Software
13// is furnished to do so, subject to the following
14// conditions:
15
16// The above copyright notice and this permission notice
17// shall be included in all copies or substantial portions
18// of the Software.
19
20// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
21// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
22// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
23// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
24// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
25// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
27// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
28// DEALINGS IN THE SOFTWARE.
29//! Helper type for `EthPubSubApiServer` implementation.
30//!
31//! Generates IDs for tracking subscriptions.
32
33use std::fmt::Write;
34
35use jsonrpsee_types::SubscriptionId;
36
37/// An [`IdProvider`](jsonrpsee_core::traits::IdProvider) for ethereum
38/// subscription ids.
39///
40/// Returns new hex-string [QUANTITY](https://ethereum.org/en/developers/docs/apis/json-rpc/#quantities-encoding) ids
41#[derive(Debug, Clone, Copy, Default)]
42#[non_exhaustive]
43pub struct EthSubscriptionIdProvider;
44
45impl jsonrpsee_core::traits::IdProvider for EthSubscriptionIdProvider {
46    fn next_id(&self) -> SubscriptionId<'static> {
47        to_quantity(rand::random::<u128>())
48    }
49}
50
51/// Returns a hex quantity string for the given value
52///
53/// Strips all leading zeros, `0` is returned as `0x0`
54#[inline(always)]
55fn to_quantity(val: u128) -> SubscriptionId<'static> {
56    let bytes = val.to_be_bytes();
57    let b = bytes.as_slice();
58    let non_zero = b.iter().take_while(|b| **b == 0).count();
59    let b = &b[non_zero..];
60    if b.is_empty() {
61        return SubscriptionId::Str("0x0".into());
62    }
63
64    let mut id = String::with_capacity(2 * b.len() + 2);
65    id.push_str("0x");
66    let first_byte = b[0];
67    write!(id, "{first_byte:x}").unwrap();
68
69    for byte in &b[1..] {
70        write!(id, "{byte:02x}").unwrap();
71    }
72    id.into()
73}
74
75#[cfg(test)]
76mod tests {
77    use super::*;
78    use alloy_primitives::U128;
79
80    #[test]
81    fn test_id_provider_quantity() {
82        let id = to_quantity(0);
83        assert_eq!(id, SubscriptionId::Str("0x0".into()));
84        let id = to_quantity(1);
85        assert_eq!(id, SubscriptionId::Str("0x1".into()));
86
87        for _ in 0..1000 {
88            let val = rand::random::<u128>();
89            let id = to_quantity(val);
90            match id {
91                SubscriptionId::Str(id) => {
92                    let from_hex: U128 = id.parse().unwrap();
93                    assert_eq!(from_hex, U128::from(val));
94                }
95                SubscriptionId::Num(_) => {
96                    unreachable!()
97                }
98            }
99        }
100    }
101}