1use std::{cell::RefCell, error::Error, fmt::Display, marker::PhantomData, path::PathBuf, rc::Rc};
2
3use multiaddr::Multiaddr;
4use serde::{ser::SerializeStruct, Deserialize, Serialize};
5
6use super::{
7 errors::FieldError,
8 helpers::{
9 ensure_port_unique, ensure_value_is_not_empty, generate_unique_node_name,
10 generate_unique_node_name_from_names, merge_errors, merge_errors_vecs,
11 },
12 macros::states,
13 resources::ResourcesBuilder,
14 types::{AssetLocation, ChainDefaultContext, Command, Image, ValidationContext, U128},
15};
16use crate::{
17 shared::{
18 resources::Resources,
19 types::{Arg, Port},
20 },
21 utils::{default_as_true, default_initial_balance},
22};
23
24states! {
25 Buildable,
26 Initial
27}
28
29#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
48pub struct EnvVar {
49 pub name: String,
51
52 pub value: String,
54}
55
56impl From<(&str, &str)> for EnvVar {
57 fn from((name, value): (&str, &str)) -> Self {
58 Self {
59 name: name.to_owned(),
60 value: value.to_owned(),
61 }
62 }
63}
64
65#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
67pub struct NodeConfig {
68 pub(crate) name: String,
69 pub(crate) image: Option<Image>,
70 pub(crate) command: Option<Command>,
71 pub(crate) subcommand: Option<Command>,
72 #[serde(default)]
73 args: Vec<Arg>,
74 #[serde(alias = "validator", default = "default_as_true")]
75 pub(crate) is_validator: bool,
76 #[serde(alias = "invulnerable", default = "default_as_true")]
77 pub(crate) is_invulnerable: bool,
78 #[serde(alias = "bootnode", default)]
79 pub(crate) is_bootnode: bool,
80 #[serde(alias = "balance")]
81 #[serde(default = "default_initial_balance")]
82 initial_balance: U128,
83 #[serde(default)]
84 env: Vec<EnvVar>,
85 #[serde(default)]
86 bootnodes_addresses: Vec<Multiaddr>,
87 pub(crate) resources: Option<Resources>,
88 ws_port: Option<Port>,
89 rpc_port: Option<Port>,
90 prometheus_port: Option<Port>,
91 p2p_port: Option<Port>,
92 p2p_cert_hash: Option<String>,
93 pub(crate) db_snapshot: Option<AssetLocation>,
94 #[serde(default, skip_serializing_if = "Option::is_none")]
97 override_eth_key: Option<String>,
98 #[serde(default)]
99 pub(crate) chain_context: ChainDefaultContext,
101 pub(crate) node_log_path: Option<PathBuf>,
102 keystore_path: Option<PathBuf>,
104 #[serde(default)]
108 keystore_key_types: Vec<String>,
109 #[serde(default)]
114 chain_spec_key_types: Vec<String>,
115}
116
117impl Serialize for NodeConfig {
118 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
119 where
120 S: serde::Serializer,
121 {
122 let mut state = serializer.serialize_struct("NodeConfig", 19)?;
123 state.serialize_field("name", &self.name)?;
124
125 if self.image == self.chain_context.default_image {
126 state.skip_field("image")?;
127 } else {
128 state.serialize_field("image", &self.image)?;
129 }
130
131 if self.command == self.chain_context.default_command {
132 state.skip_field("command")?;
133 } else {
134 state.serialize_field("command", &self.command)?;
135 }
136
137 if self.subcommand.is_none() {
138 state.skip_field("subcommand")?;
139 } else {
140 state.serialize_field("subcommand", &self.subcommand)?;
141 }
142
143 if self.args.is_empty() || self.args == self.chain_context.default_args {
144 state.skip_field("args")?;
145 } else {
146 state.serialize_field("args", &self.args)?;
147 }
148
149 state.serialize_field("validator", &self.is_validator)?;
150 state.serialize_field("invulnerable", &self.is_invulnerable)?;
151 state.serialize_field("bootnode", &self.is_bootnode)?;
152 state.serialize_field("balance", &self.initial_balance)?;
153
154 if self.env.is_empty() {
155 state.skip_field("env")?;
156 } else {
157 state.serialize_field("env", &self.env)?;
158 }
159
160 if self.bootnodes_addresses.is_empty() {
161 state.skip_field("bootnodes_addresses")?;
162 } else {
163 state.serialize_field("bootnodes_addresses", &self.bootnodes_addresses)?;
164 }
165
166 if self.resources == self.chain_context.default_resources {
167 state.skip_field("resources")?;
168 } else {
169 state.serialize_field("resources", &self.resources)?;
170 }
171
172 state.serialize_field("ws_port", &self.ws_port)?;
173 state.serialize_field("rpc_port", &self.rpc_port)?;
174 state.serialize_field("prometheus_port", &self.prometheus_port)?;
175 state.serialize_field("p2p_port", &self.p2p_port)?;
176 state.serialize_field("p2p_cert_hash", &self.p2p_cert_hash)?;
177 state.serialize_field("override_eth_key", &self.override_eth_key)?;
178
179 if self.db_snapshot == self.chain_context.default_db_snapshot {
180 state.skip_field("db_snapshot")?;
181 } else {
182 state.serialize_field("db_snapshot", &self.db_snapshot)?;
183 }
184
185 if self.node_log_path.is_none() {
186 state.skip_field("node_log_path")?;
187 } else {
188 state.serialize_field("node_log_path", &self.node_log_path)?;
189 }
190
191 if self.keystore_path.is_none() {
192 state.skip_field("keystore_path")?;
193 } else {
194 state.serialize_field("keystore_path", &self.keystore_path)?;
195 }
196
197 if self.keystore_key_types.is_empty() {
198 state.skip_field("keystore_key_types")?;
199 } else {
200 state.serialize_field("keystore_key_types", &self.keystore_key_types)?;
201 }
202
203 if self.chain_spec_key_types.is_empty() {
204 state.skip_field("chain_spec_key_typese")?;
205 } else {
206 state.serialize_field("chain_spec_key_types", &self.chain_spec_key_types)?;
207 }
208
209 state.skip_field("chain_context")?;
210 state.end()
211 }
212}
213
214#[derive(Debug, Clone, PartialEq, Deserialize)]
216pub struct GroupNodeConfig {
217 #[serde(flatten)]
218 pub(crate) base_config: NodeConfig,
219 pub(crate) count: usize,
220}
221
222impl GroupNodeConfig {
223 pub fn expand_group_configs(&self) -> Vec<NodeConfig> {
226 let mut used_names = std::collections::HashSet::new();
227
228 (0..self.count)
229 .map(|i| {
230 let mut node = self.base_config.clone();
231 let node_name = format!("{}-{i}", node.name);
233
234 let unique_name = generate_unique_node_name_from_names(node_name, &mut used_names);
235 node.name = unique_name;
236
237 if let Some(ref base_log_path) = node.node_log_path {
239 let unique_log_path = if let Some(parent) = base_log_path.parent() {
240 parent.join(format!("{}.log", node.name))
241 } else {
242 PathBuf::from(format!("{}.log", node.name))
243 };
244 node.node_log_path = Some(unique_log_path);
245 }
246
247 node
248 })
249 .collect()
250 }
251}
252
253impl Serialize for GroupNodeConfig {
254 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
255 where
256 S: serde::Serializer,
257 {
258 let mut state = serializer.serialize_struct("GroupNodeConfig", 18)?;
259 state.serialize_field("NodeConfig", &self.base_config)?;
260 state.serialize_field("count", &self.count)?;
261 state.end()
262 }
263}
264
265impl NodeConfig {
266 pub fn name(&self) -> &str {
268 &self.name
269 }
270
271 pub fn image(&self) -> Option<&Image> {
273 self.image.as_ref()
274 }
275
276 pub fn command(&self) -> Option<&Command> {
278 self.command.as_ref()
279 }
280
281 pub fn subcommand(&self) -> Option<&Command> {
283 self.subcommand.as_ref()
284 }
285
286 pub fn args(&self) -> Vec<&Arg> {
288 self.args.iter().collect()
289 }
290
291 pub(crate) fn set_args(&mut self, args: Vec<Arg>) {
293 self.args = args;
294 }
295
296 pub fn is_validator(&self) -> bool {
298 self.is_validator
299 }
300
301 pub fn is_invulnerable(&self) -> bool {
303 self.is_invulnerable
304 }
305
306 pub fn is_bootnode(&self) -> bool {
308 self.is_bootnode
309 }
310
311 pub fn initial_balance(&self) -> u128 {
313 self.initial_balance.0
314 }
315
316 pub fn env(&self) -> Vec<&EnvVar> {
318 self.env.iter().collect()
319 }
320
321 pub fn bootnodes_addresses(&self) -> Vec<&Multiaddr> {
323 self.bootnodes_addresses.iter().collect()
324 }
325
326 pub fn resources(&self) -> Option<&Resources> {
328 self.resources.as_ref()
329 }
330
331 pub fn ws_port(&self) -> Option<u16> {
333 self.ws_port
334 }
335
336 pub fn rpc_port(&self) -> Option<u16> {
338 self.rpc_port
339 }
340
341 pub fn prometheus_port(&self) -> Option<u16> {
343 self.prometheus_port
344 }
345
346 pub fn p2p_port(&self) -> Option<u16> {
348 self.p2p_port
349 }
350
351 pub fn p2p_cert_hash(&self) -> Option<&str> {
353 self.p2p_cert_hash.as_deref()
354 }
355
356 pub fn db_snapshot(&self) -> Option<&AssetLocation> {
358 self.db_snapshot.as_ref()
359 }
360
361 pub fn node_log_path(&self) -> Option<&PathBuf> {
363 self.node_log_path.as_ref()
364 }
365
366 pub fn keystore_path(&self) -> Option<&PathBuf> {
368 self.keystore_path.as_ref()
369 }
370
371 pub fn override_eth_key(&self) -> Option<&str> {
373 self.override_eth_key.as_deref()
374 }
375
376 pub fn keystore_key_types(&self) -> Vec<&str> {
379 self.keystore_key_types.iter().map(String::as_str).collect()
380 }
381
382 pub fn chain_spec_key_types(&self) -> Vec<&str> {
385 self.chain_spec_key_types
386 .iter()
387 .map(String::as_str)
388 .collect()
389 }
390}
391
392pub struct NodeConfigBuilder<S> {
394 config: NodeConfig,
395 validation_context: Rc<RefCell<ValidationContext>>,
396 errors: Vec<anyhow::Error>,
397 _state: PhantomData<S>,
398}
399
400impl Default for NodeConfigBuilder<Initial> {
401 fn default() -> Self {
402 Self {
403 config: NodeConfig {
404 name: "".into(),
405 image: None,
406 command: None,
407 subcommand: None,
408 args: vec![],
409 is_validator: true,
410 is_invulnerable: true,
411 is_bootnode: false,
412 initial_balance: 2_000_000_000_000.into(),
413 env: vec![],
414 bootnodes_addresses: vec![],
415 resources: None,
416 ws_port: None,
417 rpc_port: None,
418 prometheus_port: None,
419 p2p_port: None,
420 p2p_cert_hash: None,
421 db_snapshot: None,
422 override_eth_key: None,
423 chain_context: Default::default(),
424 node_log_path: None,
425 keystore_path: None,
426 keystore_key_types: vec![],
427 chain_spec_key_types: vec![],
428 },
429 validation_context: Default::default(),
430 errors: vec![],
431 _state: PhantomData,
432 }
433 }
434}
435
436impl<A> NodeConfigBuilder<A> {
437 fn transition<B>(
438 config: NodeConfig,
439 validation_context: Rc<RefCell<ValidationContext>>,
440 errors: Vec<anyhow::Error>,
441 ) -> NodeConfigBuilder<B> {
442 NodeConfigBuilder {
443 config,
444 validation_context,
445 errors,
446 _state: PhantomData,
447 }
448 }
449}
450
451impl NodeConfigBuilder<Initial> {
452 pub fn new(
453 chain_context: ChainDefaultContext,
454 validation_context: Rc<RefCell<ValidationContext>>,
455 ) -> Self {
456 Self::transition(
457 NodeConfig {
458 command: chain_context.default_command.clone(),
459 image: chain_context.default_image.clone(),
460 resources: chain_context.default_resources.clone(),
461 db_snapshot: chain_context.default_db_snapshot.clone(),
462 args: chain_context.default_args.clone(),
463 chain_context,
464 ..Self::default().config
465 },
466 validation_context,
467 vec![],
468 )
469 }
470
471 pub fn with_name<T: Into<String> + Copy>(self, name: T) -> NodeConfigBuilder<Buildable> {
473 let name: String = generate_unique_node_name(name, self.validation_context.clone());
474
475 match ensure_value_is_not_empty(&name) {
476 Ok(_) => Self::transition(
477 NodeConfig {
478 name,
479 ..self.config
480 },
481 self.validation_context,
482 self.errors,
483 ),
484 Err(e) => Self::transition(
485 NodeConfig {
486 name,
488 ..self.config
489 },
490 self.validation_context,
491 merge_errors(self.errors, FieldError::Name(e).into()),
492 ),
493 }
494 }
495}
496
497impl NodeConfigBuilder<Buildable> {
498 pub fn with_command<T>(self, command: T) -> Self
500 where
501 T: TryInto<Command>,
502 T::Error: Error + Send + Sync + 'static,
503 {
504 match command.try_into() {
505 Ok(command) => Self::transition(
506 NodeConfig {
507 command: Some(command),
508 ..self.config
509 },
510 self.validation_context,
511 self.errors,
512 ),
513 Err(error) => Self::transition(
514 self.config,
515 self.validation_context,
516 merge_errors(self.errors, FieldError::Command(error.into()).into()),
517 ),
518 }
519 }
520
521 pub fn with_subcommand<T>(self, subcommand: T) -> Self
523 where
524 T: TryInto<Command>,
525 T::Error: Error + Send + Sync + 'static,
526 {
527 match subcommand.try_into() {
528 Ok(subcommand) => Self::transition(
529 NodeConfig {
530 subcommand: Some(subcommand),
531 ..self.config
532 },
533 self.validation_context,
534 self.errors,
535 ),
536 Err(error) => Self::transition(
537 self.config,
538 self.validation_context,
539 merge_errors(self.errors, FieldError::Command(error.into()).into()),
540 ),
541 }
542 }
543
544 pub fn with_image<T>(self, image: T) -> Self
546 where
547 T: TryInto<Image>,
548 T::Error: Error + Send + Sync + 'static,
549 {
550 match image.try_into() {
551 Ok(image) => Self::transition(
552 NodeConfig {
553 image: Some(image),
554 ..self.config
555 },
556 self.validation_context,
557 self.errors,
558 ),
559 Err(error) => Self::transition(
560 self.config,
561 self.validation_context,
562 merge_errors(self.errors, FieldError::Image(error.into()).into()),
563 ),
564 }
565 }
566
567 pub fn with_args(self, args: Vec<Arg>) -> Self {
569 Self::transition(
570 NodeConfig {
571 args,
572 ..self.config
573 },
574 self.validation_context,
575 self.errors,
576 )
577 }
578
579 pub fn validator(self, choice: bool) -> Self {
581 Self::transition(
582 NodeConfig {
583 is_validator: choice,
584 ..self.config
585 },
586 self.validation_context,
587 self.errors,
588 )
589 }
590
591 pub fn invulnerable(self, choice: bool) -> Self {
593 Self::transition(
594 NodeConfig {
595 is_invulnerable: choice,
596 ..self.config
597 },
598 self.validation_context,
599 self.errors,
600 )
601 }
602
603 pub fn bootnode(self, choice: bool) -> Self {
605 Self::transition(
606 NodeConfig {
607 is_bootnode: choice,
608 ..self.config
609 },
610 self.validation_context,
611 self.errors,
612 )
613 }
614
615 pub fn with_override_eth_key(self, session_key: impl Into<String>) -> Self {
617 Self::transition(
618 NodeConfig {
619 override_eth_key: Some(session_key.into()),
620 ..self.config
621 },
622 self.validation_context,
623 self.errors,
624 )
625 }
626
627 pub fn with_initial_balance(self, initial_balance: u128) -> Self {
629 Self::transition(
630 NodeConfig {
631 initial_balance: initial_balance.into(),
632 ..self.config
633 },
634 self.validation_context,
635 self.errors,
636 )
637 }
638
639 pub fn with_env(self, env: Vec<impl Into<EnvVar>>) -> Self {
641 let env = env.into_iter().map(|var| var.into()).collect::<Vec<_>>();
642
643 Self::transition(
644 NodeConfig { env, ..self.config },
645 self.validation_context,
646 self.errors,
647 )
648 }
649
650 pub fn with_raw_bootnodes_addresses<T>(self, bootnodes_addresses: Vec<T>) -> Self
655 where
656 T: TryInto<Multiaddr> + Display + Copy,
657 T::Error: Error + Send + Sync + 'static,
658 {
659 let mut addrs = vec![];
660 let mut errors = vec![];
661
662 for (index, addr) in bootnodes_addresses.into_iter().enumerate() {
663 match addr.try_into() {
664 Ok(addr) => addrs.push(addr),
665 Err(error) => errors.push(
666 FieldError::BootnodesAddress(index, addr.to_string(), error.into()).into(),
667 ),
668 }
669 }
670
671 Self::transition(
672 NodeConfig {
673 bootnodes_addresses: addrs,
674 ..self.config
675 },
676 self.validation_context,
677 merge_errors_vecs(self.errors, errors),
678 )
679 }
680
681 pub fn with_resources(self, f: impl FnOnce(ResourcesBuilder) -> ResourcesBuilder) -> Self {
683 match f(ResourcesBuilder::new()).build() {
684 Ok(resources) => Self::transition(
685 NodeConfig {
686 resources: Some(resources),
687 ..self.config
688 },
689 self.validation_context,
690 self.errors,
691 ),
692 Err(errors) => Self::transition(
693 self.config,
694 self.validation_context,
695 merge_errors_vecs(
696 self.errors,
697 errors
698 .into_iter()
699 .map(|error| FieldError::Resources(error).into())
700 .collect::<Vec<_>>(),
701 ),
702 ),
703 }
704 }
705
706 pub fn with_ws_port(self, ws_port: Port) -> Self {
708 match ensure_port_unique(ws_port, self.validation_context.clone()) {
709 Ok(_) => Self::transition(
710 NodeConfig {
711 ws_port: Some(ws_port),
712 ..self.config
713 },
714 self.validation_context,
715 self.errors,
716 ),
717 Err(error) => Self::transition(
718 self.config,
719 self.validation_context,
720 merge_errors(self.errors, FieldError::WsPort(error).into()),
721 ),
722 }
723 }
724
725 pub fn with_rpc_port(self, rpc_port: Port) -> Self {
727 match ensure_port_unique(rpc_port, self.validation_context.clone()) {
728 Ok(_) => Self::transition(
729 NodeConfig {
730 rpc_port: Some(rpc_port),
731 ..self.config
732 },
733 self.validation_context,
734 self.errors,
735 ),
736 Err(error) => Self::transition(
737 self.config,
738 self.validation_context,
739 merge_errors(self.errors, FieldError::RpcPort(error).into()),
740 ),
741 }
742 }
743
744 pub fn with_prometheus_port(self, prometheus_port: Port) -> Self {
746 match ensure_port_unique(prometheus_port, self.validation_context.clone()) {
747 Ok(_) => Self::transition(
748 NodeConfig {
749 prometheus_port: Some(prometheus_port),
750 ..self.config
751 },
752 self.validation_context,
753 self.errors,
754 ),
755 Err(error) => Self::transition(
756 self.config,
757 self.validation_context,
758 merge_errors(self.errors, FieldError::PrometheusPort(error).into()),
759 ),
760 }
761 }
762
763 pub fn with_p2p_port(self, p2p_port: Port) -> Self {
765 match ensure_port_unique(p2p_port, self.validation_context.clone()) {
766 Ok(_) => Self::transition(
767 NodeConfig {
768 p2p_port: Some(p2p_port),
769 ..self.config
770 },
771 self.validation_context,
772 self.errors,
773 ),
774 Err(error) => Self::transition(
775 self.config,
776 self.validation_context,
777 merge_errors(self.errors, FieldError::P2pPort(error).into()),
778 ),
779 }
780 }
781
782 pub fn with_p2p_cert_hash(self, p2p_cert_hash: impl Into<String>) -> Self {
785 Self::transition(
786 NodeConfig {
787 p2p_cert_hash: Some(p2p_cert_hash.into()),
788 ..self.config
789 },
790 self.validation_context,
791 self.errors,
792 )
793 }
794
795 pub fn with_db_snapshot(self, location: impl Into<AssetLocation>) -> Self {
797 Self::transition(
798 NodeConfig {
799 db_snapshot: Some(location.into()),
800 ..self.config
801 },
802 self.validation_context,
803 self.errors,
804 )
805 }
806
807 pub fn with_log_path(self, log_path: impl Into<PathBuf>) -> Self {
809 Self::transition(
810 NodeConfig {
811 node_log_path: Some(log_path.into()),
812 ..self.config
813 },
814 self.validation_context,
815 self.errors,
816 )
817 }
818
819 pub fn with_keystore_path(self, keystore_path: impl Into<PathBuf>) -> Self {
821 Self::transition(
822 NodeConfig {
823 keystore_path: Some(keystore_path.into()),
824 ..self.config
825 },
826 self.validation_context,
827 self.errors,
828 )
829 }
830
831 pub fn with_keystore_key_types(self, key_types: Vec<impl Into<String>>) -> Self {
851 Self::transition(
852 NodeConfig {
853 keystore_key_types: key_types.into_iter().map(|k| k.into()).collect(),
854 ..self.config
855 },
856 self.validation_context,
857 self.errors,
858 )
859 }
860
861 pub fn with_chain_spec_key_types(self, key_types: Vec<impl Into<String>>) -> Self {
887 Self::transition(
888 NodeConfig {
889 chain_spec_key_types: key_types.into_iter().map(|k| k.into()).collect(),
890 ..self.config
891 },
892 self.validation_context,
893 self.errors,
894 )
895 }
896
897 pub fn build(self) -> Result<NodeConfig, (String, Vec<anyhow::Error>)> {
899 if !self.errors.is_empty() {
900 return Err((self.config.name.clone(), self.errors));
901 }
902
903 Ok(self.config)
904 }
905}
906
907pub struct GroupNodeConfigBuilder<S> {
909 base_config: NodeConfig,
910 count: usize,
911 validation_context: Rc<RefCell<ValidationContext>>,
912 errors: Vec<anyhow::Error>,
913 _state: PhantomData<S>,
914}
915
916impl GroupNodeConfigBuilder<Initial> {
917 pub fn new(
918 chain_context: ChainDefaultContext,
919 validation_context: Rc<RefCell<ValidationContext>>,
920 ) -> Self {
921 let (errors, base_config) = match NodeConfigBuilder::new(
922 chain_context.clone(),
923 validation_context.clone(),
924 )
925 .with_name(" ") .build()
927 {
928 Ok(base_config) => (vec![], base_config),
929 Err((_name, errors)) => (errors, NodeConfig::default()),
930 };
931
932 Self {
933 base_config,
934 count: 1,
935 validation_context,
936 errors,
937 _state: PhantomData,
938 }
939 }
940
941 pub fn with_base_node(
943 mut self,
944 f: impl FnOnce(NodeConfigBuilder<Initial>) -> NodeConfigBuilder<Buildable>,
945 ) -> GroupNodeConfigBuilder<Buildable> {
946 match f(NodeConfigBuilder::new(
947 ChainDefaultContext::default(),
948 self.validation_context.clone(),
949 ))
950 .build()
951 {
952 Ok(node) => {
953 self.base_config = node;
954 GroupNodeConfigBuilder {
955 base_config: self.base_config,
956 count: self.count,
957 validation_context: self.validation_context,
958 errors: self.errors,
959 _state: PhantomData,
960 }
961 },
962 Err((_name, errors)) => {
963 self.errors.extend(errors);
964 GroupNodeConfigBuilder {
965 base_config: self.base_config,
966 count: self.count,
967 validation_context: self.validation_context,
968 errors: self.errors,
969 _state: PhantomData,
970 }
971 },
972 }
973 }
974
975 pub fn with_count(mut self, count: usize) -> Self {
977 self.count = count;
978 self
979 }
980}
981
982impl GroupNodeConfigBuilder<Buildable> {
983 pub fn with_count(mut self, count: usize) -> Self {
985 self.count = count;
986 self
987 }
988
989 pub fn build(self) -> Result<GroupNodeConfig, (String, Vec<anyhow::Error>)> {
990 if self.count == 0 {
991 return Err((
992 self.base_config.name().to_string(),
993 vec![anyhow::anyhow!("Count cannot be zero")],
994 ));
995 }
996
997 if !self.errors.is_empty() {
998 return Err((self.base_config.name().to_string(), self.errors));
999 }
1000
1001 Ok(GroupNodeConfig {
1002 base_config: self.base_config,
1003 count: self.count,
1004 })
1005 }
1006}
1007
1008#[cfg(test)]
1009mod tests {
1010 use std::collections::HashSet;
1011
1012 use super::*;
1013
1014 #[test]
1015 fn node_config_builder_should_succeeds_and_returns_a_node_config() {
1016 let node_config =
1017 NodeConfigBuilder::new(ChainDefaultContext::default(), Default::default())
1018 .with_name("node")
1019 .with_command("mycommand")
1020 .with_image("myrepo:myimage")
1021 .with_args(vec![("--arg1", "value1").into(), "--option2".into()])
1022 .validator(true)
1023 .invulnerable(true)
1024 .bootnode(true)
1025 .with_override_eth_key("0x0123456789abcdef0123456789abcdef01234567")
1026 .with_initial_balance(100_000_042)
1027 .with_env(vec![("VAR1", "VALUE1"), ("VAR2", "VALUE2")])
1028 .with_raw_bootnodes_addresses(vec![
1029 "/ip4/10.41.122.55/tcp/45421",
1030 "/ip4/51.144.222.10/tcp/2333",
1031 ])
1032 .with_resources(|resources| {
1033 resources
1034 .with_request_cpu("200M")
1035 .with_request_memory("500M")
1036 .with_limit_cpu("1G")
1037 .with_limit_memory("2G")
1038 })
1039 .with_ws_port(5000)
1040 .with_rpc_port(6000)
1041 .with_prometheus_port(7000)
1042 .with_p2p_port(8000)
1043 .with_p2p_cert_hash(
1044 "ec8d6467180a4b72a52b24c53aa1e53b76c05602fa96f5d0961bf720edda267f",
1045 )
1046 .with_db_snapshot("/tmp/mysnapshot")
1047 .with_keystore_path("/tmp/mykeystore")
1048 .build()
1049 .unwrap();
1050
1051 assert_eq!(node_config.name(), "node");
1052 assert_eq!(node_config.command().unwrap().as_str(), "mycommand");
1053 assert_eq!(node_config.image().unwrap().as_str(), "myrepo:myimage");
1054 let args: Vec<Arg> = vec![("--arg1", "value1").into(), "--option2".into()];
1055 assert_eq!(node_config.args(), args.iter().collect::<Vec<_>>());
1056 assert!(node_config.is_validator());
1057 assert!(node_config.is_invulnerable());
1058 assert!(node_config.is_bootnode());
1059 assert_eq!(
1060 node_config.override_eth_key(),
1061 Some("0x0123456789abcdef0123456789abcdef01234567")
1062 );
1063 assert_eq!(node_config.initial_balance(), 100_000_042);
1064 let env: Vec<EnvVar> = vec![("VAR1", "VALUE1").into(), ("VAR2", "VALUE2").into()];
1065 assert_eq!(node_config.env(), env.iter().collect::<Vec<_>>());
1066 let bootnodes_addresses: Vec<Multiaddr> = vec![
1067 "/ip4/10.41.122.55/tcp/45421".try_into().unwrap(),
1068 "/ip4/51.144.222.10/tcp/2333".try_into().unwrap(),
1069 ];
1070 assert_eq!(
1071 node_config.bootnodes_addresses(),
1072 bootnodes_addresses.iter().collect::<Vec<_>>()
1073 );
1074 let resources = node_config.resources().unwrap();
1075 assert_eq!(resources.request_cpu().unwrap().as_str(), "200M");
1076 assert_eq!(resources.request_memory().unwrap().as_str(), "500M");
1077 assert_eq!(resources.limit_cpu().unwrap().as_str(), "1G");
1078 assert_eq!(resources.limit_memory().unwrap().as_str(), "2G");
1079 assert_eq!(node_config.ws_port().unwrap(), 5000);
1080 assert_eq!(node_config.rpc_port().unwrap(), 6000);
1081 assert_eq!(node_config.prometheus_port().unwrap(), 7000);
1082 assert_eq!(node_config.p2p_port().unwrap(), 8000);
1083 assert_eq!(
1084 node_config.p2p_cert_hash().unwrap(),
1085 "ec8d6467180a4b72a52b24c53aa1e53b76c05602fa96f5d0961bf720edda267f"
1086 );
1087 assert!(matches!(
1088 node_config.db_snapshot().unwrap(), AssetLocation::FilePath(value) if value.to_str().unwrap() == "/tmp/mysnapshot"
1089 ));
1090 assert!(matches!(
1091 node_config.keystore_path().unwrap().to_str().unwrap(),
1092 "/tmp/mykeystore"
1093 ));
1094 }
1095
1096 #[test]
1097 fn node_config_builder_should_use_unique_name_if_node_name_already_used() {
1098 let mut used_nodes_names = HashSet::new();
1099 used_nodes_names.insert("mynode".into());
1100 let validation_context = Rc::new(RefCell::new(ValidationContext {
1101 used_nodes_names,
1102 ..Default::default()
1103 }));
1104 let node_config =
1105 NodeConfigBuilder::new(ChainDefaultContext::default(), validation_context)
1106 .with_name("mynode")
1107 .build()
1108 .unwrap();
1109
1110 assert_eq!(node_config.name, "mynode-1");
1111 }
1112
1113 #[test]
1114 fn node_config_builder_should_fails_and_returns_an_error_and_node_name_if_command_is_invalid() {
1115 let (node_name, errors) =
1116 NodeConfigBuilder::new(ChainDefaultContext::default(), Default::default())
1117 .with_name("node")
1118 .with_command("invalid command")
1119 .build()
1120 .unwrap_err();
1121
1122 assert_eq!(node_name, "node");
1123 assert_eq!(errors.len(), 1);
1124 assert_eq!(
1125 errors.first().unwrap().to_string(),
1126 "command: 'invalid command' shouldn't contains whitespace"
1127 );
1128 }
1129
1130 #[test]
1131 fn node_config_builder_should_fails_and_returns_an_error_and_node_name_if_image_is_invalid() {
1132 let (node_name, errors) =
1133 NodeConfigBuilder::new(ChainDefaultContext::default(), Default::default())
1134 .with_name("node")
1135 .with_image("myinvalid.image")
1136 .build()
1137 .unwrap_err();
1138
1139 assert_eq!(node_name, "node");
1140 assert_eq!(errors.len(), 1);
1141 assert_eq!(
1142 errors.first().unwrap().to_string(),
1143 "image: 'myinvalid.image' doesn't match regex '^([ip]|[hostname]/)?[tag_name]:[tag_version]?$'"
1144 );
1145 }
1146
1147 #[test]
1148 fn node_config_builder_should_fails_and_returns_an_error_and_node_name_if_one_bootnode_address_is_invalid(
1149 ) {
1150 let (node_name, errors) =
1151 NodeConfigBuilder::new(ChainDefaultContext::default(), Default::default())
1152 .with_name("node")
1153 .with_raw_bootnodes_addresses(vec!["/ip4//tcp/45421"])
1154 .build()
1155 .unwrap_err();
1156
1157 assert_eq!(node_name, "node");
1158 assert_eq!(errors.len(), 1);
1159 assert_eq!(
1160 errors.first().unwrap().to_string(),
1161 "bootnodes_addresses[0]: '/ip4//tcp/45421' failed to parse: invalid IPv4 address syntax"
1162 );
1163 }
1164
1165 #[test]
1166 fn node_config_builder_should_fails_and_returns_mulitle_errors_and_node_name_if_multiple_bootnode_address_are_invalid(
1167 ) {
1168 let (node_name, errors) =
1169 NodeConfigBuilder::new(ChainDefaultContext::default(), Default::default())
1170 .with_name("node")
1171 .with_raw_bootnodes_addresses(vec!["/ip4//tcp/45421", "//10.42.153.10/tcp/43111"])
1172 .build()
1173 .unwrap_err();
1174
1175 assert_eq!(node_name, "node");
1176 assert_eq!(errors.len(), 2);
1177 assert_eq!(
1178 errors.first().unwrap().to_string(),
1179 "bootnodes_addresses[0]: '/ip4//tcp/45421' failed to parse: invalid IPv4 address syntax"
1180 );
1181 assert_eq!(
1182 errors.get(1).unwrap().to_string(),
1183 "bootnodes_addresses[1]: '//10.42.153.10/tcp/43111' unknown protocol string: "
1184 );
1185 }
1186
1187 #[test]
1188 fn node_config_builder_should_fails_and_returns_an_error_and_node_name_if_resources_has_an_error(
1189 ) {
1190 let (node_name, errors) =
1191 NodeConfigBuilder::new(ChainDefaultContext::default(), Default::default())
1192 .with_name("node")
1193 .with_resources(|resources| resources.with_limit_cpu("invalid"))
1194 .build()
1195 .unwrap_err();
1196
1197 assert_eq!(node_name, "node");
1198 assert_eq!(errors.len(), 1);
1199 assert_eq!(
1200 errors.first().unwrap().to_string(),
1201 r"resources.limit_cpu: 'invalid' doesn't match regex '^\d+(.\d+)?(m|K|M|G|T|P|E|Ki|Mi|Gi|Ti|Pi|Ei)?$'"
1202 );
1203 }
1204
1205 #[test]
1206 fn node_config_builder_should_fails_and_returns_multiple_errors_and_node_name_if_resources_has_multiple_errors(
1207 ) {
1208 let (node_name, errors) =
1209 NodeConfigBuilder::new(ChainDefaultContext::default(), Default::default())
1210 .with_name("node")
1211 .with_resources(|resources| {
1212 resources
1213 .with_limit_cpu("invalid")
1214 .with_request_memory("invalid")
1215 })
1216 .build()
1217 .unwrap_err();
1218
1219 assert_eq!(node_name, "node");
1220 assert_eq!(errors.len(), 2);
1221 assert_eq!(
1222 errors.first().unwrap().to_string(),
1223 r"resources.limit_cpu: 'invalid' doesn't match regex '^\d+(.\d+)?(m|K|M|G|T|P|E|Ki|Mi|Gi|Ti|Pi|Ei)?$'"
1224 );
1225 assert_eq!(
1226 errors.get(1).unwrap().to_string(),
1227 r"resources.request_memory: 'invalid' doesn't match regex '^\d+(.\d+)?(m|K|M|G|T|P|E|Ki|Mi|Gi|Ti|Pi|Ei)?$'"
1228 );
1229 }
1230
1231 #[test]
1232 fn node_config_builder_should_fails_and_returns_multiple_errors_and_node_name_if_multiple_fields_have_errors(
1233 ) {
1234 let (node_name, errors) =
1235 NodeConfigBuilder::new(ChainDefaultContext::default(), Default::default())
1236 .with_name("node")
1237 .with_command("invalid command")
1238 .with_image("myinvalid.image")
1239 .with_resources(|resources| {
1240 resources
1241 .with_limit_cpu("invalid")
1242 .with_request_memory("invalid")
1243 })
1244 .build()
1245 .unwrap_err();
1246
1247 assert_eq!(node_name, "node");
1248 assert_eq!(errors.len(), 4);
1249 assert_eq!(
1250 errors.first().unwrap().to_string(),
1251 "command: 'invalid command' shouldn't contains whitespace"
1252 );
1253 assert_eq!(
1254 errors.get(1).unwrap().to_string(),
1255 "image: 'myinvalid.image' doesn't match regex '^([ip]|[hostname]/)?[tag_name]:[tag_version]?$'"
1256 );
1257 assert_eq!(
1258 errors.get(2).unwrap().to_string(),
1259 r"resources.limit_cpu: 'invalid' doesn't match regex '^\d+(.\d+)?(m|K|M|G|T|P|E|Ki|Mi|Gi|Ti|Pi|Ei)?$'"
1260 );
1261 assert_eq!(
1262 errors.get(3).unwrap().to_string(),
1263 r"resources.request_memory: 'invalid' doesn't match regex '^\d+(.\d+)?(m|K|M|G|T|P|E|Ki|Mi|Gi|Ti|Pi|Ei)?$'"
1264 );
1265 }
1266
1267 #[test]
1268 fn node_config_builder_should_fails_and_returns_an_error_and_node_name_if_ws_port_is_already_used(
1269 ) {
1270 let validation_context = Rc::new(RefCell::new(ValidationContext {
1271 used_ports: vec![30333],
1272 ..Default::default()
1273 }));
1274 let (node_name, errors) =
1275 NodeConfigBuilder::new(ChainDefaultContext::default(), validation_context)
1276 .with_name("node")
1277 .with_ws_port(30333)
1278 .build()
1279 .unwrap_err();
1280
1281 assert_eq!(node_name, "node");
1282 assert_eq!(errors.len(), 1);
1283 assert_eq!(
1284 errors.first().unwrap().to_string(),
1285 "ws_port: '30333' is already used across config"
1286 );
1287 }
1288
1289 #[test]
1290 fn node_config_builder_should_fails_and_returns_an_error_and_node_name_if_rpc_port_is_already_used(
1291 ) {
1292 let validation_context = Rc::new(RefCell::new(ValidationContext {
1293 used_ports: vec![4444],
1294 ..Default::default()
1295 }));
1296 let (node_name, errors) =
1297 NodeConfigBuilder::new(ChainDefaultContext::default(), validation_context)
1298 .with_name("node")
1299 .with_rpc_port(4444)
1300 .build()
1301 .unwrap_err();
1302
1303 assert_eq!(node_name, "node");
1304 assert_eq!(errors.len(), 1);
1305 assert_eq!(
1306 errors.first().unwrap().to_string(),
1307 "rpc_port: '4444' is already used across config"
1308 );
1309 }
1310
1311 #[test]
1312 fn node_config_builder_should_fails_and_returns_an_error_and_node_name_if_prometheus_port_is_already_used(
1313 ) {
1314 let validation_context = Rc::new(RefCell::new(ValidationContext {
1315 used_ports: vec![9089],
1316 ..Default::default()
1317 }));
1318 let (node_name, errors) =
1319 NodeConfigBuilder::new(ChainDefaultContext::default(), validation_context)
1320 .with_name("node")
1321 .with_prometheus_port(9089)
1322 .build()
1323 .unwrap_err();
1324
1325 assert_eq!(node_name, "node");
1326 assert_eq!(errors.len(), 1);
1327 assert_eq!(
1328 errors.first().unwrap().to_string(),
1329 "prometheus_port: '9089' is already used across config"
1330 );
1331 }
1332
1333 #[test]
1334 fn node_config_builder_should_fails_and_returns_and_error_and_node_name_if_p2p_port_is_already_used(
1335 ) {
1336 let validation_context = Rc::new(RefCell::new(ValidationContext {
1337 used_ports: vec![45093],
1338 ..Default::default()
1339 }));
1340 let (node_name, errors) =
1341 NodeConfigBuilder::new(ChainDefaultContext::default(), validation_context)
1342 .with_name("node")
1343 .with_p2p_port(45093)
1344 .build()
1345 .unwrap_err();
1346
1347 assert_eq!(node_name, "node");
1348 assert_eq!(errors.len(), 1);
1349 assert_eq!(
1350 errors.first().unwrap().to_string(),
1351 "p2p_port: '45093' is already used across config"
1352 );
1353 }
1354
1355 #[test]
1356 fn node_config_builder_should_fails_if_node_name_is_empty() {
1357 let validation_context = Rc::new(RefCell::new(ValidationContext {
1358 ..Default::default()
1359 }));
1360
1361 let (_, errors) =
1362 NodeConfigBuilder::new(ChainDefaultContext::default(), validation_context)
1363 .with_name("")
1364 .build()
1365 .unwrap_err();
1366
1367 assert_eq!(errors.len(), 1);
1368 assert_eq!(errors.first().unwrap().to_string(), "name: can't be empty");
1369 }
1370
1371 #[test]
1372 fn group_default_base_node() {
1373 let validation_context = Rc::new(RefCell::new(ValidationContext::default()));
1374
1375 let group_config =
1376 GroupNodeConfigBuilder::new(ChainDefaultContext::default(), validation_context.clone())
1377 .with_base_node(|node| node.with_name("validator"))
1378 .build()
1379 .unwrap();
1380
1381 assert_eq!(group_config.count, 1);
1383 assert_eq!(group_config.base_config.name(), "validator");
1384 }
1385
1386 #[test]
1387 fn group_custom_base_node() {
1388 let validation_context = Rc::new(RefCell::new(ValidationContext::default()));
1389 let node_config =
1390 NodeConfigBuilder::new(ChainDefaultContext::default(), validation_context.clone())
1391 .with_name("node")
1392 .with_command("some_command")
1393 .with_image("repo:image")
1394 .validator(true)
1395 .invulnerable(true)
1396 .bootnode(true);
1397
1398 let group_config =
1399 GroupNodeConfigBuilder::new(ChainDefaultContext::default(), validation_context.clone())
1400 .with_count(5)
1401 .with_base_node(|_node| node_config)
1402 .build()
1403 .unwrap();
1404
1405 assert_eq!(group_config.count, 5);
1407
1408 assert_eq!(group_config.base_config.name(), "node");
1409 assert_eq!(
1410 group_config.base_config.command().unwrap().as_str(),
1411 "some_command"
1412 );
1413 assert_eq!(
1414 group_config.base_config.image().unwrap().as_str(),
1415 "repo:image"
1416 );
1417 assert!(group_config.base_config.is_validator());
1418 assert!(group_config.base_config.is_invulnerable());
1419 assert!(group_config.base_config.is_bootnode());
1420 }
1421
1422 #[test]
1423 fn ensure_default_args_are_overrided() {
1424 let validation_context = Rc::new(RefCell::new(ValidationContext::default()));
1425 let chain_context = ChainDefaultContext {
1426 default_args: vec!["-lruntime=trace".into()],
1427 ..Default::default()
1428 };
1429 let node_config = NodeConfigBuilder::new(chain_context, validation_context)
1430 .with_name("node")
1431 .with_args(vec!["-lruntime=info".into()])
1432 .build()
1433 .unwrap();
1434
1435 assert_eq!(node_config.args, vec!["-lruntime=info".into()]);
1436 }
1437}