rust-eigenda-client 0.1.6

EigenDA Client
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
use std::{str::FromStr, sync::Arc};

use super::{
    blob_info::BlobInfo, config::EigenConfig, eth_client,
    generated::disperser::BlobInfo as DisperserBlobInfo, verifier::Verifier,
};
use crate::{
    blob_info,
    client::BlobProvider,
    errors::{
        BlobStatusError, CommunicationError, ConfigError, EigenClientError, VerificationError,
    },
    generated::disperser::{
        self,
        authenticated_request::Payload::{AuthenticationData, DisperseRequest},
        disperser_client::DisperserClient,
        AuthenticatedReply, BlobAuthHeader,
    },
    rust_eigenda_signers::signers::private_key::Signer as PrivateKeySigner,
};
use byteorder::{BigEndian, ByteOrder};
use rust_eigenda_signers::{Message, Sign};
use tiny_keccak::{Hasher, Keccak};
use tokio::sync::{mpsc, Mutex};
use tokio_stream::{wrappers::UnboundedReceiverStream, StreamExt};
use tonic::{
    transport::{Channel, ClientTlsConfig, Endpoint},
    Streaming,
};

/// Raw Client that comunicates with the disperser
#[derive(Debug)]
pub(crate) struct RawEigenClient<S = PrivateKeySigner> {
    client: Arc<Mutex<DisperserClient<Channel>>>,
    signer: S,
    pub config: EigenConfig,
    verifier: Verifier<eth_client::EthClient>,
    blob_provider: Arc<dyn BlobProvider>,
}

pub(crate) const FIELD_ELEMENT_SIZE_BYTES: usize = 32;

impl<S> RawEigenClient<S> {
    const BLOB_SIZE_LIMIT: usize = 1024 * 1024 * 16; // 16 MB
    /// Creates a new RawEigenClient
    pub(crate) async fn new(
        signer: S,
        config: EigenConfig,
        blob_provider: Arc<dyn BlobProvider>,
    ) -> Result<Self, EigenClientError> {
        let endpoint = Endpoint::from_str(config.disperser_rpc.as_str())
            .map_err(ConfigError::Tonic)?
            .tls_config(ClientTlsConfig::new())
            .map_err(ConfigError::Tonic)?;
        let client = Arc::new(Mutex::new(
            DisperserClient::connect(endpoint)
                .await
                .map_err(ConfigError::Tonic)?,
        ));

        let url = config.eth_rpc_url.clone();
        let eth_client = eth_client::EthClient::new(url, config.eigenda_svc_manager_address);

        let verifier = Verifier::new(config.clone(), eth_client).await?;
        Ok(RawEigenClient {
            client,
            signer,
            config,
            verifier,
            blob_provider,
        })
    }

    /// Returns the blob size limit
    pub(crate) fn blob_size_limit() -> usize {
        Self::BLOB_SIZE_LIMIT
    }

    /// Dispatches a blob to the disperser without authentication
    async fn dispatch_blob_non_authenticated(
        &self,
        data: Vec<u8>,
    ) -> Result<String, EigenClientError> {
        let padded_data = convert_by_padding_empty_byte(&data);

        let custom_quorum_numbers: Vec<u32> = self
            .config
            .custom_quorum_numbers
            .iter()
            .map(|&x| x as u32)
            .collect();
        let request = disperser::DisperseBlobRequest {
            data: padded_data,
            custom_quorum_numbers,
            account_id: String::default(), // Account Id is not used in non-authenticated mode
        };

        let disperse_reply = self
            .client
            .lock()
            .await
            .disperse_blob(request)
            .await
            .map_err(BlobStatusError::Status)?
            .into_inner();

        match disperser::BlobStatus::try_from(disperse_reply.result)
            .map_err(BlobStatusError::Prost)?
        {
            disperser::BlobStatus::Failed
            | disperser::BlobStatus::InsufficientSignatures
            | disperser::BlobStatus::Unknown => Err(BlobStatusError::BlobDispatchedFailed)?,

            disperser::BlobStatus::Dispersing
            | disperser::BlobStatus::Processing
            | disperser::BlobStatus::Finalized
            | disperser::BlobStatus::Confirmed => Ok(hex::encode(disperse_reply.request_id)),
        }
    }

    /// Dispatches a blob to the disperser with authentication
    async fn dispatch_blob_authenticated(&self, data: Vec<u8>) -> Result<String, EigenClientError>
    where
        S: Sign,
    {
        let (tx, rx) = mpsc::unbounded_channel();

        // 1. send DisperseBlobRequest
        let padded_data = convert_by_padding_empty_byte(&data);
        self.disperse_data(padded_data, &tx)?;

        // this await is blocked until the first response on the stream, so we only await after sending the `DisperseBlobRequest`
        let mut response_stream = self
            .client
            .clone()
            .lock()
            .await
            .disperse_blob_authenticated(UnboundedReceiverStream::new(rx))
            .await
            .map_err(BlobStatusError::Status)?;
        let response_stream = response_stream.get_mut();

        // 2. receive BlobAuthHeader
        let blob_auth_header = self.receive_blob_auth_header(response_stream).await?;

        // 3. sign and send BlobAuthHeader
        self.submit_authentication_data(blob_auth_header.clone(), &tx)
            .await?;

        // 4. receive DisperseBlobReply
        let reply = response_stream
            .next()
            .await
            .ok_or(CommunicationError::NoResponseFromServer)?
            .map_err(BlobStatusError::Status)?
            .payload
            .ok_or(CommunicationError::NoPayloadInResponse)?;

        let disperser::authenticated_reply::Payload::DisperseReply(disperse_reply) = reply else {
            return Err(CommunicationError::ErrorFromServer(
                "Unexpected response".to_string(),
            ))?;
        };

        match disperser::BlobStatus::try_from(disperse_reply.result)
            .map_err(BlobStatusError::Prost)?
        {
            disperser::BlobStatus::Failed
            | disperser::BlobStatus::InsufficientSignatures
            | disperser::BlobStatus::Unknown => Err(BlobStatusError::BlobDispatchedFailed)?,

            disperser::BlobStatus::Dispersing
            | disperser::BlobStatus::Processing
            | disperser::BlobStatus::Finalized
            | disperser::BlobStatus::Confirmed => Ok(hex::encode(disperse_reply.request_id)),
        }
    }

    /// Gets the blob info for a given request id
    pub(crate) async fn get_blob_info(
        &self,
        request_id: &str,
    ) -> Result<Option<BlobInfo>, EigenClientError> {
        let blob_info = self.try_get_inclusion_data(request_id.to_string()).await?;

        let Some(blob_info) = blob_info else {
            return Ok(None);
        };
        let blob_info = blob_info::BlobInfo::try_from(blob_info)?;
        let Some(data) = self
            .get_blob(
                blob_info.blob_verification_proof.blob_index,
                blob_info
                    .clone()
                    .blob_verification_proof
                    .batch_medatada
                    .batch_header_hash,
            )
            .await?
        else {
            return Err(CommunicationError::FailedToGetBlob)?;
        };

        let data_db = self
            .blob_provider
            .get_blob(request_id)
            .await
            .map_err(CommunicationError::BlobProvider)?;
        if let Some(data_db) = data_db {
            if data_db != data {
                return Err(VerificationError::DataMismatch)?;
            }
        }
        self.verifier
            .verify_commitment(blob_info.blob_header.commitment.clone(), data)?;

        let result = self
            .verifier
            .verify_inclusion_data_against_settlement_layer(blob_info.clone())
            .await;
        if let Err(e) = result {
            match e {
                // in case of an error, the dispatcher will retry, so the need to return None
                VerificationError::EmptyHash => return Ok(None),
                _ => Err(EigenClientError::Verification(e))?,
            }
        }
        Ok(Some(blob_info))
    }

    /// Returns the inclusion data for a given request id
    pub(crate) async fn get_inclusion_data(
        &self,
        request_id: &str,
    ) -> Result<Option<Vec<u8>>, EigenClientError> {
        let blob_info = self.get_blob_info(request_id).await?;
        if let Some(blob_info) = blob_info {
            Ok(Some(ethabi::encode(&blob_info.to_tokens())))
        } else {
            Ok(None)
        }
    }

    /// Dispatches a blob to the disperser
    pub(crate) async fn dispatch_blob(&self, data: Vec<u8>) -> Result<String, EigenClientError>
    where
        S: Sign,
    {
        if self.config.authenticated {
            self.dispatch_blob_authenticated(data).await
        } else {
            self.dispatch_blob_non_authenticated(data).await
        }
    }

    fn disperse_data(
        &self,
        data: Vec<u8>,
        tx: &mpsc::UnboundedSender<disperser::AuthenticatedRequest>,
    ) -> Result<(), EigenClientError>
    where
        S: Sign,
    {
        let custom_quorum_numbers: Vec<u32> = self
            .config
            .custom_quorum_numbers
            .iter()
            .map(|&x| x as u32)
            .collect();
        let req = disperser::AuthenticatedRequest {
            payload: Some(DisperseRequest(disperser::DisperseBlobRequest {
                data,
                custom_quorum_numbers,
                account_id: self.signer.public_key().account_id(),
            })),
        };

        tx.send(req).map_err(CommunicationError::DisperseBlob)?;
        Ok(())
    }

    fn keccak256(&self, input: &[u8]) -> [u8; 32] {
        let mut hasher = Keccak::v256();
        let mut output = [0u8; 32];
        hasher.update(input);
        hasher.finalize(&mut output);
        output
    }

    async fn submit_authentication_data(
        &self,
        blob_auth_header: BlobAuthHeader,
        tx: &mpsc::UnboundedSender<disperser::AuthenticatedRequest>,
    ) -> Result<(), EigenClientError>
    where
        S: Sign,
    {
        // TODO: replace challenge_parameter with actual auth header when it is available
        let mut buf = [0u8; 4];
        BigEndian::write_u32(&mut buf, blob_auth_header.challenge_parameter);
        let digest = self.keccak256(&buf);

        let msg = Message::new(digest);

        let authentication_data = self
            .signer
            .sign_digest(&msg)
            .await
            .map_err(|e| EigenClientError::Communication(CommunicationError::Signing(Box::new(e))))?
            .to_bytes()
            .to_vec();

        let req = disperser::AuthenticatedRequest {
            payload: Some(AuthenticationData(disperser::AuthenticationData {
                authentication_data,
            })),
        };

        tx.send(req)
            .map_err(CommunicationError::AuthenticationData)?;
        Ok(())
    }

    async fn receive_blob_auth_header(
        &self,
        response_stream: &mut Streaming<AuthenticatedReply>,
    ) -> Result<disperser::BlobAuthHeader, EigenClientError> {
        let reply = response_stream
            .next()
            .await
            .ok_or(CommunicationError::NoResponseFromServer)?;

        let Ok(reply) = reply else {
            return Err(CommunicationError::ErrorFromServer(format!("{:?}", reply)))?;
        };

        let reply = reply
            .payload
            .ok_or(CommunicationError::NoPayloadInResponse)?;

        if let disperser::authenticated_reply::Payload::BlobAuthHeader(blob_auth_header) = reply {
            Ok(blob_auth_header)
        } else {
            Err(CommunicationError::ErrorFromServer(
                "Unexpected Response".to_string(),
            ))?
        }
    }

    pub(crate) async fn try_get_inclusion_data(
        &self,
        request_id: String,
    ) -> Result<Option<DisperserBlobInfo>, EigenClientError> {
        let polling_request = disperser::BlobStatusRequest {
            request_id: hex::decode(request_id).map_err(CommunicationError::Hex)?,
        };

        let resp = self
            .client
            .lock()
            .await
            .get_blob_status(polling_request.clone())
            .await
            .map_err(BlobStatusError::Status)?
            .into_inner();

        match disperser::BlobStatus::try_from(resp.status).map_err(BlobStatusError::Prost)? {
            disperser::BlobStatus::Processing | disperser::BlobStatus::Dispersing => Ok(None),
            disperser::BlobStatus::Failed => Err(BlobStatusError::BlobDispatchedFailed)?,
            disperser::BlobStatus::InsufficientSignatures => {
                Err(BlobStatusError::InsufficientSignatures)?
            }
            disperser::BlobStatus::Confirmed => {
                if !self.config.wait_for_finalization {
                    let blob_info = resp
                        .info
                        .ok_or_else(|| BlobStatusError::NoBlobHeaderInResponse)?;
                    return Ok(Some(blob_info));
                }
                Ok(None)
            }
            disperser::BlobStatus::Finalized => {
                let blob_info = resp
                    .info
                    .ok_or_else(|| BlobStatusError::NoBlobHeaderInResponse)?;
                Ok(Some(blob_info))
            }

            _ => Err(BlobStatusError::ReceivedUnknownBlobStatus)?,
        }
    }

    /// Returns the blob data
    pub(crate) async fn get_blob(
        &self,
        blob_index: u32,
        batch_header_hash: Vec<u8>,
    ) -> Result<Option<Vec<u8>>, EigenClientError> {
        let get_response = self
            .client
            .lock()
            .await
            .retrieve_blob(disperser::RetrieveBlobRequest {
                batch_header_hash,
                blob_index,
            })
            .await
            .map_err(BlobStatusError::Status)?
            .into_inner();

        if get_response.data.is_empty() {
            return Err(CommunicationError::FailedToGetBlob)?;
        }

        let data = remove_empty_byte_from_padded_bytes(&get_response.data);
        Ok(Some(data))
    }
}

fn convert_by_padding_empty_byte(data: &[u8]) -> Vec<u8> {
    let parse_size = FIELD_ELEMENT_SIZE_BYTES - 1;

    let chunk_count = data.len().div_ceil(parse_size);
    let mut valid_data = Vec::with_capacity(data.len() + chunk_count);

    for chunk in data.chunks(parse_size) {
        valid_data.push(0x00); // Add the padding byte (0x00)
        valid_data.extend_from_slice(chunk);
    }
    valid_data
}

fn remove_empty_byte_from_padded_bytes(data: &[u8]) -> Vec<u8> {
    let parse_size = FIELD_ELEMENT_SIZE_BYTES;

    let chunk_count = data.len().div_ceil(parse_size);
    // Safe subtraction, as we know chunk_count is always less than the length of the data
    let mut valid_data = Vec::with_capacity(data.len() - chunk_count);

    for chunk in data.chunks(parse_size) {
        valid_data.extend_from_slice(&chunk[1..]);
    }
    valid_data
}

#[cfg(test)]
mod test {
    #[test]
    fn test_pad_and_unpad() {
        let data = vec![1, 2, 3, 4, 5, 6, 7, 8, 9];
        let padded_data = super::convert_by_padding_empty_byte(&data);
        let unpadded_data = super::remove_empty_byte_from_padded_bytes(&padded_data);
        assert_eq!(data, unpadded_data);
    }

    #[test]
    fn test_pad_and_unpad_large() {
        let data = vec![1; 1000];
        let padded_data = super::convert_by_padding_empty_byte(&data);
        let unpadded_data = super::remove_empty_byte_from_padded_bytes(&padded_data);
        assert_eq!(data, unpadded_data);
    }

    #[test]
    fn test_pad_and_unpad_empty() {
        let data = Vec::new();
        let padded_data = super::convert_by_padding_empty_byte(&data);
        let unpadded_data = super::remove_empty_byte_from_padded_bytes(&padded_data);
        assert_eq!(data, unpadded_data);
    }
}