-
Notifications
You must be signed in to change notification settings - Fork 396
Expand file tree
/
Copy pathlib.rs
More file actions
2771 lines (2492 loc) · 108 KB
/
lib.rs
File metadata and controls
2771 lines (2492 loc) · 108 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_current_block_number_retryable, get_user_balance_retryable,
get_user_nonce_from_ethereum_retryable, query_balance_unlocked_events_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::collections::HashMap;
use std::env;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
use aligned_sdk::common::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::common::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::{Http, Middleware, Provider};
use ethers::types::{Address, Signature, TransactionReceipt, U256, U64};
use futures_util::{future, join, 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};
// Message handler lock timeout
const MESSAGE_HANDLER_LOCK_TIMEOUT: Duration = Duration::from_secs(10);
const POLLING_EVENTS_LOCK_TIMEOUT: Duration = Duration::from_secs(300);
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;
pub mod circom;
mod config;
mod connection;
mod eth;
mod ffi;
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 {
// Configuration parameters
s3_client: S3Client,
s3_bucket_name: String,
download_endpoint: String,
s3_client_secondary: Option<S3Client>,
s3_bucket_name_secondary: Option<String>,
download_endpoint_secondary: Option<String>,
eth_ws_url: String,
eth_ws_url_fallback: String,
batcher_signer: Arc<SignerMiddlewareT>,
batcher_signer_fallback: Arc<SignerMiddlewareT>,
eth_http_provider: Provider<Http>,
eth_http_provider_fallback: Provider<Http>,
chain_id: U256,
payment_service: BatcherPaymentService,
payment_service_fallback: BatcherPaymentService,
service_manager: ServiceManager,
service_manager_fallback: ServiceManager,
min_block_interval: u64,
transaction_wait_timeout: u64,
max_proof_size: usize,
max_batch_byte_size: usize,
max_batch_proof_qty: usize,
pre_verification_is_enabled: bool,
non_paying_config: Option<NonPayingConfig>,
aggregator_fee_percentage_multiplier: u128,
aggregator_gas_cost: u128,
current_min_max_fee: RwLock<U256>,
amount_of_proofs_for_min_max_fee: usize,
min_bump_percentage: U256,
balance_unlock_polling_interval_seconds: u64,
// Shared state access:
// Two kinds of threads interact with the shared state:
// 1. User message processing threads (run in parallel)
// 2. Batch creation thread (runs sequentially, includes failure recovery)
//
// Locking rules:
// - To avoid deadlocks, always acquire `user_states` before `batch_state`.
// - During failure recovery, restoring a valid state may require breaking this rule:
// additional user locks might be acquired *after* the batch lock.
// (See the `restore` algorithm in the `batch_queue` module.)
//
// Because of this exception, user message handling uses lock acquisition with timeouts.
batch_state: Mutex<BatchState>,
user_states: Arc<RwLock<HashMap<Address, Arc<Mutex<UserState>>>>>,
last_uploaded_batch_block: Mutex<u64>,
/// This is used to avoid multiple batches being submitted at the same time
/// It could be removed in the future by changing how we spawn
/// the batch creation task
posting_batch: Mutex<bool>,
disabled_verifiers: Mutex<U256>,
// Observability and monitoring
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
// Primary S3 configuration
let s3_config_primary = s3::S3Config {
access_key_id: env::var("AWS_ACCESS_KEY_ID").ok(),
secret_access_key: env::var("AWS_SECRET_ACCESS_KEY").ok(),
region: env::var("AWS_REGION").ok(),
endpoint_url: 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(s3_config_primary).await;
// Secondary S3 configuration (optional)
let s3_bucket_name_secondary = env::var("AWS_BUCKET_NAME_SECONDARY").ok();
let download_endpoint_secondary = env::var("DOWNLOAD_ENDPOINT_SECONDARY").ok();
let s3_client_secondary = if s3_bucket_name_secondary.is_some()
&& download_endpoint_secondary.is_some()
{
let s3_config_secondary = s3::S3Config {
access_key_id: env::var("AWS_ACCESS_KEY_ID_SECONDARY").ok(),
secret_access_key: env::var("AWS_SECRET_ACCESS_KEY_SECONDARY").ok(),
region: env::var("AWS_REGION_SECONDARY").ok(),
endpoint_url: env::var("UPLOAD_ENDPOINT_SECONDARY").ok(),
};
Some(s3::create_client(s3_config_secondary).await)
} else {
info!("Secondary S3 configuration not found or incomplete. Operating with primary S3 only.");
None
};
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);
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 user_states = Arc::new(RwLock::new(HashMap::new()));
let 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.write().await.insert(
non_paying_config.replacement.address(),
Arc::new(Mutex::new(non_paying_user_state)),
);
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,
s3_client_secondary,
s3_bucket_name_secondary,
download_endpoint_secondary,
eth_ws_url: config.eth_ws_url,
eth_ws_url_fallback: config.eth_ws_url_fallback,
batcher_signer,
batcher_signer_fallback,
eth_http_provider,
eth_http_provider_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,
amount_of_proofs_for_min_max_fee: config.batcher.amount_of_proofs_for_min_max_fee,
min_bump_percentage: U256::from(config.batcher.min_bump_percentage),
balance_unlock_polling_interval_seconds: config
.batcher
.balance_unlock_polling_interval_seconds,
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),
user_states,
disabled_verifiers: Mutex::new(disabled_verifiers),
current_min_max_fee: RwLock::new(U256::zero()),
metrics,
telemetry,
}
}
async fn update_evicted_user_state_with_lock(
&self,
removed_entry: &types::batch_queue::BatchQueueEntry,
batch_queue: &types::batch_queue::BatchQueue,
user_state_guard: &mut tokio::sync::MutexGuard<'_, crate::types::user_state::UserState>,
) {
let addr = removed_entry.sender;
let new_last_max_fee_limit = match batch_queue
.iter()
.filter(|(e, _)| e.sender == addr)
.next_back()
{
Some((last_entry, _)) => last_entry.nonced_verification_data.max_fee,
None => {
self.user_states.write().await.remove(&addr);
return;
}
};
user_state_guard.proofs_in_batch -= 1;
user_state_guard.nonce -= U256::one();
user_state_guard.total_fees_in_queue -= removed_entry.nonced_verification_data.max_fee;
user_state_guard.last_max_fee_limit = new_last_max_fee_limit;
}
// Fallback async version for restoration path where we don't have pre-held locks
async fn update_evicted_user_state_async(
&self,
removed_entry: &types::batch_queue::BatchQueueEntry,
batch_queue: &types::batch_queue::BatchQueue,
) -> Option<()> {
let addr = removed_entry.sender;
let new_last_max_fee_limit = match batch_queue
.iter()
.filter(|(e, _)| e.sender == addr)
.next_back()
{
Some((last_entry, _)) => last_entry.nonced_verification_data.max_fee,
None => {
self.user_states.write().await.remove(&addr);
return Some(());
}
};
let user_state = self.user_states.read().await.get(&addr)?.clone();
let mut user_state_guard = user_state.lock().await;
user_state_guard.proofs_in_batch -= 1;
user_state_guard.nonce -= U256::one();
user_state_guard.total_fees_in_queue -= removed_entry.nonced_verification_data.max_fee;
user_state_guard.last_max_fee_limit = new_last_max_fee_limit;
Some(())
}
fn calculate_new_user_states_data(
&self,
batch_queue: &batch_queue::BatchQueue,
) -> HashMap<Address, (usize, U256, U256)> {
let mut updated_user_states = HashMap::new();
for (entry, _) in batch_queue.iter() {
let addr = entry.sender;
let max_fee = entry.nonced_verification_data.max_fee;
let (proof_count, max_fee_limit, total_fees_in_queue) = updated_user_states
.entry(addr)
.or_insert((0, max_fee, U256::zero()));
*proof_count += 1;
*total_fees_in_queue += max_fee;
if max_fee < *max_fee_limit {
*max_fee_limit = max_fee;
}
}
updated_user_states
}
/// Helper to apply 15-second timeout to user lock acquisition with consistent logging and metrics
async fn try_user_lock_with_timeout<F, T>(&self, addr: Address, lock_future: F) -> Option<T>
where
F: std::future::Future<Output = T>,
{
match timeout(MESSAGE_HANDLER_LOCK_TIMEOUT, lock_future).await {
Ok(result) => Some(result),
Err(_) => {
warn!("User lock acquisition timed out for address {}", addr);
self.metrics.inc_message_handler_user_lock_timeout();
None
}
}
}
/// Helper to apply `duration` timeout to batch lock acquisition with consistent logging and metrics
async fn try_batch_lock_with_timeout<F, T>(
&self,
lock_future: F,
duration: Duration,
) -> Option<T>
where
F: std::future::Future<Output = T>,
{
match timeout(duration, lock_future).await {
Ok(result) => Some(result),
Err(_) => {
warn!("Batch lock acquisition timed out");
self.metrics.inc_message_handler_batch_lock_timeout();
None
}
}
}
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())
}
/// Poll for BalanceUnlocked events from BatcherPaymentService contract.
/// Runs at configurable intervals and checks recent blocks for events (2x the polling interval).
/// When an event is detected, removes user's proofs from queue and resets UserState.
pub async fn poll_balance_unlocked_events(self: Arc<Self>) -> Result<(), BatcherError> {
let mut interval = tokio::time::interval(Duration::from_secs(
self.balance_unlock_polling_interval_seconds,
));
let mut from_block = self.get_current_block_number().await.map_err(|e| {
BatcherError::EthereumProviderError(format!(
"Failed to get current block number: {:?}",
e
))
})?;
loop {
interval.tick().await;
match self.process_balance_unlocked_events(from_block).await {
Ok(current_block) => {
from_block = current_block;
}
Err(e) => {
error!("Error processing BalanceUnlocked events: {:?}", e);
// On error, keep from_block unchanged to retry the same range next time
}
}
}
}
async fn process_balance_unlocked_events(&self, from_block: U64) -> Result<U64, BatcherError> {
// Get current block number using HTTP providers
let current_block = self.get_current_block_number().await.map_err(|e| {
BatcherError::EthereumProviderError(format!(
"Failed to get current block number: {:?}",
e
))
})?;
// Query events with retry logic
let events = self
.query_balance_unlocked_events(from_block, current_block)
.await
.map_err(|e| {
BatcherError::EthereumProviderError(format!(
"Failed to query BalanceUnlocked events: {:?}",
e
))
})?;
info!(
"Found {} BalanceUnlocked events in blocks {} to {}",
events.len(),
from_block,
current_block
);
// Process each event
for event in events {
let user_address = event.user;
debug!(
"Processing BalanceUnlocked event for user: {:?}",
user_address
);
// Check if user has proofs in queue
//
// Double-check that funds are still unlocked by calling the contract
// This is necessary because we query events over a block range, and the
// user’s state may have changed (e.g., funds could be locked again) after
// the event was emitted. Verifying on-chain ensures we don’t act on stale data.
//
// There is a brief period between the checks and the removal during which the user's
// proofs could be sent. This is acceptable, as the removal will not fail;
// it will simply clear the user's state.
if self.user_has_proofs_in_queue(user_address).await
&& self.user_balance_is_unlocked(&user_address).await
{
info!(
"User {:?} has proofs in queue and funds are unlocked, proceeding to remove proofs and resetting UserState",
user_address
);
self.remove_user_proofs_and_reset_state(user_address).await;
}
}
Ok(current_block)
}
/// Gets the current block number from Ethereum.
/// Retries on recoverable errors using exponential backoff up to `ETHEREUM_CALL_MAX_RETRIES` times:
/// (0,5 secs - 1 secs - 2 secs - 4 secs - 8 secs).
async fn get_current_block_number(&self) -> Result<U64, RetryError<String>> {
retry_function(
|| {
get_current_block_number_retryable(
&self.eth_http_provider,
&self.eth_http_provider_fallback,
)
},
ETHEREUM_CALL_MIN_RETRY_DELAY,
ETHEREUM_CALL_BACKOFF_FACTOR,
ETHEREUM_CALL_MAX_RETRIES,
ETHEREUM_CALL_MAX_RETRY_DELAY,
)
.await
}
/// Queries BalanceUnlocked events from the BatcherPaymentService contract.
/// Retries on recoverable errors using exponential backoff up to `ETHEREUM_CALL_MAX_RETRIES` times:
/// (0,5 secs - 1 secs - 2 secs - 4 secs - 8 secs).
async fn query_balance_unlocked_events(
&self,
from_block: U64,
to_block: U64,
) -> Result<
Vec<aligned_sdk::eth::batcher_payment_service::BalanceUnlockedFilter>,
RetryError<String>,
> {
retry_function(
|| {
query_balance_unlocked_events_retryable(
&self.payment_service,
&self.payment_service_fallback,
from_block,
to_block,
)
},
ETHEREUM_CALL_MIN_RETRY_DELAY,
ETHEREUM_CALL_BACKOFF_FACTOR,
ETHEREUM_CALL_MAX_RETRIES,
ETHEREUM_CALL_MAX_RETRY_DELAY,
)
.await
}
async fn user_has_proofs_in_queue(&self, user_address: Address) -> bool {
let user_states = self.user_states.read().await;
let Some(user_state) = user_states.get(&user_address) else {
return false;
};
let Some(user_state_guard) = self
.try_user_lock_with_timeout(user_address, user_state.lock())
.await
else {
return false;
};
user_state_guard.proofs_in_batch > 0
}
async fn remove_user_proofs_and_reset_state(&self, user_address: Address) {
let mut user_states = self.user_states.write().await;
let mut batch_state_guard = match self
.try_batch_lock_with_timeout(self.batch_state.lock(), POLLING_EVENTS_LOCK_TIMEOUT)
.await
{
Some(guard) => guard,
None => {
error!(
"Failed to acquire batch lock when trying to remove proofs from user {:?}, skipping removal",
user_address
);
self.metrics.inc_unlocked_event_polling_batch_lock_timeout();
return;
}
};
let removed_entries = batch_state_guard
.batch_queue
.extract_if(|entry, _| entry.sender == user_address);
// Notify user via websocket
for (entry, _) in removed_entries {
if let Some(ws_sink) = entry.messaging_sink {
let ws_sink_clone = ws_sink.clone();
tokio::spawn(async move {
send_message(
ws_sink_clone.clone(),
SubmitProofResponseMessage::UserFundsUnlocked,
)
.await;
// Close websocket connection
let mut sink_guard = ws_sink_clone.write().await;
if let Err(e) = sink_guard.close().await {
warn!(
"Error closing websocket for user {:?}: {:?}",
user_address, e
);
} else {
info!("Closed websocket connection for user {:?}", user_address);
}
});
}
info!(
"Removed proof with nonce {} for user {:?} from batch queue",
entry.nonced_verification_data.nonce, user_address
);
}
user_states.remove(&user_address);
info!(
"Removed UserState entry for user {:?} after processing BalanceUnlocked event",
user_address
);
}
pub async fn listen_new_blocks_retryable(
self: Arc<Self>,
) -> Result<(), RetryError<BatcherError>> {
// Try to connect at least to one of the nodes (main or fallback)
let eth_ws_provider = Provider::connect(&self.eth_ws_url).await.ok();
let eth_ws_provider_fallback = Provider::connect(&self.eth_ws_url_fallback).await.ok();
if eth_ws_provider.is_none() {
warn!("Failed to instantiate Ethereum main websocket provider");
}
if eth_ws_provider_fallback.is_none() {
warn!("Failed to instantiate fallback Ethereum websocket provider");
}
if eth_ws_provider.is_none() && eth_ws_provider_fallback.is_none() {
return Err(RetryError::Transient(
BatcherError::EthereumSubscriptionError(
"Both Ethereum websocket providers failed to connect".to_string(),
),
));
}
// Try to connect to one stream (main or fallback)
let mut stream = match ð_ws_provider {
Some(provider) => match provider.subscribe_blocks().await {
Ok(s) => Some(s),
Err(e) => {
warn!("Error subscribing to blocks on primary provider: {:?}", e);
None
}
},
None => None,
};
let mut stream_fallback = match ð_ws_provider_fallback {
Some(provider) => match provider.subscribe_blocks().await {
Ok(s) => Some(s),
Err(e) => {
warn!("Error subscribing to blocks on fallback provider: {:?}", e);
None
}
},
None => None,
};
if stream.is_none() && stream_fallback.is_none() {
return Err(RetryError::Transient(
BatcherError::EthereumSubscriptionError(
"Both Ethereum block subscriptions failed".to_string(),
),
));
}
let last_seen_block = Mutex::<u64>::new(0);
loop {
// Wait for both responses
let (block_main, block_fallback) = join!(
async {
match stream.as_mut() {
Some(s) => s.next().await,
None => None,
}
},
async {
match stream_fallback.as_mut() {
Some(s) => s.next().await,
None => None,
}
}
);
let block = if let Some(block) = block_main {
block
} else if let Some(block) = block_fallback {
block
} else {
// Both rpc failed to respond, break and try to reconnect
break;
};
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!("Both main and fallback Ethereum WS clients subscriptions have disconnected, will try to reconnect...");
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 the address is not paying, we will return the nonce of the aligned_payment_address
if !self.has_to_pay(&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 user_states_guard = match timeout(
MESSAGE_HANDLER_LOCK_TIMEOUT,
self.user_states.read(),
)
.await
{
Ok(guard) => guard,
Err(_) => {
warn!("User states read lock acquisition timed out in handle_get_nonce_for_address_msg");
self.metrics.inc_message_handler_user_states_lock_timeouts();
send_message(ws_conn_sink, GetNonceResponseMessage::ServerBusy).await;
return Ok(());
}
};
let user_state_ref = user_states_guard.get(&address).cloned();
match user_state_ref {
Some(user_state_ref) => {
let Some(user_state_guard) = self
.try_user_lock_with_timeout(address, user_state_ref.lock())
.await
else {
send_message(ws_conn_sink.clone(), GetNonceResponseMessage::ServerBusy)
.await;
return Ok(());
};
Some(user_state_guard.nonce)
}
None => None,
}
};
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()),