-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathconfig.rs
More file actions
807 lines (717 loc) · 25.6 KB
/
Copy pathconfig.rs
File metadata and controls
807 lines (717 loc) · 25.6 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
use std::{
collections::{HashMap, HashSet},
env,
fs::File,
path::PathBuf,
};
use alloy_primitives::Address;
use clap::Parser;
use eyre::ensure;
use helix_types::{BlsKeypair, BlsPublicKey, BlsPublicKeyBytes, BlsSecretKey};
use reqwest::Url;
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use teloxide::types::ChatId;
use tracing::error;
use crate::{BuilderInfo, ValidatorPreferences, api::*};
static mut LOCAL_DEV: bool = false;
pub fn is_local_dev() -> bool {
unsafe { LOCAL_DEV }
}
#[derive(Serialize, Deserialize, Clone)]
pub struct RelayConfig {
pub instance_id: Option<String>,
#[serde(default)]
pub website: WebsiteConfig,
pub postgres: PostgresConfig,
pub simulators: Vec<SimulatorConfig>,
#[serde(default)]
pub beacon_clients: Vec<BeaconClientConfig>,
#[serde(default)]
pub relays: Vec<RelayGossipConfig>,
#[serde(default)]
pub relay_network: RelayNetworkConfig,
#[serde(default)]
pub builders: Vec<BuilderConfig>,
#[serde(default)]
pub logging: LoggingConfig,
#[serde(default)]
pub validator_preferences: ValidatorPreferences,
#[serde(default)]
pub router_config: RouterConfig,
#[serde(default = "default_duration")]
pub target_get_payload_propagation_duration_ms: u64,
/// Configuration for block merging parameters.
#[serde(default)]
pub block_merging_config: BlockMergingConfig,
/// Configuration for the websocket header stream.
#[serde(default)]
pub header_stream: HeaderStreamConfig,
pub primev_config: Option<PrimevConfig>,
pub discord_webhook_url: Option<Url>,
pub alerts_config: Option<AlertsConfig>,
pub inclusion_list: Option<InclusionListConfig>,
pub is_submission_instance: bool,
pub is_registration_instance: bool,
#[serde(default)]
is_local_dev: bool,
/// Cores configuration, recommended to be set for production use
pub cores: CoresConfig,
#[serde(default = "default_bool::<true>")]
pub gossip_payload_on_header: bool,
#[serde(default = "default_u16::<4040>")]
pub api_port: u16,
#[serde(default = "default_u16::<4041>")]
pub tcp_port: u16,
#[serde(default = "default_usize::<512>")]
pub tcp_max_connections: usize,
pub s3_config: Option<S3Config>,
/// Directory for local cache snapshots (bincode). Enables fast startup.
pub snapshot_dir: Option<PathBuf>,
pub clickhouse: Option<ClickhouseConfig>,
#[serde(default)]
pub enable_flux_profiler: bool,
}
#[derive(Serialize, Deserialize, Clone)]
pub struct ClickhouseConfig {
pub url: String,
pub database: String,
pub user: String,
}
impl RelayConfig {
pub fn empty_for_test() -> Self {
Self {
instance_id: Default::default(),
website: Default::default(),
postgres: Default::default(),
simulators: Default::default(),
beacon_clients: Default::default(),
relays: Default::default(),
relay_network: Default::default(),
builders: Default::default(),
logging: Default::default(),
validator_preferences: Default::default(),
router_config: Default::default(),
target_get_payload_propagation_duration_ms: Default::default(),
block_merging_config: Default::default(),
header_stream: Default::default(),
primev_config: Default::default(),
discord_webhook_url: Default::default(),
alerts_config: Default::default(),
inclusion_list: Default::default(),
is_submission_instance: Default::default(),
is_registration_instance: Default::default(),
is_local_dev: Default::default(),
cores: CoresConfig {
auctioneer: 1,
tokio: vec![],
reg_workers: vec![],
tcp_bid_submissions_tile: 2,
decoder: vec![4],
simulator: 5,
top_bid: 1,
data_gatherer: 3,
block_merging: 0,
housekeeper: None,
},
gossip_payload_on_header: false,
api_port: 4040,
tcp_port: 4041,
tcp_max_connections: 512,
s3_config: None,
snapshot_dir: None,
clickhouse: None,
enable_flux_profiler: false,
}
}
}
impl AsRef<RelayConfig> for RelayConfig {
fn as_ref(&self) -> &RelayConfig {
self
}
}
#[derive(Serialize, Deserialize, Clone)]
pub struct WebsiteConfig {
#[serde(default)]
pub enabled: bool,
#[serde(default)]
pub port: u16,
#[serde(default)]
pub listen_address: String,
#[serde(default)]
pub show_config_details: bool,
#[serde(default)]
pub network_name: String,
#[serde(default)]
pub relay_url: String,
#[serde(default)]
pub relay_pubkey: String,
#[serde(default)]
pub link_beaconchain: String,
#[serde(default)]
pub link_etherscan: String,
#[serde(default)]
pub link_data_api: String,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct CoresConfig {
pub auctioneer: usize,
pub tokio: Vec<usize>,
/// Registrations
pub reg_workers: Vec<usize>,
pub tcp_bid_submissions_tile: usize,
pub decoder: Vec<usize>,
#[serde(default)]
pub simulator: usize,
#[serde(default)]
pub top_bid: usize,
#[serde(default)]
pub data_gatherer: usize,
#[serde(default)]
pub block_merging: usize,
pub housekeeper: Option<usize>,
}
impl Default for WebsiteConfig {
fn default() -> Self {
Self {
enabled: false,
port: 8080,
listen_address: "0.0.0.0".to_string(),
show_config_details: false,
network_name: String::new(),
relay_url: String::new(),
relay_pubkey: String::new(),
link_beaconchain: String::new(),
link_etherscan: String::new(),
link_data_api: String::new(),
}
}
}
pub fn load_config<R: AsRef<RelayConfig> + DeserializeOwned>() -> R {
let start_config = StartConfig::parse();
let file = File::open(&start_config.config)
.unwrap_or_else(|_| panic!("unable to find config file: '{}'", start_config.config));
let config: R = serde_yaml::from_reader(file).expect("failed to parse config file");
unsafe {
LOCAL_DEV = config.as_ref().is_local_dev;
}
config
}
pub fn expect_env_var(env_var: &str) -> String {
env::var(env_var).expect(&format!("{} should be set", env_var))
}
pub fn load_keypair() -> BlsKeypair {
let signing_key_str = expect_env_var("RELAY_KEY");
let signing_key_bytes =
alloy_primitives::hex::decode(signing_key_str).expect("invalid RELAY_KEY bytes");
let signing_key = BlsSecretKey::deserialize(signing_key_bytes.as_slice())
.expect("could not convert env signing key to SecretKey");
let public_key = signing_key.public_key();
BlsKeypair::from_components(public_key, signing_key)
}
#[derive(Serialize, Deserialize, Clone, Default)]
pub struct PostgresConfig {
pub hostname: String,
#[serde(default = "default_u16::<5432>")]
pub port: u16,
pub db_name: String,
pub user: String,
pub region: i16,
pub region_name: String,
/// Overrides deadpool's default pool size (`physical_cpu_count * 4`) for both the
/// normal and high-priority pools. Without this, pool size scales with the host's
/// core count, which can let a single instance consume a large share of Postgres's
/// `max_connections` on beefier machines.
#[serde(default)]
pub pool_size: Option<usize>,
}
#[derive(Serialize, Deserialize, Clone, Default)]
pub struct BlockMergingConfig {
/// Flag to enable this feature.
#[serde(default = "default_bool::<false>")]
pub is_enabled: bool,
/// Maximum age of a merged bid before it is considered stale and discarded.
#[serde(default = "default_u64::<250>")]
pub max_merged_bid_age_ms: u64,
/// Flag to allow dry run mode.
#[serde(default = "default_bool::<false>")]
pub is_dry_run: bool,
/// Builder-side merging over TCP. Tile is only spawned if set.
#[serde(default)]
pub tcp: Option<BlockMergingTcpConfig>,
}
/// Mirrors `RelayConfigV1` fields; kept local so helix-common does not depend
/// on helix-tcp-types.
#[derive(Serialize, Deserialize, Clone)]
pub struct BlockMergingTcpConfig {
/// The single merging builder this relay dials.
pub builder: MergingBuilderEndpoint,
pub relay_fee_recipient: Address,
pub multisend_contract: Address,
pub relay_bps: u64,
pub merged_builder_bps: u64,
pub winning_builder_bps: u64,
#[serde(default = "default_u64::<140_000>")]
pub distribution_gas_limit: u64,
pub builder_collaterals: Vec<MergingBuilderCollateral>,
}
#[derive(Serialize, Deserialize, Clone)]
pub struct MergingBuilderEndpoint {
pub addr: std::net::SocketAddr,
/// UUID api key, validated by the builder on registration.
pub api_key: String,
}
#[derive(Serialize, Deserialize, Clone)]
pub struct MergingBuilderCollateral {
pub builder_coinbase: Address,
pub collateral_safe: Address,
}
pub const fn default_u16<const U: u16>() -> u16 {
U
}
pub const fn default_bool<const B: bool>() -> bool {
B
}
pub const fn default_usize<const U: usize>() -> usize {
U
}
pub const fn default_u64<const D: u64>() -> u64 {
D
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct AlertsConfig {
pub telegram_bot_token: String,
#[serde(default)]
pub merged_blocks_chat_ids: Vec<ChatId>,
/// Shared demotion channel, receives all demotions.
#[serde(default)]
pub demotion_chat_id: Option<ChatId>,
/// Extra demotion channel per builder, keyed by builder_id.
#[serde(default)]
pub builder_demotion_chat_ids: HashMap<String, ChatId>,
pub relay_url: String,
}
#[derive(Serialize, Deserialize, Clone, Default)]
pub struct SimulatorConfig {
pub url: String,
#[serde(default = "default_namespace")]
pub namespace: String,
/// roughly number of cores on simulator
#[serde(default = "default_usize::<32>")]
pub max_concurrent_tasks: usize,
/// If set, use the SSZ binary endpoint at this URL instead of JSON-RPC
pub ssz_url: Option<String>,
}
fn default_namespace() -> String {
"flashbots".to_string()
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct BeaconClientConfig {
pub url: Url,
}
#[derive(Serialize, Deserialize, Clone)]
pub struct RelayGossipConfig {
pub url: String,
}
#[derive(Default, Serialize, Deserialize, Clone)]
pub struct RelayNetworkConfig {
/// Whether functionality is enabled or not
#[serde(default = "default_bool::<false>")]
pub is_enabled: bool,
/// Information on known peers
#[serde(default)]
pub peers: Vec<RelayNetworkPeerConfig>,
/// Duration until the first cutoff point on the slot (t_1),
/// when we compute an inclusion list based on the ones
/// broadcasted by our peers and broadcast it to them.
/// Should be lower than [`Self::cutoff_2_ms`]
///
/// See the network's IL module documentation for more details.
#[serde(default = "default_u64::<2000>")]
pub cutoff_1_ms: u64,
/// Duration until the second cutoff point in the slot (t_2),
/// when we compute the final inclusion list for the slot.
/// Should be higher than [`Self::cutoff_1_ms`]
///
/// See the network's IL module documentation for more details.
#[serde(default = "default_u64::<4000>")]
pub cutoff_2_ms: u64,
}
impl RelayNetworkConfig {
/// Validates config is sane
pub fn validate(&self) {
let mut peer_pubkeys = HashSet::with_capacity(self.peers.len());
for peer in &self.peers {
peer.validate();
let pubkey = peer.pubkey;
assert!(!peer_pubkeys.contains(&pubkey), "duplicate peer pubkey found: {pubkey}");
peer_pubkeys.insert(pubkey);
}
assert!(self.cutoff_1_ms < self.cutoff_2_ms, "cutoff_1_ms must be less than cutoff_2_ms");
}
}
#[derive(Serialize, Deserialize, Clone)]
pub struct RelayNetworkPeerConfig {
/// The URL of the peer.
/// A valid URL is of the form 'ws://<peer-url>'
pub url: Option<Url>,
/// The BLS public key of the peer, to verify its identity.
pub pubkey: BlsPublicKeyBytes,
}
impl RelayNetworkPeerConfig {
fn validate(&self) {
// Verify serialized public key is valid
let _deserialized_pubkey = BlsPublicKey::deserialize(self.pubkey.as_ref())
.inspect_err(
|e| error!(err=?e, pubkey=%self.pubkey, "failed to deserialize peer pubkey"),
)
.expect("pubkey should be valid");
if let Some(url) = &self.url {
let has_ws_scheme = ["ws", "wss"].contains(&url.scheme());
let has_port = url.port().is_some();
assert!(
has_ws_scheme || has_port,
"peer URL must have ws/wss scheme or a specific port"
);
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct BuilderConfig {
pub pub_key: BlsPublicKeyBytes,
pub builder_info: BuilderInfo,
}
#[derive(Serialize, Deserialize, Clone, Default)]
pub struct PrimevConfig {
pub builder_url: String,
pub builder_contract: String,
pub validator_url: String,
pub validator_contract: String,
}
#[derive(Default, Serialize, Deserialize, Clone)]
#[serde(tag = "type")]
pub enum LoggingConfig {
#[default]
Console,
File {
dir_path: PathBuf,
file_name: String,
/// OpenTelemetry server URL
otlp_server: Option<Url>,
},
}
// FIXME
impl LoggingConfig {
pub fn dir_path(&self) -> Option<PathBuf> {
match self {
LoggingConfig::Console => None,
LoggingConfig::File { dir_path, .. } => Some(dir_path.clone()),
}
}
}
#[derive(Parser, Debug, Clone, Default, Serialize, Deserialize)]
#[clap(name = "basic")]
pub struct StartConfig {
#[clap(long, default_value = "config.yml")]
pub config: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct RouterConfig {
#[serde(default)]
pub enabled_routes: Vec<RouteInfo>,
/// On receipt of a shutdown signal, milliseconds to wait after shutting down health endpoint
/// and before terminating.
#[serde(default = "default_u64::<12_000>")]
pub shutdown_delay_ms: u64,
}
impl RouterConfig {
// Function to resolve condensed variants and replace them with real routes
pub fn resolve_condensed_routes(&mut self) {
if self.enabled_routes.is_empty() {
// If no routes are enabled, enable all real routes
self.extend([Route::BuilderApi, Route::ProposerApi, Route::DataApi]);
} else if self.contains(Route::All) {
// If All is present, replace it with all real routes
self.remove(&Route::All);
self.extend([Route::BuilderApi, Route::ProposerApi, Route::DataApi]);
}
// Replace BuilderApi, ProposerApi, DataApi with their real routes
self.replace_condensed_with_real(Route::BuilderApi, &[
Route::GetValidators,
Route::SubmitBlock,
Route::GetTopBid,
Route::GetTopBidV2,
Route::GetInclusionList,
Route::PromoteBuilder,
]);
self.replace_condensed_with_real(Route::ProposerApi, &[
Route::Status,
Route::RegisterValidators,
Route::GetHeader,
Route::HeaderStream,
Route::GetPayload,
Route::GetPayloadV2,
]);
self.replace_condensed_with_real(Route::DataApi, &[
Route::ProposerPayloadDelivered,
Route::ProposerHeaderDelivered,
Route::BuilderBidsReceived,
Route::ValidatorRegistration,
Route::DataAdjustments,
Route::MergedBlocks,
]);
}
pub fn enable_relay_network(&mut self) {
self.extend([Route::RelayNetwork]);
}
fn contains(&self, route: Route) -> bool {
self.enabled_routes.iter().map(|x| x.route).collect::<HashSet<_>>().contains(&route)
}
fn remove(&mut self, route: &Route) {
self.enabled_routes.retain(|x| x.route != *route);
}
fn extend(&mut self, routes: impl IntoIterator<Item = Route>) {
for route in routes {
if !self.contains(route) {
self.enabled_routes.push(RouteInfo { route, rate_limit: None });
}
}
}
fn replace_condensed_with_real(&mut self, special_variant: Route, real_routes: &[Route]) {
if self.contains(special_variant) {
self.remove(&special_variant);
self.extend(real_routes.iter().cloned());
}
}
/// Validate routes, returns true if the bid sorter should be started
pub fn validate_bid_sorter(&self) -> eyre::Result<bool> {
let routes = self.enabled_routes.iter().map(|r| r.route).collect::<Vec<_>>();
if routes.contains(&Route::All) {
return Ok(true);
}
let is_get_header_instance = routes.contains(&Route::ProposerApi) ||
routes.contains(&Route::GetHeader) ||
routes.contains(&Route::HeaderStream);
let is_submission_instance =
routes.contains(&Route::BuilderApi) || routes.contains(&Route::SubmitBlock);
if is_get_header_instance {
ensure!(
is_submission_instance,
"relay is serving headers so should have submissions enabled"
);
ensure!(
routes.contains(&Route::BuilderApi) || routes.contains(&Route::GetTopBid),
"routes should have get_top_bid enabled"
);
Ok(true)
} else if is_submission_instance {
ensure!(
is_get_header_instance,
"relay is receiving blocks so should have get_header enabled"
);
ensure!(
routes.contains(&Route::BuilderApi) || routes.contains(&Route::GetTopBid),
"routes should have get_top_bid enabled"
);
Ok(true)
} else {
Ok(false)
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RouteInfo {
pub route: Route,
pub rate_limit: Option<RateLimitInfo>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RateLimitInfo {
// Interval after which one element of the quota is replenished in milliseconds
pub replenish_ms: u64,
// The quota size that defines how many requests can occur before being rate limited and
// clients have to wait until the elements of the quota are replenished
pub burst_size: u32,
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub enum Route {
All,
BuilderApi,
ProposerApi,
DataApi,
GetValidators,
SubmitBlock,
GetTopBid,
GetTopBidV2,
Status,
RegisterValidators,
GetHeader,
HeaderStream,
GetPayload,
GetPayloadV2,
ProposerPayloadDelivered,
ProposerPayloadDeliveredV2,
ProposerHeaderDelivered,
BuilderBidsReceived,
BuilderBidsReceivedV2,
ValidatorRegistration,
GetInclusionList,
RelayNetwork,
DataAdjustments,
MergedBlocks,
PromoteBuilder,
}
impl Route {
pub fn path(&self) -> String {
match self {
Route::GetValidators => format!("{PATH_BUILDER_API}{PATH_GET_VALIDATORS}"),
Route::SubmitBlock => format!("{PATH_BUILDER_API}{PATH_SUBMIT_BLOCK}"),
Route::GetTopBid => format!("{PATH_BUILDER_API}{PATH_GET_TOP_BID}"),
Route::GetTopBidV2 => format!("{PATH_BUILDER_API_V2}{PATH_GET_TOP_BID}"),
Route::PromoteBuilder => format!("{PATH_BUILDER_API_V2}{PATH_PROMOTE_BUILDER}"),
Route::GetInclusionList => format!("{PATH_BUILDER_API}{PATH_GET_INCLUSION_LIST}"),
Route::Status => format!("{PATH_PROPOSER_API}{PATH_STATUS}"),
Route::RegisterValidators => format!("{PATH_PROPOSER_API}{PATH_REGISTER_VALIDATORS}"),
Route::GetHeader => format!("{PATH_PROPOSER_API}{PATH_GET_HEADER}"),
Route::HeaderStream => format!("{PATH_PROPOSER_API}{PATH_HEADER_STREAM}"),
Route::GetPayload => format!("{PATH_PROPOSER_API}{PATH_GET_PAYLOAD}"),
Route::GetPayloadV2 => format!("{PATH_PROPOSER_API_V2}{PATH_GET_PAYLOAD}"),
Route::ProposerPayloadDelivered => {
format!("{PATH_DATA_API}{PATH_PROPOSER_PAYLOAD_DELIVERED}")
}
Route::ProposerPayloadDeliveredV2 => {
format!("{PATH_DATA_API_V2}{PATH_PROPOSER_PAYLOAD_DELIVERED}")
}
Route::ProposerHeaderDelivered => {
format!("{PATH_DATA_API}{PATH_PROPOSER_HEADER_DELIVERED}")
}
Route::BuilderBidsReceived => format!("{PATH_DATA_API}{PATH_BUILDER_BIDS_RECEIVED}"),
Route::BuilderBidsReceivedV2 => {
format!("{PATH_DATA_API_V2}{PATH_BUILDER_BIDS_RECEIVED}")
}
Route::ValidatorRegistration => format!("{PATH_DATA_API}{PATH_VALIDATOR_REGISTRATION}"),
Route::DataAdjustments => format!("{PATH_DATA_API}{PATH_DATA_ADJUSTMENTS}"),
Route::MergedBlocks => format!("{PATH_DATA_API}{PATH_MERGED_BLOCKS}"),
Route::All => panic!("All is not a real route"),
Route::BuilderApi => panic!("BuilderApi is not a real route"),
Route::ProposerApi => panic!("ProposerApi is not a real route"),
Route::DataApi => panic!("DataApi is not a real route"),
Route::RelayNetwork => PATH_RELAY_NETWORK.to_string(),
}
}
}
fn default_duration() -> u64 {
1000
}
#[derive(Serialize, Deserialize, Clone)]
pub struct S3Config {
pub bucket: String,
pub region: String,
}
#[derive(Clone, Deserialize, Serialize)]
pub struct InclusionListConfig {
pub node_url: Url,
pub relay_address: Address,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct HeaderStreamConfig {
/// How long to stream for, ending at the client's `X-Timeout-Ms` deadline.
#[serde(default = "default_u64::<300>")]
pub stream_for_ms: u64,
/// Interval between bid updates.
#[serde(default = "default_u64::<5>")]
pub interval_ms: u64,
/// Keys allowed to open a stream. Empty allows every connection.
#[serde(default)]
pub api_keys: HashSet<String>,
}
impl Default for HeaderStreamConfig {
fn default() -> Self {
Self { stream_for_ms: 300, interval_ms: 5, api_keys: HashSet::new() }
}
}
#[cfg(test)]
mod tests {
use super::*;
fn create_router_config(routes: Vec<Route>) -> RouterConfig {
RouterConfig {
enabled_routes: routes
.into_iter()
.map(|route| RouteInfo { route, rate_limit: None })
.collect(),
shutdown_delay_ms: 12_000,
}
}
#[test]
fn test_validate_bid_sorter_empty_routes() {
let config = create_router_config(vec![]);
let result = config.validate_bid_sorter();
assert!(result.is_ok());
assert!(!result.unwrap());
}
#[test]
fn test_validate_bid_sorter_all_route() {
let config = create_router_config(vec![Route::All]);
let result = config.validate_bid_sorter();
assert!(result.is_ok());
assert!(result.unwrap());
}
#[test]
fn test_validate_bid_sorter_valid_get_header_instance() {
let config =
create_router_config(vec![Route::GetHeader, Route::SubmitBlock, Route::GetTopBid]);
let result = config.validate_bid_sorter();
assert!(result.is_ok());
assert!(result.unwrap());
}
#[test]
fn test_validate_bid_sorter_valid_proposer_api_instance() {
let config = create_router_config(vec![Route::ProposerApi, Route::BuilderApi]);
let result = config.validate_bid_sorter();
assert!(result.is_ok());
assert!(result.unwrap());
}
#[test]
fn test_validate_bid_sorter_get_header_without_submission() {
let config = create_router_config(vec![Route::GetHeader, Route::GetTopBid]);
let result = config.validate_bid_sorter();
assert!(result.is_err());
assert!(
result
.unwrap_err()
.to_string()
.contains("relay is serving headers so should have submissions enabled")
);
}
#[test]
fn test_validate_bid_sorter_submission_without_get_header() {
let config = create_router_config(vec![Route::SubmitBlock, Route::GetTopBid]);
let result = config.validate_bid_sorter();
assert!(result.is_err());
assert!(
result
.unwrap_err()
.to_string()
.contains("relay is receiving blocks so should have get_header enabled")
);
}
#[test]
fn test_validate_bid_sorter_get_header_without_top_bid() {
let config = create_router_config(vec![Route::GetHeader, Route::SubmitBlock]);
let result = config.validate_bid_sorter();
assert!(result.is_err());
assert!(result.unwrap_err().to_string().contains("routes should have get_top_bid enabled"));
}
#[test]
fn test_validate_bid_sorter_submission_without_top_bid() {
let config = create_router_config(vec![Route::SubmitBlock, Route::GetHeader]);
let result = config.validate_bid_sorter();
assert!(result.is_err());
assert!(result.unwrap_err().to_string().contains("routes should have get_top_bid enabled"));
}
#[test]
fn test_validate_bid_sorter_data_api_only() {
let config = create_router_config(vec![Route::DataApi, Route::ProposerPayloadDelivered]);
let result = config.validate_bid_sorter();
assert!(result.is_ok());
assert!(!result.unwrap());
}
}