data_anchor_api/
rpc.rs

1use std::collections::HashSet;
2
3use anchor_lang::prelude::Pubkey;
4use chrono::{DateTime, Utc};
5use clap::ValueEnum;
6use data_anchor_blober::GROTH16_PROOF_SIZE;
7use data_anchor_proofs::compound::CompoundInclusionProof;
8use jsonrpsee::{
9    core::{RpcResult, SubscriptionResult},
10    proc_macros::rpc,
11};
12use serde::{Deserialize, Serialize};
13
14/// A data structure representing a blober's information, including the blober's pubkey, the
15/// payer's pubkey, and the network of the blober.
16#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
17pub struct BloberData {
18    #[serde(with = "pubkey_with_str")]
19    pub blober: Pubkey,
20    pub payer: Pubkey,
21    pub network_id: u64,
22}
23
24/// A time range with optional start and end times, used for filtering time.
25#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
26pub struct TimeRange {
27    /// The start time of the range, inclusive.
28    pub start: Option<DateTime<Utc>>,
29    /// The end time of the range, inclusive.
30    pub end: Option<DateTime<Utc>>,
31}
32
33impl TimeRange {
34    /// Returns the start and end times as a tuple of `DateTime<Utc>`, with defaults for
35    /// missing values.
36    pub fn to_db_defaults(&self) -> (DateTime<Utc>, DateTime<Utc>) {
37        #[allow(clippy::unwrap_used, reason = "Hardcoding 0 will never panic")]
38        let default_start = DateTime::<Utc>::from_timestamp_micros(0).unwrap();
39
40        (
41            self.start.unwrap_or(default_start),
42            self.end.unwrap_or(Utc::now()),
43        )
44    }
45}
46
47/// A wrapper around a blober's pubkey, used to identify a blober in RPC calls.
48#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
49pub struct PubkeyFromStr(#[serde(with = "pubkey_with_str")] pub Pubkey);
50
51impl From<PubkeyFromStr> for Pubkey {
52    fn from(value: PubkeyFromStr) -> Self {
53        value.0
54    }
55}
56
57impl From<Pubkey> for PubkeyFromStr {
58    fn from(value: Pubkey) -> Self {
59        PubkeyFromStr(value)
60    }
61}
62
63/// Data structure to hold the proof data
64#[serde_with::serde_as]
65#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
66pub struct ProofData {
67    /// The Groth16 proof bytes
68    #[serde_as(as = "serde_with::Bytes")]
69    pub proof: [u8; GROTH16_PROOF_SIZE],
70    /// The public values from the proof
71    pub public_values: Vec<u8>,
72    /// The verification key bytes in hex encoding with a leading "0x"
73    pub verification_key: String,
74}
75
76/// The Indexer RPC interface.
77#[rpc(server, client)]
78pub trait IndexerRpc {
79    /// Check the health of the RPC server. Returns an error if the server is not healthy.
80    #[method(name = "health")]
81    async fn health(&self) -> RpcResult<()>;
82
83    /// Retrieve a list of blobs for a given slot and blober pubkey. Returns an error if there was a
84    /// database or RPC failure, and None if the slot has not been completed yet. If the slot is
85    /// completed, an empty list will be returned.
86    #[method(name = "get_blobs")]
87    async fn get_blobs(&self, blober: PubkeyFromStr, slot: u64) -> RpcResult<Option<Vec<Vec<u8>>>>;
88
89    /// Retrieve a list of blobs for a given blober pubkey and time range. Returns an error if there
90    /// was a database or RPC failure, and an empty list if no blobs were found.
91    #[method(name = "get_blobs_by_blober")]
92    async fn get_blobs_by_blober(
93        &self,
94        blober: PubkeyFromStr,
95        time_range: Option<TimeRange>,
96    ) -> RpcResult<Vec<Vec<u8>>>;
97
98    /// Retrieve a list of blobs for a given payer pubkey, network ID, and time range. Returns an
99    /// error if there was a database or RPC failure, and an empty list if no blobs were found.
100    #[method(name = "get_blobs_by_payer")]
101    async fn get_blobs_by_payer(
102        &self,
103        payer: PubkeyFromStr,
104        network_name: String,
105        time_range: Option<TimeRange>,
106    ) -> RpcResult<Vec<Vec<u8>>>;
107
108    /// Retrieve a list of blobs for a given network name and time range. Returns an error if there
109    /// was a database or RPC failure, and an empty list if no blobs were found.
110    #[method(name = "get_blobs_by_network")]
111    async fn get_blobs_by_network(
112        &self,
113        network_name: String,
114        time_range: Option<TimeRange>,
115    ) -> RpcResult<Vec<Vec<u8>>>;
116
117    /// Retrieve a list of blobs for a given namespace and time range. Returns an error if there
118    /// was a database or RPC failure, and an empty list if no blobs were found.
119    #[method(name = "get_blobs_by_namespace")]
120    async fn get_blobs_by_namespace_for_payer(
121        &self,
122        namespace: String,
123        payer: Option<PubkeyFromStr>,
124        time_range: Option<TimeRange>,
125    ) -> RpcResult<Vec<Vec<u8>>>;
126
127    /// Retrieve a list of payers for a given network name. Returns an error if there was a
128    /// database or RPC failure, and an empty list if no payers were found.
129    #[method(name = "get_payers_by_network")]
130    async fn get_payers_by_network(&self, network_name: String) -> RpcResult<Vec<PubkeyFromStr>>;
131
132    /// Retrieve a proof for a given slot and blober pubkey. Returns an error if there was a
133    /// database or RPC failure, and None if the slot has not been completed yet.
134    #[method(name = "get_proof")]
135    async fn get_proof(
136        &self,
137        blober: PubkeyFromStr,
138        slot: u64,
139    ) -> RpcResult<Option<CompoundInclusionProof>>;
140
141    /// Retrieve a compound proof that covers a particular blob. Returns an error if there was a
142    /// database or RPC failure, and None if the blob does not exist.
143    #[method(name = "get_proof_for_blob")]
144    async fn get_proof_for_blob(
145        &self,
146        blob_address: PubkeyFromStr,
147    ) -> RpcResult<Option<CompoundInclusionProof>>;
148
149    /// Listen to blob finalization events from specified blobers. This will return a stream of
150    /// slots and blober PDAs that have finalized blobs. The stream will be closed when the RPC server is
151    /// shut down.
152    #[subscription(
153        name = "subscribe_blob_finalization" => "listen_subscribe_blob_finalization",
154        unsubscribe = "unsubscribe_blob_finalization", 
155        item = (Pubkey, u64)
156    )]
157    async fn subscribe_blob_finalization(
158        &self,
159        blobers: HashSet<PubkeyFromStr>,
160    ) -> SubscriptionResult;
161}
162
163#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, ValueEnum)]
164#[serde(rename_all = "kebab-case")]
165pub enum CustomerElf {
166    DataCorrectness,
167    DawnSla,
168}
169
170impl std::fmt::Display for CustomerElf {
171    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
172        match self {
173            CustomerElf::DataCorrectness => write!(f, "data-correctness"),
174            CustomerElf::DawnSla => write!(f, "dawn-sla"),
175        }
176    }
177}
178
179#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
180#[repr(i8)]
181pub enum RequestFailureReason {
182    #[default]
183    Unknown,
184    ProofGenerationFailed,
185    TransactionError,
186    RpcConnection,
187}
188
189impl From<RequestFailureReason> for i16 {
190    fn from(reason: RequestFailureReason) -> Self {
191        match reason {
192            RequestFailureReason::Unknown => -1,
193            RequestFailureReason::ProofGenerationFailed => -2,
194            RequestFailureReason::TransactionError => -3,
195            RequestFailureReason::RpcConnection => -4,
196        }
197    }
198}
199
200impl From<i16> for RequestFailureReason {
201    fn from(reason: i16) -> Self {
202        match reason {
203            -1 => RequestFailureReason::Unknown,
204            -2 => RequestFailureReason::ProofGenerationFailed,
205            -3 => RequestFailureReason::TransactionError,
206            -4 => RequestFailureReason::RpcConnection,
207            #[allow(
208                clippy::panic,
209                reason = "This should never happen as we only use this for reading from the database"
210            )]
211            _ => panic!("Invalid request failure reason: {reason}"),
212        }
213    }
214}
215
216#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
217#[repr(i8)]
218pub enum RequestStatus {
219    #[default]
220    Created,
221    Submitted,
222    Completed,
223    Posted,
224    Failed(RequestFailureReason),
225}
226
227impl From<RequestStatus> for i16 {
228    fn from(status: RequestStatus) -> Self {
229        match status {
230            RequestStatus::Created => 0,
231            RequestStatus::Submitted => 1,
232            RequestStatus::Completed => 2,
233            RequestStatus::Posted => 3,
234            RequestStatus::Failed(reason) => reason.into(),
235        }
236    }
237}
238
239impl From<i16> for RequestStatus {
240    fn from(status: i16) -> Self {
241        match status {
242            0 => RequestStatus::Created,
243            1 => RequestStatus::Submitted,
244            2 => RequestStatus::Completed,
245            3 => RequestStatus::Posted,
246            x if x < 0 => RequestStatus::Failed(x.into()),
247            #[allow(
248                clippy::panic,
249                reason = "This should never happen as we only use this for reading from the database"
250            )]
251            _ => panic!("Invalid request status: {status}"),
252        }
253    }
254}
255
256/// The Proof RPC interface.
257#[rpc(server, client)]
258pub trait ProofRpc {
259    /// Check the health of the RPC server. Returns an error if the server is not healthy.
260    #[method(name = "health")]
261    async fn health(&self) -> RpcResult<()>;
262
263    /// Request building a succinct ZK Groth16 proof for a given blober and slot. (Custom per
264    /// client)
265    #[method(name = "checkpoint_proof")]
266    async fn checkpoint_proof(
267        &self,
268        blober: PubkeyFromStr,
269        slot: u64,
270        customer_elf: CustomerElf,
271    ) -> RpcResult<String>;
272
273    /// Get a proof request status by its ID. Returns an error if the request does not exist or
274    /// if there was a database or RPC failure.
275    #[method(name = "get_proof_request_status")]
276    async fn get_proof_request_status(&self, request_id: String) -> RpcResult<RequestStatus>;
277}
278
279pub mod pubkey_with_str {
280    use std::str::FromStr;
281
282    use anchor_lang::prelude::Pubkey;
283    use serde::{Deserialize, Deserializer, de};
284
285    pub fn deserialize<'de, D>(deserializer: D) -> Result<Pubkey, D::Error>
286    where
287        D: Deserializer<'de>,
288    {
289        String::deserialize(deserializer)
290            .and_then(|key| Pubkey::from_str(&key).map_err(de::Error::custom))
291    }
292
293    pub fn serialize<S>(pubkey: &Pubkey, serializer: S) -> Result<S::Ok, S::Error>
294    where
295        S: serde::Serializer,
296    {
297        serializer.serialize_str(&pubkey.to_string())
298    }
299}