Skip to content

Commit 5151da8

Browse files
gabrielbosioMarcosNicolauavilagaston9
authored
feat: various sdk improvements (#1313)
Co-authored-by: Marcos Nicolau <[email protected]> Co-authored-by: Avila Gastón <[email protected]> Co-authored-by: avilagaston9 <[email protected]>
1 parent 24b24e6 commit 5151da8

File tree

14 files changed

+444
-203
lines changed

14 files changed

+444
-203
lines changed

batcher/aligned-batcher/src/connection.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use std::sync::Arc;
33
use crate::types::{batch_queue::BatchQueueEntry, errors::BatcherError};
44
use aligned_sdk::{
55
communication::serialization::cbor_serialize,
6-
core::types::{BatchInclusionData, ResponseMessage, VerificationCommitmentBatch},
6+
core::types::{BatchInclusionData, SubmitProofResponseMessage, VerificationCommitmentBatch},
77
};
88
use futures_util::{stream::SplitSink, SinkExt};
99
use lambdaworks_crypto::merkle_tree::merkle::MerkleTree;
@@ -27,7 +27,7 @@ pub(crate) async fn send_batch_inclusion_data_responses(
2727
batch_merkle_tree,
2828
entry.nonced_verification_data.nonce,
2929
);
30-
let response = ResponseMessage::BatchInclusionData(batch_inclusion_data);
30+
let response = SubmitProofResponseMessage::BatchInclusionData(batch_inclusion_data);
3131

3232
let serialized_response = cbor_serialize(&response)
3333
.map_err(|e| BatcherError::SerializationError(e.to_string()))?;

batcher/aligned-batcher/src/lib.rs

Lines changed: 156 additions & 31 deletions
Large diffs are not rendered by default.

batcher/aligned-sdk/src/communication/messaging.rs

Lines changed: 29 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,14 @@ use futures_util::stream::{SplitSink, TryFilter};
1111
use tokio_tungstenite::{tungstenite::Message, MaybeTlsStream, WebSocketStream};
1212

1313
use crate::communication::serialization::{cbor_deserialize, cbor_serialize};
14-
use crate::core::types::BatchInclusionData;
14+
use crate::core::types::{BatchInclusionData, SubmitProofMessage};
1515
use crate::{
1616
communication::batch::process_batcher_response,
1717
core::{
1818
errors::SubmitError,
1919
types::{
20-
AlignedVerificationData, ClientMessage, NoncedVerificationData, ResponseMessage,
21-
VerificationData, VerificationDataCommitment,
20+
AlignedVerificationData, ClientMessage, NoncedVerificationData,
21+
SubmitProofResponseMessage, VerificationData, VerificationDataCommitment,
2222
},
2323
},
2424
};
@@ -36,26 +36,28 @@ pub async fn send_messages(
3636
ws_write: Arc<Mutex<SplitSink<WebSocketStream<MaybeTlsStream<TcpStream>>, Message>>>,
3737
payment_service_addr: Address,
3838
verification_data: &[VerificationData],
39-
max_fees: &[U256],
39+
max_fee: U256,
4040
wallet: Wallet<SigningKey>,
4141
mut nonce: U256,
4242
) -> Vec<Result<NoncedVerificationData, SubmitError>> {
4343
let chain_id = U256::from(wallet.chain_id());
4444
let mut ws_write = ws_write.lock().await;
4545
let mut sent_verification_data: Vec<Result<NoncedVerificationData, SubmitError>> = Vec::new();
4646

47-
for (idx, verification_data) in verification_data.iter().enumerate() {
47+
for (idx, verification_data_i) in verification_data.iter().enumerate() {
4848
// Build each message to send
4949
let verification_data = NoncedVerificationData::new(
50-
verification_data.clone(),
50+
verification_data_i.clone(),
5151
nonce,
52-
max_fees[idx],
52+
max_fee,
5353
chain_id,
5454
payment_service_addr,
5555
);
5656

5757
nonce += U256::one();
58-
let msg = ClientMessage::new(verification_data.clone(), wallet.clone()).await;
58+
let data = SubmitProofMessage::new(verification_data.clone(), wallet.clone()).await;
59+
let msg = ClientMessage::SubmitProof(Box::new(data));
60+
5961
let msg_bin = match cbor_serialize(&msg) {
6062
Ok(bin) => bin,
6163
Err(e) => {
@@ -168,49 +170,52 @@ pub async fn receive(
168170
async fn handle_batcher_response(msg: Message) -> Result<BatchInclusionData, SubmitError> {
169171
let data = msg.into_data();
170172
match cbor_deserialize(data.as_slice()) {
171-
Ok(ResponseMessage::BatchInclusionData(batch_inclusion_data)) => {
173+
Ok(SubmitProofResponseMessage::BatchInclusionData(batch_inclusion_data)) => {
172174
//OK case. Proofs was valid and it was included in this batch.
173175
Ok(batch_inclusion_data)
174176
}
175-
Ok(ResponseMessage::InvalidNonce) => {
177+
Ok(SubmitProofResponseMessage::InvalidNonce) => {
176178
error!("Batcher responded with invalid nonce");
177179
Err(SubmitError::InvalidNonce)
178180
}
179-
Ok(ResponseMessage::InvalidSignature) => {
181+
Ok(SubmitProofResponseMessage::InvalidSignature) => {
180182
error!("Batcher responded with invalid signature");
181183
Err(SubmitError::InvalidSignature)
182184
}
183-
Ok(ResponseMessage::ProofTooLarge) => {
185+
Ok(SubmitProofResponseMessage::ProofTooLarge) => {
184186
error!("Batcher responded with proof too large");
185187
Err(SubmitError::ProofTooLarge)
186188
}
187-
Ok(ResponseMessage::InvalidMaxFee) => {
189+
Ok(SubmitProofResponseMessage::InvalidMaxFee) => {
188190
error!("Batcher responded with invalid max fee");
189191
Err(SubmitError::InvalidMaxFee)
190192
}
191-
Ok(ResponseMessage::InsufficientBalance(addr)) => {
193+
Ok(SubmitProofResponseMessage::InsufficientBalance(addr)) => {
192194
error!("Batcher responded with insufficient balance");
193195
Err(SubmitError::InsufficientBalance(addr))
194196
}
195-
Ok(ResponseMessage::InvalidChainId) => {
197+
Ok(SubmitProofResponseMessage::InvalidChainId) => {
196198
error!("Batcher responded with invalid chain id");
197199
Err(SubmitError::InvalidChainId)
198200
}
199-
Ok(ResponseMessage::InvalidReplacementMessage) => {
201+
Ok(SubmitProofResponseMessage::InvalidReplacementMessage) => {
200202
error!("Batcher responded with invalid replacement message");
201203
Err(SubmitError::InvalidReplacementMessage)
202204
}
203-
Ok(ResponseMessage::AddToBatchError) => {
205+
Ok(SubmitProofResponseMessage::AddToBatchError) => {
204206
error!("Batcher responded with add to batch error");
205207
Err(SubmitError::AddToBatchError)
206208
}
207-
Ok(ResponseMessage::EthRpcError) => {
209+
Ok(SubmitProofResponseMessage::EthRpcError) => {
208210
error!("Batcher experienced Eth RPC connection error");
209211
Err(SubmitError::EthereumProviderError(
210212
"Batcher experienced Eth RPC connection error".to_string(),
211213
))
212214
}
213-
Ok(ResponseMessage::InvalidPaymentServiceAddress(received_addr, expected_addr)) => {
215+
Ok(SubmitProofResponseMessage::InvalidPaymentServiceAddress(
216+
received_addr,
217+
expected_addr,
218+
)) => {
214219
error!(
215220
"Batcher responded with invalid payment service address: {:?}, expected: {:?}",
216221
received_addr, expected_addr
@@ -220,11 +225,11 @@ async fn handle_batcher_response(msg: Message) -> Result<BatchInclusionData, Sub
220225
expected_addr,
221226
))
222227
}
223-
Ok(ResponseMessage::InvalidProof(reason)) => {
228+
Ok(SubmitProofResponseMessage::InvalidProof(reason)) => {
224229
error!("Batcher responded with invalid proof: {}", reason);
225230
Err(SubmitError::InvalidProof(reason))
226231
}
227-
Ok(ResponseMessage::CreateNewTaskError(merkle_root, error)) => {
232+
Ok(SubmitProofResponseMessage::CreateNewTaskError(merkle_root, error)) => {
228233
error!("Batcher responded with create new task error: {}", error);
229234
Err(SubmitError::BatchSubmissionFailed(
230235
"Could not create task with merkle root ".to_owned()
@@ -233,18 +238,18 @@ async fn handle_batcher_response(msg: Message) -> Result<BatchInclusionData, Sub
233238
+ &error,
234239
))
235240
}
236-
Ok(ResponseMessage::ProtocolVersion(_)) => {
241+
Ok(SubmitProofResponseMessage::ProtocolVersion(_)) => {
237242
error!("Batcher responded with protocol version instead of batch inclusion data");
238243
Err(SubmitError::UnexpectedBatcherResponse(
239244
"Batcher responded with protocol version instead of batch inclusion data"
240245
.to_string(),
241246
))
242247
}
243-
Ok(ResponseMessage::BatchReset) => {
248+
Ok(SubmitProofResponseMessage::BatchReset) => {
244249
error!("Batcher responded with batch reset");
245250
Err(SubmitError::ProofQueueFlushed)
246251
}
247-
Ok(ResponseMessage::Error(e)) => {
252+
Ok(SubmitProofResponseMessage::Error(e)) => {
248253
error!("Batcher responded with error: {}", e);
249254
Err(SubmitError::GenericError(e))
250255
}

batcher/aligned-sdk/src/communication/protocol.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use futures_util::{stream::SplitStream, StreamExt};
22
use tokio::net::TcpStream;
33
use tokio_tungstenite::{MaybeTlsStream, WebSocketStream};
44

5-
use crate::core::{errors::SubmitError, types::ResponseMessage};
5+
use crate::core::{errors::SubmitError, types::SubmitProofResponseMessage};
66

77
use super::serialization::cbor_deserialize;
88

@@ -13,7 +13,7 @@ pub async fn check_protocol_version(
1313
) -> Result<(), SubmitError> {
1414
if let Some(Ok(msg)) = ws_read.next().await {
1515
match cbor_deserialize(msg.into_data().as_slice()) {
16-
Ok(ResponseMessage::ProtocolVersion(protocol_version)) => {
16+
Ok(SubmitProofResponseMessage::ProtocolVersion(protocol_version)) => {
1717
if protocol_version > EXPECTED_PROTOCOL_VERSION {
1818
return Err(SubmitError::ProtocolVersionMismatch {
1919
current: protocol_version,

batcher/aligned-sdk/src/communication/serialization.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use std::io::Read;
22

3-
use serde::{de::DeserializeOwned, Serialize};
3+
use serde::{de::DeserializeOwned, Deserialize, Serialize};
44

55
pub fn cbor_serialize<T: Serialize>(value: &T) -> Result<Vec<u8>, SerializationError> {
66
let mut buf = Vec::new();
@@ -12,7 +12,7 @@ pub fn cbor_deserialize<R: Read, T: DeserializeOwned>(buf: R) -> Result<T, Seria
1212
ciborium::from_reader(buf).map_err(|_| SerializationError)
1313
}
1414

15-
#[derive(Debug)]
15+
#[derive(Debug, Serialize, Deserialize, Clone)]
1616
pub struct SerializationError;
1717

1818
impl std::fmt::Display for SerializationError {

batcher/aligned-sdk/src/core/errors.rs

Lines changed: 11 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ use ethers::providers::ProviderError;
33
use ethers::signers::WalletError;
44
use ethers::types::transaction::eip712::Eip712Error;
55
use ethers::types::{SignatureError, H160};
6+
use serde::{Deserialize, Serialize};
67
use std::io;
78
use std::path::PathBuf;
89
use tokio_tungstenite::tungstenite::protocol::CloseFrame;
@@ -15,7 +16,6 @@ use super::types::ProofInvalidReason;
1516
pub enum AlignedError {
1617
SubmitError(SubmitError),
1718
VerificationError(VerificationError),
18-
NonceError(NonceError),
1919
ChainIdError(ChainIdError),
2020
MaxFeeEstimateError(MaxFeeEstimateError),
2121
FileError(FileError),
@@ -33,12 +33,6 @@ impl From<VerificationError> for AlignedError {
3333
}
3434
}
3535

36-
impl From<NonceError> for AlignedError {
37-
fn from(e: NonceError) -> Self {
38-
AlignedError::NonceError(e)
39-
}
40-
}
41-
4236
impl From<ChainIdError> for AlignedError {
4337
fn from(e: ChainIdError) -> Self {
4438
AlignedError::ChainIdError(e)
@@ -62,7 +56,6 @@ impl fmt::Display for AlignedError {
6256
match self {
6357
AlignedError::SubmitError(e) => write!(f, "Submit error: {}", e),
6458
AlignedError::VerificationError(e) => write!(f, "Verification error: {}", e),
65-
AlignedError::NonceError(e) => write!(f, "Nonce error: {}", e),
6659
AlignedError::ChainIdError(e) => write!(f, "Chain ID error: {}", e),
6760
AlignedError::MaxFeeEstimateError(e) => write!(f, "Max fee estimate error: {}", e),
6861
AlignedError::FileError(e) => write!(f, "File error: {}", e),
@@ -102,6 +95,7 @@ pub enum SubmitError {
10295
BatchSubmissionFailed(String),
10396
AddToBatchError,
10497
InvalidProofInclusionData,
98+
GetNonceError(String),
10599
GenericError(String),
106100
}
107101

@@ -216,6 +210,7 @@ impl fmt::Display for SubmitError {
216210
SubmitError::InvalidProofInclusionData => {
217211
write!(f, "Batcher responded with invalid batch inclusion data. Can't verify your proof was correctly included in the batch.")
218212
}
213+
SubmitError::GetNonceError(e) => write!(f, "Error while getting nonce {}", e),
219214
}
220215
}
221216
}
@@ -243,21 +238,14 @@ impl fmt::Display for VerificationError {
243238
}
244239
}
245240

246-
#[derive(Debug)]
247-
pub enum NonceError {
248-
EthereumProviderError(String),
249-
EthereumCallError(String),
250-
}
251-
252-
impl fmt::Display for NonceError {
253-
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
254-
match self {
255-
NonceError::EthereumProviderError(e) => {
256-
write!(f, "Ethereum provider error: {}", e)
257-
}
258-
NonceError::EthereumCallError(e) => write!(f, "Ethereum call error: {}", e),
259-
}
260-
}
241+
#[derive(Debug, Serialize, Deserialize, Clone)]
242+
pub enum GetNonceError {
243+
EthRpcError(String),
244+
ConnectionFailed(String),
245+
SerializationError(String),
246+
UnexpectedResponse(String),
247+
InvalidRequest(String),
248+
ProtocolMismatch { current: u16, expected: u16 },
261249
}
262250

263251
#[derive(Debug)]

batcher/aligned-sdk/src/core/types.rs

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -220,11 +220,29 @@ impl BatchInclusionData {
220220
}
221221

222222
#[derive(Debug, Clone, Serialize, Deserialize)]
223-
pub struct ClientMessage {
223+
pub struct SubmitProofMessage {
224224
pub verification_data: NoncedVerificationData,
225225
pub signature: Signature,
226226
}
227227

228+
#[derive(Debug, Clone, Serialize, Deserialize)]
229+
pub enum ClientMessage {
230+
GetNonceForAddress(Address),
231+
// Needs to be wrapped in box as the message is 3x bigger than the others
232+
// see https://rust-lang.github.io/rust-clippy/master/index.html#large_enum_variant
233+
SubmitProof(Box<SubmitProofMessage>),
234+
}
235+
236+
impl Display for ClientMessage {
237+
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
238+
// Use pattern matching to print the variant name
239+
match self {
240+
ClientMessage::GetNonceForAddress(_) => write!(f, "GetNonceForAddress"),
241+
ClientMessage::SubmitProof(_) => write!(f, "SubmitProof"),
242+
}
243+
}
244+
}
245+
228246
impl Eip712 for NoncedVerificationData {
229247
type Error = Eip712Error;
230248
fn domain(&self) -> Result<EIP712Domain, Self::Error> {
@@ -275,7 +293,7 @@ impl Eip712 for NoncedVerificationData {
275293
}
276294
}
277295

278-
impl ClientMessage {
296+
impl SubmitProofMessage {
279297
/// Client message is a wrap around verification data and its signature.
280298
/// The signature is obtained by calculating the commitments and then hashing them.
281299
pub async fn new(
@@ -287,7 +305,7 @@ impl ClientMessage {
287305
.await
288306
.expect("Failed to sign the verification data");
289307

290-
ClientMessage {
308+
Self {
291309
verification_data,
292310
signature,
293311
}
@@ -352,7 +370,7 @@ impl Display for ProofInvalidReason {
352370
}
353371

354372
#[derive(Debug, Clone, Serialize, Deserialize)]
355-
pub enum ResponseMessage {
373+
pub enum SubmitProofResponseMessage {
356374
BatchInclusionData(BatchInclusionData),
357375
ProtocolVersion(u16),
358376
CreateNewTaskError(String, String), //merkle-root, error
@@ -371,6 +389,13 @@ pub enum ResponseMessage {
371389
InvalidPaymentServiceAddress(Address, Address),
372390
}
373391

392+
#[derive(Debug, Clone, Serialize, Deserialize)]
393+
pub enum GetNonceResponseMessage {
394+
Nonce(U256),
395+
EthRpcError(String),
396+
InvalidRequest(String),
397+
}
398+
374399
#[derive(Debug, Clone, Copy)]
375400
pub enum Network {
376401
Devnet,

0 commit comments

Comments
 (0)