-
Notifications
You must be signed in to change notification settings - Fork 396
Expand file tree
/
Copy pathlib.rs
More file actions
2067 lines (1854 loc) · 79.2 KB
/
lib.rs
File metadata and controls
2067 lines (1854 loc) · 79.2 KB
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
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use aligned_sdk::communication::serialization::{cbor_deserialize, cbor_serialize};
use config::NonPayingConfig;
use connection::{send_message, WsMessageSink};
use dotenvy::dotenv;
use eth::service_manager::ServiceManager;
use eth::utils::{calculate_bumped_gas_price, get_batcher_signer, get_gas_price};
use ethers::contract::ContractError;
use ethers::signers::Signer;
use retry::batcher_retryables::{
cancel_create_new_task_retryable, create_new_task_retryable, get_user_balance_retryable,
get_user_nonce_from_ethereum_retryable, simulate_create_new_task_retryable,
user_balance_is_unlocked_retryable,
};
use retry::{retry_function, RetryError};
use tokio::time::{timeout, Instant};
use types::batch_state::BatchState;
use types::user_state::UserState;
use batch_queue::calculate_batch_size;
use std::cmp::Ordering;
use std::collections::HashMap;
use std::env;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
use aligned_sdk::core::constants::{
ADDITIONAL_SUBMISSION_GAS_COST_PER_PROOF, BATCHER_SUBMISSION_BASE_GAS_COST,
BUMP_BACKOFF_FACTOR, BUMP_MAX_RETRIES, BUMP_MAX_RETRY_DELAY, BUMP_MIN_RETRY_DELAY,
CBOR_ARRAY_MAX_OVERHEAD, CONNECTION_TIMEOUT, DEFAULT_MAX_FEE_PER_PROOF,
ETHEREUM_CALL_BACKOFF_FACTOR, ETHEREUM_CALL_MAX_RETRIES, ETHEREUM_CALL_MAX_RETRY_DELAY,
ETHEREUM_CALL_MIN_RETRY_DELAY, GAS_PRICE_PERCENTAGE_MULTIPLIER, PERCENTAGE_DIVIDER,
RESPOND_TO_TASK_FEE_LIMIT_PERCENTAGE_MULTIPLIER,
};
use aligned_sdk::core::types::{
ClientMessage, GetNonceResponseMessage, NoncedVerificationData, ProofInvalidReason,
ProvingSystemId, SubmitProofMessage, SubmitProofResponseMessage, VerificationCommitmentBatch,
VerificationData, VerificationDataCommitment,
};
use aws_sdk_s3::client::Client as S3Client;
use eth::payment_service::{BatcherPaymentService, CreateNewTaskFeeParams, SignerMiddlewareT};
use ethers::prelude::{Middleware, Provider};
use ethers::types::{Address, Signature, TransactionReceipt, U256};
use futures_util::{future, SinkExt, StreamExt, TryStreamExt};
use lambdaworks_crypto::merkle_tree::merkle::MerkleTree;
use lambdaworks_crypto::merkle_tree::traits::IsMerkleTreeBackend;
use log::{debug, error, info, warn};
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::{Mutex, MutexGuard, RwLock};
use tokio_tungstenite::tungstenite::{Error, Message};
use types::batch_queue::{self, BatchQueueEntry, BatchQueueEntryPriority};
use types::errors::{BatcherError, TransactionSendError};
use crate::config::{ConfigFromYaml, ContractDeploymentOutput};
use crate::telemetry::sender::TelemetrySender;
mod config;
mod connection;
mod eth;
pub mod gnark;
pub mod metrics;
pub mod retry;
pub mod risc_zero;
pub mod s3;
pub mod sp1;
pub mod telemetry;
pub mod types;
mod zk_utils;
pub const LISTEN_NEW_BLOCKS_MAX_TIMES: usize = usize::MAX;
pub struct Batcher {
s3_client: S3Client,
s3_bucket_name: String,
download_endpoint: String,
eth_ws_url: String,
eth_ws_url_fallback: String,
batcher_signer: Arc<SignerMiddlewareT>,
batcher_signer_fallback: Arc<SignerMiddlewareT>,
chain_id: U256,
payment_service: BatcherPaymentService,
payment_service_fallback: BatcherPaymentService,
service_manager: ServiceManager,
service_manager_fallback: ServiceManager,
batch_state: Mutex<BatchState>,
min_block_interval: u64,
transaction_wait_timeout: u64,
max_proof_size: usize,
max_batch_byte_size: usize,
max_batch_proof_qty: usize,
last_uploaded_batch_block: Mutex<u64>,
pre_verification_is_enabled: bool,
non_paying_config: Option<NonPayingConfig>,
posting_batch: Mutex<bool>,
disabled_verifiers: Mutex<U256>,
aggregator_fee_percentage_multiplier: u128,
aggregator_gas_cost: u128,
pub metrics: metrics::BatcherMetrics,
pub telemetry: TelemetrySender,
}
impl Batcher {
pub async fn new(config_file: String) -> Self {
dotenv().ok();
// https://docs.aws.amazon.com/sdk-for-rust/latest/dg/localstack.html
let upload_endpoint = env::var("UPLOAD_ENDPOINT").ok();
let s3_bucket_name =
env::var("AWS_BUCKET_NAME").expect("AWS_BUCKET_NAME not found in environment");
let download_endpoint =
env::var("DOWNLOAD_ENDPOINT").expect("DOWNLOAD_ENDPOINT not found in environment");
let s3_client = s3::create_client(upload_endpoint).await;
let config = ConfigFromYaml::new(config_file);
// Ensure max_batch_bytes_size can at least hold one proof of max_proof_size,
// including the overhead introduced by serialization
assert!(
config.batcher.max_proof_size + CBOR_ARRAY_MAX_OVERHEAD
<= config.batcher.max_batch_byte_size,
"max_batch_bytes_size ({}) not big enough for one max_proof_size ({}) proof",
config.batcher.max_batch_byte_size,
config.batcher.max_proof_size
);
let deployment_output =
ContractDeploymentOutput::new(config.aligned_layer_deployment_config_file_path);
log::info!(
"Starting metrics server on port {}",
config.batcher.metrics_port
);
let metrics = metrics::BatcherMetrics::start(config.batcher.metrics_port)
.expect("Failed to start metrics server");
let eth_http_provider =
eth::get_provider(config.eth_rpc_url.clone()).expect("Failed to get provider");
let eth_http_provider_fallback = eth::get_provider(config.eth_rpc_url_fallback.clone())
.expect("Failed to get fallback provider");
// FIXME(marian): We are getting just the last block number right now, but we should really
// have the last submitted batch block registered and query it when the batcher is initialized.
let last_uploaded_batch_block = match eth_http_provider.get_block_number().await {
Ok(block_num) => block_num,
Err(e) => {
warn!(
"Failed to get block number with main rpc, trying with fallback rpc. Err: {:?}",
e
);
eth_http_provider_fallback
.get_block_number()
.await
.expect("Failed to get block number with fallback rpc")
}
};
let last_uploaded_batch_block = last_uploaded_batch_block.as_u64();
let chain_id = match eth_http_provider.get_chainid().await {
Ok(chain_id) => chain_id,
Err(e) => {
warn!("Failed to get chain id with main rpc: {}", e);
eth_http_provider_fallback
.get_chainid()
.await
.expect("Failed to get chain id with fallback rpc")
}
};
let batcher_signer = get_batcher_signer(eth_http_provider.clone(), config.ecdsa.clone())
.await
.expect("Failed to get Batcher signer");
let batcher_signer_fallback =
get_batcher_signer(eth_http_provider_fallback.clone(), config.ecdsa.clone())
.await
.expect("Failed to get Batcher signer fallback");
let payment_service = eth::payment_service::get_batcher_payment_service(
batcher_signer.clone(),
deployment_output.addresses.batcher_payment_service.clone(),
)
.await
.expect("Failed to get Batcher Payment Service contract");
let payment_service_fallback = eth::payment_service::get_batcher_payment_service(
batcher_signer_fallback.clone(),
deployment_output.addresses.batcher_payment_service,
)
.await
.expect("Failed to get fallback Batcher Payment Service contract");
let service_manager = eth::service_manager::get_service_manager(
eth_http_provider.clone(),
config.ecdsa.clone(),
deployment_output.addresses.service_manager.clone(),
)
.await
.expect("Failed to get Service Manager contract");
let service_manager_fallback = eth::service_manager::get_service_manager(
eth_http_provider_fallback.clone(),
config.ecdsa,
deployment_output.addresses.service_manager,
)
.await
.expect("Failed to get fallback Service Manager contract");
let mut user_states = HashMap::new();
let mut batch_state = BatchState::new(config.batcher.max_queue_size);
let non_paying_config = if let Some(non_paying_config) = config.batcher.non_paying {
warn!("Non-paying address configuration detected. Will replace non-paying address {} with configured address.",
non_paying_config.address);
let non_paying_config = NonPayingConfig::from_yaml_config(non_paying_config).await;
let nonpaying_nonce = payment_service
.user_nonces(non_paying_config.replacement.address())
.call()
.await
.expect("Could not get non-paying nonce from Ethereum");
let non_paying_user_state = UserState::new(nonpaying_nonce);
user_states.insert(
non_paying_config.replacement.address(),
non_paying_user_state,
);
batch_state =
BatchState::new_with_user_states(user_states, config.batcher.max_queue_size);
Some(non_paying_config)
} else {
None
};
let disabled_verifiers = match service_manager.disabled_verifiers().call().await {
Ok(disabled_verifiers) => Ok(disabled_verifiers),
Err(_) => service_manager_fallback.disabled_verifiers().call().await,
}
.expect("Failed to get disabled verifiers");
let telemetry = TelemetrySender::new(format!(
"http://{}",
config.batcher.telemetry_ip_port_address
));
Self {
s3_client,
s3_bucket_name,
download_endpoint,
eth_ws_url: config.eth_ws_url,
eth_ws_url_fallback: config.eth_ws_url_fallback,
batcher_signer,
batcher_signer_fallback,
chain_id,
payment_service,
payment_service_fallback,
service_manager,
service_manager_fallback,
min_block_interval: config.batcher.block_interval,
transaction_wait_timeout: config.batcher.transaction_wait_timeout,
max_proof_size: config.batcher.max_proof_size,
max_batch_byte_size: config.batcher.max_batch_byte_size,
max_batch_proof_qty: config.batcher.max_batch_proof_qty,
last_uploaded_batch_block: Mutex::new(last_uploaded_batch_block),
pre_verification_is_enabled: config.batcher.pre_verification_is_enabled,
non_paying_config,
aggregator_fee_percentage_multiplier: config
.batcher
.aggregator_fee_percentage_multiplier,
aggregator_gas_cost: config.batcher.aggregator_gas_cost,
posting_batch: Mutex::new(false),
batch_state: Mutex::new(batch_state),
disabled_verifiers: Mutex::new(disabled_verifiers),
metrics,
telemetry,
}
}
pub async fn listen_connections(self: Arc<Self>, address: &str) -> Result<(), BatcherError> {
// Create the event loop and TCP listener we'll accept connections on.
let listener = TcpListener::bind(address)
.await
.map_err(|e| BatcherError::TcpListenerError(e.to_string()))?;
info!("Listening on: {}", address);
loop {
match listener.accept().await {
Ok((stream, addr)) => {
let batcher = self.clone();
// Let's spawn the handling of each connection in a separate task.
tokio::spawn(batcher.handle_connection(stream, addr));
}
Err(e) => {
self.metrics.user_error(&["connection_accept_error", ""]);
error!("Couldn't accept new connection: {}", e);
}
}
}
}
/// Listen for Ethereum new blocks.
/// Retries on recoverable errors using exponential backoff
/// with the maximum number of retries and a `MAX_DELAY` of 1 hour.
pub async fn listen_new_blocks(self: Arc<Self>) -> Result<(), BatcherError> {
retry_function(
|| {
let app = self.clone();
async move { app.listen_new_blocks_retryable().await }
},
ETHEREUM_CALL_MIN_RETRY_DELAY,
ETHEREUM_CALL_BACKOFF_FACTOR,
LISTEN_NEW_BLOCKS_MAX_TIMES,
ETHEREUM_CALL_MAX_RETRY_DELAY,
)
.await
.map_err(|e| e.inner())
}
pub async fn listen_new_blocks_retryable(
self: Arc<Self>,
) -> Result<(), RetryError<BatcherError>> {
let eth_ws_provider = Provider::connect(&self.eth_ws_url).await.map_err(|e| {
warn!("Failed to instantiate Ethereum websocket provider");
RetryError::Transient(BatcherError::EthereumSubscriptionError(e.to_string()))
})?;
let eth_ws_provider_fallback =
Provider::connect(&self.eth_ws_url_fallback)
.await
.map_err(|e| {
warn!("Failed to instantiate fallback Ethereum websocket provider");
RetryError::Transient(BatcherError::EthereumSubscriptionError(e.to_string()))
})?;
let mut stream = eth_ws_provider.subscribe_blocks().await.map_err(|e| {
warn!("Error subscribing to blocks.");
RetryError::Transient(BatcherError::EthereumSubscriptionError(e.to_string()))
})?;
let mut stream_fallback =
eth_ws_provider_fallback
.subscribe_blocks()
.await
.map_err(|e| {
warn!("Error subscribing to blocks.");
RetryError::Transient(BatcherError::EthereumSubscriptionError(e.to_string()))
})?;
let last_seen_block = Mutex::<u64>::new(0);
while let Some(block) = tokio::select! {
block = stream.next() => block,
block = stream_fallback.next() => block,
} {
let batcher = self.clone();
let block_number = block.number.unwrap_or_default();
let block_number = u64::try_from(block_number).unwrap_or_default();
{
let mut last_seen_block = last_seen_block.lock().await;
if block_number <= *last_seen_block {
continue;
}
*last_seen_block = block_number;
}
info!("Received new block: {}", block_number);
tokio::spawn(async move {
if let Err(e) = batcher.handle_new_block(block_number).await {
error!("Error when handling new block: {:?}", e);
};
});
}
error!("Failed to fetch blocks");
Err(RetryError::Transient(
BatcherError::EthereumSubscriptionError("Could not get new blocks".to_string()),
))
}
async fn handle_connection(
self: Arc<Self>,
raw_stream: TcpStream,
addr: SocketAddr,
) -> Result<(), BatcherError> {
info!("Incoming TCP connection from: {}", addr);
self.metrics.open_connections.inc();
let ws_stream_future = tokio_tungstenite::accept_async(raw_stream);
let ws_stream =
match timeout(Duration::from_secs(CONNECTION_TIMEOUT), ws_stream_future).await {
Ok(Ok(stream)) => stream,
Ok(Err(e)) => {
warn!("Error while establishing websocket connection: {}", e);
self.metrics.open_connections.dec();
return Ok(());
}
Err(e) => {
warn!("Error while establishing websocket connection: {}", e);
self.metrics.open_connections.dec();
self.metrics.user_error(&["user_timeout", ""]);
return Ok(());
}
};
debug!("WebSocket connection established: {}", addr);
let (outgoing, incoming) = ws_stream.split();
let outgoing = Arc::new(RwLock::new(outgoing));
let protocol_version_msg = SubmitProofResponseMessage::ProtocolVersion(
aligned_sdk::communication::protocol::EXPECTED_PROTOCOL_VERSION,
);
let serialized_protocol_version_msg = cbor_serialize(&protocol_version_msg)
.map_err(|e| BatcherError::SerializationError(e.to_string()))?;
outgoing
.write()
.await
.send(Message::binary(serialized_protocol_version_msg))
.await?;
let mut incoming_filter = incoming.try_filter(|msg| future::ready(msg.is_binary()));
let future_msg = incoming_filter.try_next();
// timeout to prevent a DOS attack
match timeout(Duration::from_secs(CONNECTION_TIMEOUT), future_msg).await {
Ok(Ok(Some(msg))) => {
self.clone().handle_message(msg, outgoing.clone()).await?;
}
Err(elapsed) => {
warn!("[{}] {}", &addr, elapsed);
self.metrics.user_error(&["user_timeout", ""]);
self.metrics.open_connections.dec();
return Ok(());
}
Ok(Ok(None)) => {
info!("[{}] Connection closed by the other side", &addr);
self.metrics.open_connections.dec();
return Ok(());
}
Ok(Err(e)) => {
error!("Unexpected error: {}", e);
self.metrics.open_connections.dec();
return Ok(());
}
};
match incoming_filter
.try_for_each(|msg| self.clone().handle_message(msg, outgoing.clone()))
.await
{
Err(e) => {
self.metrics.broken_ws_connections.inc();
error!("Unexpected error: {}", e)
}
Ok(_) => info!("{} disconnected", &addr),
}
self.metrics.open_connections.dec();
Ok(())
}
/// Handle an individual message from the client.
async fn handle_message(
self: Arc<Self>,
message: Message,
ws_conn_sink: WsMessageSink,
) -> Result<(), Error> {
// Deserialize verification data from message
let client_msg: ClientMessage = match cbor_deserialize(message.into_data().as_slice()) {
Ok(msg) => msg,
Err(e) => {
warn!("Failed to deserialize message: {}", e);
self.metrics.user_error(&["deserialize_error", ""]);
return Ok(());
}
};
info!("Received new client message of type: {}", client_msg);
match client_msg {
ClientMessage::GetNonceForAddress(address) => {
self.clone()
.handle_get_nonce_for_address_msg(address, ws_conn_sink)
.await
}
ClientMessage::SubmitProof(msg) => {
self.clone()
.handle_submit_proof_msg(msg, ws_conn_sink)
.await
}
}
}
async fn handle_get_nonce_for_address_msg(
self: Arc<Self>,
mut address: Address,
ws_conn_sink: WsMessageSink,
) -> Result<(), Error> {
if self.is_nonpaying(&address) {
info!("Handling nonpaying message");
let Some(non_paying_config) = self.non_paying_config.as_ref() else {
warn!(
"There isn't a non-paying configuration loaded. This message will be ignored"
);
send_message(
ws_conn_sink.clone(),
GetNonceResponseMessage::InvalidRequest(
"There isn't a non-paying configuration loaded.".to_string(),
),
)
.await;
return Ok(());
};
let replacement_addr = non_paying_config.replacement.address();
address = replacement_addr;
}
let cached_user_nonce = {
let batch_state_lock = self.batch_state.lock().await;
batch_state_lock.get_user_nonce(&address).await
};
let user_nonce = if let Some(user_nonce) = cached_user_nonce {
user_nonce
} else {
match self.get_user_nonce_from_ethereum(address).await {
Ok(ethereum_user_nonce) => ethereum_user_nonce,
Err(e) => {
error!(
"Failed to get user nonce from Ethereum for address {address:?}. Error: {e:?}"
);
send_message(
ws_conn_sink.clone(),
GetNonceResponseMessage::EthRpcError("Eth RPC error".to_string()),
)
.await;
return Ok(());
}
}
};
send_message(
ws_conn_sink.clone(),
GetNonceResponseMessage::Nonce(user_nonce),
)
.await;
Ok(())
}
async fn handle_submit_proof_msg(
self: Arc<Self>,
client_msg: Box<SubmitProofMessage>,
ws_conn_sink: WsMessageSink,
) -> Result<(), Error> {
let msg_nonce = client_msg.verification_data.nonce;
debug!("Received message with nonce: {msg_nonce:?}");
self.metrics.received_proofs.inc();
// * ---------------------------------------------------*
// * Perform validations over the message *
// * ---------------------------------------------------*
// All check functions sends the error to the metrics server and logs it
// if they return false
if !self.msg_chain_id_is_valid(&client_msg, &ws_conn_sink).await {
return Ok(());
}
if !self
.msg_batcher_payment_addr_is_valid(&client_msg, &ws_conn_sink)
.await
{
return Ok(());
}
if !self
.msg_proof_size_is_valid(&client_msg, &ws_conn_sink)
.await
{
return Ok(());
}
let Some(addr) = self
.msg_signature_is_valid(&client_msg, &ws_conn_sink)
.await
else {
return Ok(());
};
let nonced_verification_data = client_msg.verification_data.clone();
// When pre-verification is enabled, batcher will verify proofs for faster feedback with clients
if self.pre_verification_is_enabled {
let verification_data = &nonced_verification_data.verification_data;
if self
.is_verifier_disabled(verification_data.proving_system)
.await
{
warn!(
"Verifier for proving system {} is disabled, skipping verification",
verification_data.proving_system
);
send_message(
ws_conn_sink.clone(),
SubmitProofResponseMessage::InvalidProof(ProofInvalidReason::DisabledVerifier(
verification_data.proving_system,
)),
)
.await;
self.metrics.user_error(&[
"disabled_verifier",
&format!("{}", verification_data.proving_system),
]);
return Ok(());
}
if !zk_utils::verify(verification_data).await {
error!("Invalid proof detected. Verification failed");
send_message(
ws_conn_sink.clone(),
SubmitProofResponseMessage::InvalidProof(ProofInvalidReason::RejectedProof),
)
.await;
self.metrics.user_error(&[
"rejected_proof",
&format!("{}", verification_data.proving_system),
]);
return Ok(());
}
}
if self.is_nonpaying(&addr) {
// TODO: Non paying msg and paying should share some logic
return self
.handle_nonpaying_msg(ws_conn_sink.clone(), &client_msg)
.await;
}
info!("Handling paying message");
// We don't need a batch state lock here, since if the user locks its funds
// after the check, some blocks should pass until he can withdraw.
// It is safe to do just do this here.
if !self.msg_user_balance_is_locked(&addr, &ws_conn_sink).await {
return Ok(());
}
// We acquire the lock first only to query if the user is already present and the lock is dropped.
// If it was not present, then the user nonce is queried to the Aligned contract.
// Lastly, we get a lock of the batch state again and insert the user state if it was still missing.
let is_user_in_state: bool;
{
let batch_state_lock = self.batch_state.lock().await;
is_user_in_state = batch_state_lock.user_states.contains_key(&addr);
}
if !is_user_in_state {
let ethereum_user_nonce = match self.get_user_nonce_from_ethereum(addr).await {
Ok(ethereum_user_nonce) => ethereum_user_nonce,
Err(e) => {
error!(
"Failed to get user nonce from Ethereum for address {addr:?}. Error: {e:?}"
);
send_message(
ws_conn_sink.clone(),
SubmitProofResponseMessage::EthRpcError,
)
.await;
self.metrics.user_error(&["eth_rpc_error", ""]);
return Ok(());
}
};
let user_state = UserState::new(ethereum_user_nonce);
let mut batch_state_lock = self.batch_state.lock().await;
batch_state_lock
.user_states
.entry(addr)
.or_insert(user_state);
}
// * ---------------------------------------------------*
// * Perform validations over user state *
// * ---------------------------------------------------*
let Some(user_balance) = self.get_user_balance(&addr).await else {
error!("Could not get balance for address {addr:?}");
send_message(
ws_conn_sink.clone(),
SubmitProofResponseMessage::EthRpcError,
)
.await;
self.metrics.user_error(&["eth_rpc_error", ""]);
return Ok(());
};
// For now on until the message is fully processed, the batch state is locked
// This is needed because we need to query the user state to make validations and
// finally add the proof to the batch queue.
let mut batch_state_lock = self.batch_state.lock().await;
let msg_max_fee = nonced_verification_data.max_fee;
let Some(user_last_max_fee_limit) =
batch_state_lock.get_user_last_max_fee_limit(&addr).await
else {
std::mem::drop(batch_state_lock);
send_message(
ws_conn_sink.clone(),
SubmitProofResponseMessage::AddToBatchError,
)
.await;
self.metrics.user_error(&["batcher_state_error", ""]);
return Ok(());
};
if msg_max_fee > user_last_max_fee_limit {
std::mem::drop(batch_state_lock);
warn!("Invalid max fee for address {addr}, had fee limit of {user_last_max_fee_limit:?}, sent {msg_max_fee:?}");
send_message(
ws_conn_sink.clone(),
SubmitProofResponseMessage::InvalidMaxFee,
)
.await;
self.metrics.user_error(&["invalid_max_fee", ""]);
return Ok(());
}
let Some(user_accumulated_fee) = batch_state_lock.get_user_total_fees_in_queue(&addr).await
else {
std::mem::drop(batch_state_lock);
send_message(
ws_conn_sink.clone(),
SubmitProofResponseMessage::AddToBatchError,
)
.await;
self.metrics.user_error(&["batcher_state_error", ""]);
return Ok(());
};
if !self.verify_user_has_enough_balance(user_balance, user_accumulated_fee, msg_max_fee) {
std::mem::drop(batch_state_lock);
send_message(
ws_conn_sink.clone(),
SubmitProofResponseMessage::InsufficientBalance(addr),
)
.await;
self.metrics.user_error(&["insufficient_balance", ""]);
return Ok(());
}
let cached_user_nonce = batch_state_lock.get_user_nonce(&addr).await;
let Some(expected_nonce) = cached_user_nonce else {
error!("Failed to get cached user nonce: User not found in user states, but it should have been already inserted");
std::mem::drop(batch_state_lock);
send_message(
ws_conn_sink.clone(),
SubmitProofResponseMessage::AddToBatchError,
)
.await;
self.metrics.user_error(&["batcher_state_error", ""]);
return Ok(());
};
if expected_nonce < msg_nonce {
std::mem::drop(batch_state_lock);
warn!("Invalid nonce for address {addr}, expected nonce: {expected_nonce:?}, received nonce: {msg_nonce:?}");
send_message(
ws_conn_sink.clone(),
SubmitProofResponseMessage::InvalidNonce,
)
.await;
self.metrics.user_error(&["invalid_nonce", ""]);
return Ok(());
}
// In this case, the message might be a replacement one. If it is valid,
// we replace the old entry with the new from the replacement message.
if expected_nonce > msg_nonce {
info!("Possible replacement message received: Expected nonce {expected_nonce:?} - message nonce: {msg_nonce:?}");
self.handle_replacement_message(
batch_state_lock,
nonced_verification_data,
ws_conn_sink.clone(),
client_msg.signature,
addr,
)
.await;
return Ok(());
}
// * ---------------------------------------------------------------------*
// * Perform validation over batcher queue *
// * ---------------------------------------------------------------------*
if batch_state_lock.is_queue_full() {
info!("Batch queue is full. Evaluating if the incoming proof can replace a lower-priority entry.");
let msg_entry_priority = BatchQueueEntryPriority::new(
nonced_verification_data.max_fee,
nonced_verification_data.nonce,
);
if let Some(lowest_entry_priority) = batch_state_lock.lowest_entry_priority() {
// If the new proof has more priority than the lowest one in the queue, discard the latter one and push the new one
if lowest_entry_priority.cmp(&msg_entry_priority) == Ordering::Greater {
let Some((removed_entry, _)) = batch_state_lock.batch_queue.pop() else {
warn!("Failed to remove lowest-priority proof despite queue being full.");
std::mem::drop(batch_state_lock);
send_message(
ws_conn_sink.clone(),
SubmitProofResponseMessage::BatchQueueLimitExceededError,
)
.await;
return Ok(());
};
info!(
"Incoming proof (nonce: {}, fee: {}) has higher priority. Replacing lowest priority proof from sender {} with nonce {}.",
nonced_verification_data.nonce,
nonced_verification_data.max_fee,
removed_entry.sender,
removed_entry.nonced_verification_data.nonce
);
batch_state_lock.update_user_state_on_entry_removal(&removed_entry);
if let Some(removed_entry_ws) = removed_entry.messaging_sink {
send_message(
removed_entry_ws,
SubmitProofResponseMessage::BatchQueueLimitExceededError,
)
.await;
};
} else {
warn!(
"Incoming proof (nonce: {}, fee: {}) has lower priority than all entries in the full queue. Rejecting submission.",
nonced_verification_data.nonce,
nonced_verification_data.max_fee
);
std::mem::drop(batch_state_lock);
send_message(
ws_conn_sink.clone(),
SubmitProofResponseMessage::BatchQueueLimitExceededError,
)
.await;
return Ok(());
}
}
}
// * ---------------------------------------------------------------------*
// * Add message data into the queue and update user state *
// * ---------------------------------------------------------------------*
if let Err(e) = self
.add_to_batch(
batch_state_lock,
nonced_verification_data,
ws_conn_sink.clone(),
client_msg.signature,
addr,
)
.await
{
error!("Error while adding entry to batch: {e:?}");
send_message(ws_conn_sink, SubmitProofResponseMessage::AddToBatchError).await;
self.metrics.user_error(&["add_to_batch_error", ""]);
return Ok(());
};
info!("Verification data message handled");
Ok(())
}
async fn is_verifier_disabled(&self, verifier: ProvingSystemId) -> bool {
let disabled_verifiers = self.disabled_verifiers.lock().await;
zk_utils::is_verifier_disabled(*disabled_verifiers, verifier)
}
// Verifies user has enough balance for paying all his proofs in the current batch.
fn verify_user_has_enough_balance(
&self,
user_balance: U256,
user_accumulated_fee: U256,
new_msg_max_fee: U256,
) -> bool {
let required_balance: U256 = user_accumulated_fee + new_msg_max_fee;
user_balance >= required_balance
}
/// Handles a replacement message
/// First checks if the message is already in the batch
/// If the message is in the batch, checks if the max fee is higher
/// If the max fee is higher, replaces the message in the batch
/// If the max fee is lower, sends an error message to the client
/// If the message is not in the batch, sends an error message to the client
/// Returns true if the message was replaced in the batch, false otherwise
async fn handle_replacement_message(
&self,
mut batch_state_lock: MutexGuard<'_, BatchState>,
nonced_verification_data: NoncedVerificationData,
ws_conn_sink: WsMessageSink,
signature: Signature,
addr: Address,
) {
let replacement_max_fee = nonced_verification_data.max_fee;
let nonce = nonced_verification_data.nonce;
let Some(entry) = batch_state_lock.get_entry(addr, nonce) else {
std::mem::drop(batch_state_lock);
warn!("Invalid nonce for address {addr}. Queue entry with nonce {nonce} not found");
send_message(
ws_conn_sink.clone(),
SubmitProofResponseMessage::InvalidNonce,
)
.await;
self.metrics.user_error(&["invalid_nonce", ""]);
return;
};
let original_max_fee = entry.nonced_verification_data.max_fee;
if original_max_fee > replacement_max_fee {
std::mem::drop(batch_state_lock);
warn!("Invalid replacement message for address {addr}, had max fee: {original_max_fee:?}, received fee: {replacement_max_fee:?}");
send_message(
ws_conn_sink.clone(),
SubmitProofResponseMessage::InvalidReplacementMessage,
)
.await;
self.metrics
.user_error(&["invalid_replacement_message", ""]);
return;
}
info!("Replacing message for address {addr} with nonce {nonce} and max fee {replacement_max_fee}");
// The replacement entry is built from the old entry and validated for then to be replaced
let mut replacement_entry = entry.clone();
replacement_entry.signature = signature;
replacement_entry.verification_data_commitment =
nonced_verification_data.verification_data.clone().into();
replacement_entry.nonced_verification_data = nonced_verification_data;
// Close old sink in old entry and replace it with the new one
{
if let Some(messaging_sink) = replacement_entry.messaging_sink {
let mut old_sink = messaging_sink.write().await;
if let Err(e) = old_sink.close().await {
// we dont want to exit here, just log the error
warn!("Error closing sink: {e:?}");
} else {
info!("Old websocket sink closed");
}
} else {
warn!(
"Old websocket sink was empty. This should only happen in testing environments"
)
};
}
replacement_entry.messaging_sink = Some(ws_conn_sink.clone());
if !batch_state_lock.replacement_entry_is_valid(&replacement_entry) {
std::mem::drop(batch_state_lock);
warn!("Invalid replacement message");
send_message(
ws_conn_sink.clone(),
SubmitProofResponseMessage::InvalidReplacementMessage,
)
.await;
self.metrics
.user_error(&["invalid_replacement_message", ""]);
return;
}
info!(
"Replacement entry is valid, incrementing fee for sender: {:?}, nonce: {:?}, max_fee: {:?}",
replacement_entry.sender, replacement_entry.nonced_verification_data.nonce, replacement_max_fee
);
// remove the old entry and insert the new one
// note that the entries are considered equal for the priority queue
// if they have the same nonce and sender, so we can remove the old entry
// by calling remove with the new entry
batch_state_lock.batch_queue.remove(&replacement_entry);
batch_state_lock.batch_queue.push(
replacement_entry.clone(),
BatchQueueEntryPriority::new(replacement_max_fee, nonce),
);
// update max_fee_limit
let updated_max_fee_limit_in_batch = batch_state_lock.get_user_min_fee_in_batch(&addr);
if batch_state_lock
.update_user_max_fee_limit(&addr, updated_max_fee_limit_in_batch)
.is_none()