-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathpostgres_db_service.rs
More file actions
1860 lines (1621 loc) · 67.5 KB
/
Copy pathpostgres_db_service.rs
File metadata and controls
1860 lines (1621 loc) · 67.5 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 std::{
collections::HashSet,
ops::DerefMut,
sync::Arc,
time::{SystemTime, UNIX_EPOCH},
};
use async_trait::async_trait;
use dashmap::{DashMap, DashSet};
use deadpool_postgres::{Config, GenericClient, ManagerConfig, Pool, RecyclingMethod};
use ethereum_consensus::{altair::Hash32, primitives::BlsPublicKey, ssz::prelude::ByteVector};
use helix_common::{
api::{
builder_api::BuilderGetValidatorsResponseEntry,
data_api::{BidFilters, BidsOrderBy},
proposer_api::ValidatorRegistrationInfo,
},
bid_submission::{
v2::header_submission::SignedHeaderSubmission, BidSubmission, BidTrace, SignedBidSubmission,
},
deneb::SignedValidatorRegistration,
metrics::DbMetricRecord,
simulator::BlockSimError,
versioned_payload::PayloadAndBlobs,
BuilderInfo, Filtering, GetHeaderTrace, GetPayloadTrace, GossipedHeaderTrace,
GossipedPayloadTrace, HeaderSubmissionTrace, ProposerInfo, RelayConfig,
SignedValidatorRegistrationEntry, SubmissionTrace, ValidatorPreferences, ValidatorSummary,
};
use helix_utils::utcnow_ms;
use tokio_postgres::{types::ToSql, NoTls};
use tracing::{error, info};
use crate::{
error::DatabaseError,
postgres::{
postgres_db_filters::PgBidFilters,
postgres_db_init::run_migrations_async,
postgres_db_row_parsing::{parse_bytes_to_pubkey, parse_row, parse_rows},
postgres_db_u256_parsing::PostgresNumeric,
},
types::{BidSubmissionDocument, BuilderInfoDocument, DeliveredPayloadDocument},
DatabaseService,
};
struct RegistrationParams<'a> {
fee_recipient: &'a [u8],
gas_limit: i32,
timestamp: i64,
public_key: &'a [u8],
signature: &'a [u8],
inserted_at: SystemTime,
user_agent: Option<String>,
}
struct PreferenceParams<'a> {
public_key: &'a [u8],
filtering: i16,
trusted_builders: Option<Vec<String>>,
header_delay: bool,
gossip_blobs: bool,
}
struct TrustedProposerParams<'a> {
public_key: &'a [u8],
name: Option<String>,
}
#[derive(Clone)]
pub struct PostgresDatabaseService {
validator_registration_cache: Arc<DashMap<BlsPublicKey, SignedValidatorRegistrationEntry>>,
pending_validator_registrations: Arc<DashSet<BlsPublicKey>>,
known_validators_cache: Arc<DashSet<BlsPublicKey>>,
validator_pool_cache: Arc<DashMap<String, String>>,
region: i16,
pub pool: Arc<Pool>,
}
impl PostgresDatabaseService {
pub fn new(cfg: &Config, region: i16) -> Result<Self, Box<dyn std::error::Error>> {
let pool = cfg.create_pool(None, NoTls)?;
Ok(PostgresDatabaseService {
validator_registration_cache: Arc::new(DashMap::new()),
pending_validator_registrations: Arc::new(DashSet::new()),
known_validators_cache: Arc::new(DashSet::new()),
validator_pool_cache: Arc::new(DashMap::new()),
region,
pool: Arc::new(pool),
})
}
pub async fn from_relay_config(relay_config: &RelayConfig) -> Self {
let mut cfg = Config::new();
cfg.host = Some(relay_config.postgres.hostname.clone());
cfg.port = Some(relay_config.postgres.port);
cfg.dbname = Some(relay_config.postgres.db_name.clone());
cfg.user = Some(relay_config.postgres.user.clone());
cfg.password = Some(relay_config.postgres.password.clone());
cfg.manager = Some(ManagerConfig { recycling_method: RecyclingMethod::Fast });
let pool = loop {
match cfg.create_pool(None, NoTls) {
Ok(pool) => break pool,
Err(e) => {
error!("Error creating pool: {}", e);
tokio::time::sleep(std::time::Duration::from_secs(5)).await;
}
}
};
PostgresDatabaseService {
validator_registration_cache: Arc::new(DashMap::new()),
pending_validator_registrations: Arc::new(DashSet::new()),
known_validators_cache: Arc::new(DashSet::new()),
validator_pool_cache: Arc::new(DashMap::new()),
region: relay_config.postgres.region,
pool: Arc::new(pool),
}
}
pub async fn run_migrations(&self) -> Result<(), Box<dyn std::error::Error>> {
let mut conn = self.pool.get().await?;
let client = conn.deref_mut().deref_mut();
match run_migrations_async(client).await {
Ok(report) => {
info!("Applied migrations: {}", report.applied_migrations().len());
info!("Migrations report: {:?}", report);
Ok(())
}
Err(e) => Err(e),
}
}
pub async fn init_region(&self, config: &RelayConfig) {
let client = self.pool.get().await.unwrap();
match client
.execute(
"
INSERT INTO region (id, name)
VALUES ($1, $2)
ON CONFLICT (id)
DO NOTHING
",
&[&(config.postgres.region), &(config.postgres.region_name)],
)
.await
{
Ok(_) => {
info!("Region {} initialized", config.postgres.region);
}
Err(e) => {
panic!("Error initializing region {}: {}", config.postgres.region, e);
}
};
}
pub async fn load_known_validators(&self) {
let mut record = DbMetricRecord::new("load_known_validators");
let client = self.pool.get().await.unwrap();
let rows = client.query("SELECT * FROM known_validators", &[]).await.unwrap();
for row in rows {
let public_key: BlsPublicKey =
parse_bytes_to_pubkey(row.get::<&str, &[u8]>("public_key")).unwrap();
self.known_validators_cache.insert(public_key);
}
record.record_success();
}
pub async fn load_validator_registrations(&self) {
let mut record = DbMetricRecord::new("load_validator_registrations");
match self.get_validator_registrations().await {
Ok(entries) => {
let num_entries = entries.len();
entries.into_iter().for_each(|entry| {
self.validator_registration_cache.insert(
entry.registration_info.registration.message.public_key.clone(),
entry,
);
});
info!("Loaded {} validator registrations", num_entries);
record.record_success();
}
Err(e) => {
error!("Error loading validator registrations: {}", e);
}
}
}
pub async fn start_registration_processor(&self) {
let mut interval = tokio::time::interval(std::time::Duration::from_secs(2));
let self_clone = self.clone();
tokio::spawn(async move {
loop {
interval.tick().await;
match self_clone.pending_validator_registrations.len() {
0 => continue,
_ => {
let mut entries = Vec::new();
for key in self_clone.pending_validator_registrations.iter() {
if let Some(entry) = self_clone.validator_registration_cache.get(&*key)
{
entries.push(entry.clone());
}
}
match self_clone._save_validator_registrations(&entries).await {
Ok(_) => {
for entry in entries.iter() {
self_clone.pending_validator_registrations.remove(
&entry.registration_info.registration.message.public_key,
);
}
info!("Saved {} validator registrations", entries.len());
}
Err(e) => {
error!("Error saving validator registrations: {}", e);
}
};
}
};
}
});
}
async fn _save_validator_registrations(
&self,
entries: &[SignedValidatorRegistrationEntry],
) -> Result<(), DatabaseError> {
let mut record = DbMetricRecord::new("save_validator_registrations");
let mut client = self.pool.get().await?;
let mut sorted_entries = entries.to_vec();
sorted_entries.sort_by(|a, b| {
a.registration_info
.registration
.message
.public_key
.cmp(&b.registration_info.registration.message.public_key)
});
let batch_size = 10;
for chunk in sorted_entries.chunks(batch_size) {
let transaction = client.transaction().await?;
let mut structured_params_for_reg: Vec<RegistrationParams> =
Vec::with_capacity(chunk.len());
let mut structured_params_for_pref: Vec<PreferenceParams> =
Vec::with_capacity(chunk.len());
let mut structured_params_for_trusted: Vec<TrustedProposerParams> =
Vec::with_capacity(chunk.len());
for entry in chunk.iter() {
let registration = &entry.registration_info.registration.message;
let fee_recipient = ®istration.fee_recipient;
let public_key = ®istration.public_key;
let signature = &entry.registration_info.registration.signature;
let name = &entry.pool_name;
let inserted_at = SystemTime::now();
// Collect the parameters in a structured manner
structured_params_for_reg.push(RegistrationParams {
fee_recipient: fee_recipient.as_ref(),
gas_limit: registration.gas_limit as i32,
timestamp: registration.timestamp as i64,
public_key: public_key.as_ref(),
signature: signature.as_ref(),
inserted_at,
user_agent: entry.user_agent.clone(),
});
structured_params_for_pref.push(PreferenceParams {
public_key: public_key.as_ref(),
filtering: entry.registration_info.preferences.filtering as i16,
trusted_builders: entry.registration_info.preferences.trusted_builders.clone(),
header_delay: entry.registration_info.preferences.header_delay,
gossip_blobs: entry.registration_info.preferences.gossip_blobs,
});
if name.is_some() {
structured_params_for_trusted.push(TrustedProposerParams {
public_key: public_key.as_ref(),
name: name.clone(),
});
}
}
// Prepare the params vector from the structured parameters
let params: Vec<&(dyn ToSql + Sync)> = structured_params_for_reg
.iter()
.flat_map(|tuple| {
vec![
&tuple.fee_recipient,
&tuple.gas_limit as &(dyn ToSql + Sync),
&tuple.timestamp,
&tuple.public_key,
&tuple.signature,
&tuple.inserted_at,
&tuple.user_agent,
]
})
.collect();
// Construct the SQL statement with multiple VALUES clauses
let mut sql = String::from("INSERT INTO validator_registrations (fee_recipient, gas_limit, timestamp, public_key, signature, inserted_at, user_agent) VALUES ");
let num_params_per_row = 7;
let values_clauses: Vec<String> = (0..params.len() / num_params_per_row)
.map(|row| {
let placeholders: Vec<String> = (1..=num_params_per_row)
.map(|n| format!("${}", row * num_params_per_row + n))
.collect();
format!("({})", placeholders.join(", "))
})
.collect();
// Join the values clauses and append them to the SQL statement
sql.push_str(&values_clauses.join(", "));
sql.push_str(" ON CONFLICT (public_key) DO UPDATE SET fee_recipient = excluded.fee_recipient, gas_limit = excluded.gas_limit, timestamp = excluded.timestamp, signature = excluded.signature, inserted_at = excluded.inserted_at, user_agent = excluded.user_agent");
// Execute the query
transaction.execute(&sql, ¶ms[..]).await?;
let params: Vec<&(dyn ToSql + Sync)> = structured_params_for_pref
.iter()
.flat_map(|tuple| {
vec![
&tuple.public_key as &(dyn ToSql + Sync),
&tuple.filtering,
&tuple.trusted_builders,
&tuple.header_delay,
&tuple.gossip_blobs,
]
})
.collect();
// Construct the SQL statement with multiple VALUES clauses
let mut sql =
String::from("INSERT INTO validator_preferences (public_key, filtering, trusted_builders, header_delay, gossip_blobs) VALUES ");
let num_params_per_row = 5;
let values_clauses: Vec<String> = (0..params.len() / num_params_per_row)
.map(|row| {
let placeholders: Vec<String> = (1..=num_params_per_row)
.map(|n| format!("${}", row * num_params_per_row + n))
.collect();
format!("({})", placeholders.join(", "))
})
.collect();
// Join the values clauses and append them to the SQL statement
sql.push_str(&values_clauses.join(", "));
sql.push_str(" ON CONFLICT (public_key) DO UPDATE SET filtering = excluded.filtering, trusted_builders = excluded.trusted_builders, header_delay = excluded.header_delay, gossip_blobs = excluded.gossip_blobs");
// Execute the query
transaction.execute(&sql, ¶ms[..]).await?;
if structured_params_for_trusted.is_empty() {
transaction.commit().await?;
continue
}
let params: Vec<&(dyn ToSql + Sync)> = structured_params_for_trusted
.iter()
.flat_map(|tuple| vec![&tuple.public_key as &(dyn ToSql + Sync), &tuple.name])
.collect();
// Construct the SQL statement with multiple VALUES clauses
let mut sql = String::from("INSERT INTO trusted_proposers (pub_key, name) VALUES ");
let num_params_per_row = 2;
let values_clauses: Vec<String> = (0..params.len() / num_params_per_row)
.map(|row| {
let placeholders: Vec<String> = (1..=num_params_per_row)
.map(|n| format!("${}", row * num_params_per_row + n))
.collect();
format!("({})", placeholders.join(", "))
})
.collect();
// Join the values clauses and append them to the SQL statement
sql.push_str(&values_clauses.join(", "));
sql.push_str(" ON CONFLICT (pub_key) DO NOTHING");
// Execute the query
transaction.execute(&sql, ¶ms[..]).await?;
transaction.commit().await?;
}
record.record_success();
Ok(())
}
}
impl Default for PostgresDatabaseService {
fn default() -> Self {
let mut cfg = Config::new();
cfg.host = Some("localhost".to_string());
cfg.port = Some(5432);
cfg.dbname = Some("postgres".to_string());
cfg.user = Some("postgres".to_string());
cfg.password = Some("password".to_string());
cfg.manager = Some(ManagerConfig { recycling_method: RecyclingMethod::Fast });
let pool = cfg.create_pool(None, NoTls).unwrap();
PostgresDatabaseService {
validator_registration_cache: Arc::new(DashMap::new()),
pending_validator_registrations: Arc::new(DashSet::new()),
known_validators_cache: Arc::new(DashSet::new()),
validator_pool_cache: Arc::new(DashMap::new()),
region: 1,
pool: Arc::new(pool),
}
}
}
#[async_trait]
impl DatabaseService for PostgresDatabaseService {
async fn save_validator_registration(
&self,
registration_info: ValidatorRegistrationInfo,
pool_name: Option<String>,
user_agent: Option<String>,
) -> Result<(), DatabaseError> {
let mut record = DbMetricRecord::new("save_validator_registration");
let registration = registration_info.registration.message.clone();
if let Some(entry) = self.validator_registration_cache.get(®istration.public_key) {
if entry.registration_info.registration.message.timestamp >= registration.timestamp {
return Ok(())
}
}
let fee_recipient = ®istration.fee_recipient;
let public_key = ®istration.public_key;
let signature = ®istration_info.registration.signature;
let mut client = self.pool.get().await?;
let transaction = client.transaction().await?;
let inserted_at = SystemTime::now();
transaction
.execute(
"INSERT INTO validator_preferences (public_key, filtering, trusted_builders, header_delay, gossip_blobs)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (public_key)
DO UPDATE SET
filtering = excluded.filtering, trusted_builders = excluded.trusted_builders, header_delay = excluded.header_delay, gossip_blobs = excluded.gossip_blobs
",
&[
&public_key.as_ref(),
&(registration_info.preferences.filtering as i16),
®istration_info.preferences.trusted_builders,
®istration_info.preferences.header_delay,
®istration_info.preferences.gossip_blobs,
],
)
.await?;
match transaction.execute(
"
INSERT INTO validator_registrations (fee_recipient, gas_limit, timestamp, public_key, signature, inserted_at, user_agent)
VALUES ($1, $2, $3, $4, $5,$6,$7)
ON CONFLICT (public_key)
DO UPDATE SET
fee_recipient = excluded.fee_recipient,
gas_limit = excluded.gas_limit,
timestamp = excluded.timestamp,
signature = excluded.signature,
inserted_at = excluded.inserted_at,
user_agent = excluded.user_agent
",
&[
&(fee_recipient.as_ref()),
&(registration.gas_limit as i32),
&(registration.timestamp as i64),
&(public_key.as_ref()),
&(signature.as_ref()),
&(inserted_at),
&(user_agent)
],
).await {
Ok(_) => {
self.validator_registration_cache.insert(public_key.clone(), SignedValidatorRegistrationEntry {
registration_info,
inserted_at: inserted_at.duration_since(UNIX_EPOCH).unwrap().as_millis() as u64,
pool_name,
user_agent,
});
}
Err(e) => {
return Err(DatabaseError::from(e))
},
};
transaction.commit().await?;
record.record_success();
Ok(())
}
async fn save_validator_registrations(
&self,
mut entries: Vec<ValidatorRegistrationInfo>,
pool_name: Option<String>,
user_agent: Option<String>,
) -> Result<(), DatabaseError> {
let mut record = DbMetricRecord::new("save_validator_registrations");
entries.retain(|entry| {
if let Some(existing_entry) =
self.validator_registration_cache.get(&entry.registration.message.public_key)
{
if existing_entry.registration_info.registration.message.timestamp >=
entry.registration.message.timestamp
{
return false
}
}
true
});
for entry in entries.iter() {
self.pending_validator_registrations
.insert(entry.registration.message.public_key.clone());
self.validator_registration_cache.insert(
entry.registration.message.public_key.clone(),
SignedValidatorRegistrationEntry::new(
entry.clone(),
pool_name.clone(),
user_agent.clone(),
),
);
}
record.record_success();
Ok(())
}
async fn update_trusted_builders(
&self,
validator_keys: &[BlsPublicKey],
trusted_builders: &[String],
) -> Result<(), DatabaseError> {
let mut record = DbMetricRecord::new("update_trusted_builders");
let client = self.pool.get().await?;
client
.execute(
"UPDATE validator_preferences SET trusted_builders = $1 WHERE public_key = ANY($2)",
&[
&trusted_builders,
&validator_keys.iter().map(|key| key.as_ref()).collect::<Vec<&[u8]>>(),
],
)
.await?;
record.record_success();
Ok(())
}
async fn is_registration_update_required(
&self,
registration: &SignedValidatorRegistration,
) -> Result<bool, DatabaseError> {
if let Some(existing_entry) =
self.validator_registration_cache.get(®istration.message.public_key)
{
if existing_entry.registration_info.registration.message.timestamp >=
registration.message.timestamp
{
return Ok(false)
}
}
Ok(true)
}
async fn get_validator_registration(
&self,
pub_key: BlsPublicKey,
) -> Result<SignedValidatorRegistrationEntry, DatabaseError> {
let mut record = DbMetricRecord::new("get_validator_registration");
match self
.pool
.get()
.await?
.query(
"
SELECT
validator_registrations.fee_recipient,
validator_registrations.gas_limit,
validator_registrations.timestamp,
validator_registrations.public_key,
validator_registrations.signature,
validator_preferences.filtering,
validator_preferences.trusted_builders,
validator_preferences.header_delay,
validator_preferences.gossip_blobs,
validator_registrations.inserted_at,
validator_registrations.user_agent
FROM validator_registrations
INNER JOIN validator_preferences ON validator_registrations.public_key = validator_preferences.public_key
WHERE validator_registrations.public_key = $1
",
&[&(pub_key.as_ref())],
)
.await?
{
rows if rows.is_empty() => Err(DatabaseError::ValidatorRegistrationNotFound),
rows => {
record.record_success();
parse_row(rows.first().unwrap())
},
}
}
async fn get_validator_registrations(
&self,
) -> Result<Vec<SignedValidatorRegistrationEntry>, DatabaseError> {
let mut record = DbMetricRecord::new("get_validator_registrations");
let rows = self
.pool
.get()
.await?
.query(
"
SELECT * FROM validator_registrations
INNER JOIN validator_preferences
ON validator_registrations.public_key = validator_preferences.public_key
",
&[],
)
.await?;
record.record_success();
parse_rows(rows)
}
async fn get_validator_registrations_for_pub_keys(
&self,
pub_keys: Vec<BlsPublicKey>,
) -> Result<Vec<SignedValidatorRegistrationEntry>, DatabaseError> {
let mut record = DbMetricRecord::new("get_validator_registrations_for_pub_keys");
let client = self.pool.get().await.map_err(DatabaseError::from)?;
// Constructing the query
let placeholders: Vec<String> = (1..=pub_keys.len()).map(|i| format!("${}", i)).collect();
let query = format!(
"SELECT *
FROM validator_registrations
INNER JOIN validator_preferences ON validator_registrations.public_key = validator_preferences.public_key
WHERE validator_preferences.public_key IN ({})",
placeholders.join(", ")
);
// Preparing the query
let stmt = client.prepare(&query).await.map_err(DatabaseError::from)?;
let params: Vec<Box<dyn ToSql + Sync + Send>> = pub_keys
.iter()
.map(|key: &BlsPublicKey| Box::new(key.as_ref()) as Box<dyn ToSql + Sync + Send>)
.collect();
let params_slice: Vec<&(dyn ToSql + Sync)> =
params.iter().map(|b| b.as_ref() as &(dyn ToSql + Sync)).collect();
let rows = client.query(&stmt, ¶ms_slice).await.map_err(DatabaseError::from)?;
record.record_success();
parse_rows(rows)
}
async fn get_validator_registration_timestamp(
&self,
pub_key: BlsPublicKey,
) -> Result<u64, DatabaseError> {
self.get_validator_registration(pub_key).await.map(|entry| entry.inserted_at)
}
async fn set_proposer_duties(
&self,
proposer_duties: Vec<BuilderGetValidatorsResponseEntry>,
) -> Result<(), DatabaseError> {
let mut record = DbMetricRecord::new("set_proposer_duties");
let mut client = self.pool.get().await?;
let transaction = client.transaction().await?;
transaction
.execute(
"
INSERT INTO proposer_duties_archive SELECT * FROM proposer_duties order by slot_number ON CONFLICT (slot_number) DO UPDATE SET public_key = excluded.public_key, validator_index = excluded.validator_index;
",
&[],
)
.await?;
transaction
.execute(
"
DELETE FROM proposer_duties;
",
&[],
)
.await?;
let mut structured_params: Vec<(i32, i32, &[u8])> =
Vec::with_capacity(proposer_duties.len());
for entry in proposer_duties.iter() {
structured_params.push((
entry.slot as i32,
entry.validator_index as i32,
entry.entry.registration.message.public_key.as_ref(),
));
}
// Prepare the params vector from the structured parameters
let params: Vec<&(dyn ToSql + Sync)> = structured_params
.iter()
.flat_map(|tuple| vec![&tuple.0, &tuple.1, &tuple.2 as &(dyn ToSql + Sync)])
.collect();
// Construct the SQL statement with multiple VALUES clauses
let mut sql = String::from(
"INSERT INTO proposer_duties (slot_number, validator_index, public_key) VALUES ",
);
let num_params_per_row = 3;
let values_clauses: Vec<String> = (0..params.len() / num_params_per_row)
.map(|row| {
let placeholders: Vec<String> = (1..=num_params_per_row)
.map(|n| format!("${}", row * num_params_per_row + n))
.collect();
format!("({})", placeholders.join(", "))
})
.collect();
// Join the values clauses and append them to the SQL statement
sql.push_str(&values_clauses.join(", "));
sql.push_str(" ON CONFLICT (slot_number) DO NOTHING");
// Execute the query
transaction.execute(&sql, ¶ms[..]).await?;
transaction.commit().await?;
record.record_success();
Ok(())
}
async fn get_proposer_duties(
&self,
) -> Result<Vec<BuilderGetValidatorsResponseEntry>, DatabaseError> {
let mut record = DbMetricRecord::new("get_proposer_duties");
let rows = self
.pool
.get()
.await?
.query(
"
SELECT * FROM proposer_duties
INNER JOIN validator_registrations
ON proposer_duties.public_key = validator_registrations.public_key
INNER JOIN validator_preferences
ON proposer_duties.public_key = validator_preferences.public_key
",
&[],
)
.await?;
record.record_success();
parse_rows(rows)
}
async fn set_known_validators(
&self,
known_validators: Vec<ValidatorSummary>,
) -> Result<(), DatabaseError> {
let mut record = DbMetricRecord::new("set_known_validators");
info!("Known validators: current cache size: {:?}", self.known_validators_cache.len());
let mut client = self.pool.get().await?;
let new_keys_set: HashSet<BlsPublicKey> = known_validators
.iter()
.map(|validator| validator.validator.public_key.clone())
.collect();
let old_keys_hash_set: HashSet<BlsPublicKey> = self
.known_validators_cache
.iter()
.map(|ref_multi| ref_multi.key().clone()) // Access and clone the key from RefMulti
.collect();
let keys_to_add: Vec<BlsPublicKey> =
new_keys_set.difference(&old_keys_hash_set).cloned().collect();
let keys_to_remove: Vec<BlsPublicKey> =
old_keys_hash_set.difference(&new_keys_set).cloned().collect();
for key in &keys_to_add {
self.known_validators_cache.insert(key.clone());
}
for key in &keys_to_remove {
self.known_validators_cache.remove(key);
}
info!("Known validators: added: {:?}", keys_to_add.len());
info!("Known validators: removed: {:?}", keys_to_add.len());
info!("Known validators: updated cache size: {:?}", self.known_validators_cache.len());
let transaction = client.transaction().await?;
// Perform batch deletion
for chunk in keys_to_remove.chunks(10000) {
let sql = "DELETE FROM known_validators WHERE public_key = ANY($1::bytea[])";
let byte_keys: Vec<&[u8]> = chunk.iter().map(|k| k.as_ref()).collect();
transaction.execute(sql, &[&byte_keys]).await?;
}
// Perform batch insertion
for chunk in keys_to_add.chunks(10000) {
let mut sql = String::from("INSERT INTO known_validators (public_key) VALUES ");
let values_clauses: Vec<String> =
(1..=chunk.len()).map(|i| format!("(${})", i)).collect();
sql.push_str(&values_clauses.join(", "));
sql.push_str(" ON CONFLICT (public_key) DO NOTHING");
let mut structured_params: Vec<&[u8]> = Vec::new();
for validator in chunk.iter() {
structured_params.push(validator.as_ref());
}
let params: Vec<&(dyn ToSql + Sync)> =
structured_params.iter().flat_map(|v| vec![v as &(dyn ToSql + Sync)]).collect();
transaction.execute(&sql, ¶ms[..]).await?;
}
transaction.commit().await?;
record.record_success();
Ok(())
}
async fn check_known_validators(
&self,
public_keys: Vec<BlsPublicKey>,
) -> Result<HashSet<BlsPublicKey>, DatabaseError> {
let mut record = DbMetricRecord::new("check_known_validators");
let client = self.pool.get().await?;
let mut pub_keys = HashSet::new();
for public_key in public_keys.iter() {
if self.known_validators_cache.contains(public_key) {
pub_keys.insert(public_key.clone());
} else {
let rows = client
.query(
"SELECT * FROM known_validators WHERE public_key = $1",
&[&(public_key.as_ref())],
)
.await?;
for row in rows {
let public_key: BlsPublicKey =
parse_bytes_to_pubkey(row.get::<&str, &[u8]>("public_key"))?;
self.known_validators_cache.insert(public_key.clone());
pub_keys.insert(public_key);
}
}
}
record.record_success();
Ok(pub_keys)
}
async fn get_validator_pool_name(
&self,
api_key: &str,
) -> Result<Option<String>, DatabaseError> {
let mut record = DbMetricRecord::new("get_validator_pool_name");
let client = self.pool.get().await?;
if self.validator_pool_cache.is_empty() {
let rows = client.query("SELECT * FROM validator_pools", &[]).await?;
for row in rows {
let api_key: String = row.get::<&str, &str>("api_key").to_string();
let name: String = row.get::<&str, &str>("name").to_string();
self.validator_pool_cache.insert(api_key, name);
}
}
if self.validator_pool_cache.contains_key(api_key) {
return Ok(self.validator_pool_cache.get(api_key).map(|f| f.clone()))
}
let api_key = api_key.to_string();
let rows = match client
.query("SELECT * FROM validator_pools WHERE api_key = $1", &[&api_key])
.await
{
Ok(rows) => rows,
Err(e) => {
error!("Error querying validator_pools: {}", e);
return Err(DatabaseError::from(e))
}
};
if rows.is_empty() {
return Ok(None)
}
let name: String = rows[0].get("name");
self.validator_pool_cache.insert(api_key.to_string(), name.clone());
record.record_success();
Ok(Some(name))
}
async fn save_too_late_get_payload(
&self,
slot: u64,
proposer_pub_key: &BlsPublicKey,
payload_hash: &Hash32,
message_received: u64,
payload_fetched: u64,
) -> Result<(), DatabaseError> {
let mut record = DbMetricRecord::new("save_too_late_get_payload");
let region_id = self.region;
self.pool
.get()
.await?
.execute(
"
INSERT INTO late_payload
(block_hash, slot_number, region_id, proposer_pubkey, message_received, payload_fetched)
VALUES
($1, $2, $3, $4, $5, $6)
",
&[
&(payload_hash.as_ref()),
&(slot as i32),
&(region_id),
&(proposer_pub_key.as_ref()),
&(message_received as i64),
&(payload_fetched as i64),
],
)
.await?;
record.record_success();
Ok(())
}
async fn save_delivered_payload(
&self,
bid_trace: &BidTrace,
payload: Arc<PayloadAndBlobs>,
latency_trace: &GetPayloadTrace,
user_agent: Option<String>,
) -> Result<(), DatabaseError> {
let mut record = DbMetricRecord::new("save_delivered_payload");
let region_id = self.region;
let mut client = self.pool.get().await?;
let transaction = client.transaction().await?;
transaction.execute(
"
INSERT INTO delivered_payload
(block_hash, payload_parent_hash, fee_recipient, state_root, receipts_root, logs_bloom, prev_randao, timestamp, block_number, gas_limit, gas_used, extra_data, base_fee_per_gas, user_agent)
VALUES
($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
ON CONFLICT (block_hash)
DO NOTHING
",
&[
&(bid_trace.block_hash.as_ref()),
&(payload.execution_payload.parent_hash().as_ref()),
&(payload.execution_payload.fee_recipient().as_ref()),
&(payload.execution_payload.state_root().as_ref()),
&(payload.execution_payload.receipts_root().as_ref()),
&(payload.execution_payload.logs_bloom().as_ref()),
&(payload.execution_payload.prev_randao().as_ref()),
&(payload.execution_payload.timestamp() as i64),