1use std::{cell::RefCell, error::Error, fmt::Debug, marker::PhantomData, rc::Rc};
2
3use serde::{Deserialize, Serialize};
4use support::constants::{DEFAULT_TYPESTATE, THIS_IS_A_BUG};
5
6use crate::{
7 jam_genesis::{JamGenesisConfig, JamGenesisConfigBuilder},
8 shared::{
9 errors::{ConfigError, FieldError},
10 helpers::{merge_errors, merge_errors_vecs},
11 macros::states,
12 node::{self, JamNodeConfig, JamNodeConfigBuilder},
13 resources::{Resources, ResourcesBuilder},
14 types::{
15 Arg, AssetLocation, Chain, ChainDefaultContext, Command, Image, ValidationContext,
16 },
17 },
18 types::{JamNodeMode, JamProtocolParameterType},
19 utils::{default_chain_jam, default_command_jam, default_protocol_para_type_jam},
20};
21#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
23pub struct JamchainConfig {
24 #[serde(default = "default_protocol_para_type_jam")]
26 protocol_params_type: JamProtocolParameterType,
27 #[serde(default = "default_chain_jam")]
29 id: Chain,
30 #[serde(default = "default_command_jam")]
32 default_command: Option<Command>,
33 default_image: Option<Image>,
35 default_resources: Option<Resources>,
37 #[serde(skip_serializing_if = "std::vec::Vec::is_empty", default)]
39 default_args: Vec<Arg>,
40 chain_spec_path: Option<AssetLocation>,
43 #[serde(default, skip_serializing)]
46 chain_spec_command: Option<serde_json::Value>,
47 corevm_monitor_command: Option<Command>,
49 corevm_builder_command: Option<Command>,
51 #[serde(default, skip_serializing)]
53 genesis_overrides: Option<serde_json::Value>,
54 #[serde(default, skip_serializing_if = "Option::is_none")]
56 genesis: Option<JamGenesisConfig>,
57 #[serde(skip_serializing_if = "std::vec::Vec::is_empty", default)]
59 nodes: Vec<JamNodeConfig>,
60}
61
62impl JamchainConfig {
63 pub fn id(&self) -> &Chain {
65 &self.id
66 }
67
68 pub fn protocol_params_type(&self) -> &JamProtocolParameterType {
70 &self.protocol_params_type
71 }
72
73 pub fn default_command(&self) -> Option<&Command> {
75 self.default_command.as_ref()
76 }
77
78 pub fn default_image(&self) -> Option<&Image> {
80 self.default_image.as_ref()
81 }
82
83 pub fn default_resources(&self) -> Option<&Resources> {
85 self.default_resources.as_ref()
86 }
87
88 pub fn default_args(&self) -> Vec<&Arg> {
90 self.default_args.iter().collect::<Vec<&Arg>>()
91 }
92
93 pub fn chain_spec_path(&self) -> Option<&AssetLocation> {
95 self.chain_spec_path.as_ref()
96 }
97
98 pub fn corevm_monitor_command(&self) -> Option<&Command> {
100 self.corevm_monitor_command.as_ref()
101 }
102
103 pub fn corevm_builder_command(&self) -> Option<&Command> {
105 self.corevm_builder_command.as_ref()
106 }
107
108 pub fn genesis(&self) -> Option<&JamGenesisConfig> {
110 self.genesis.as_ref()
111 }
112
113 pub fn nodes(&self) -> Vec<&JamNodeConfig> {
115 self.nodes.iter().collect::<Vec<&JamNodeConfig>>()
116 }
117
118 pub(crate) fn spec_source_errors(&self) -> Vec<anyhow::Error> {
122 let mut errors = vec![];
123 if self.chain_spec_command.is_some() {
124 errors.push(anyhow::anyhow!(
125 "chain_spec_command: removed, the JAM spec is built in process (customize it \
126 with `[jamchain.genesis]`) or given with `chain_spec_path`"
127 ));
128 }
129 if self.genesis_overrides.is_some() {
130 errors.push(anyhow::anyhow!(
131 "genesis_overrides: removed, use `[jamchain.genesis]` (services, auth_queues, \
132 privileges, config_file)"
133 ));
134 }
135 if self.genesis.is_some() && self.chain_spec_path.is_some() {
136 errors.push(anyhow::anyhow!(
137 "genesis: can't be used with `chain_spec_path`, the spec is used as given"
138 ));
139 }
140
141 errors
142 }
143
144 pub(crate) fn resolve_relative_paths(&mut self, base_dir: &std::path::Path) {
146 if let Some(genesis) = self.genesis.as_mut() {
147 genesis.resolve_relative_paths(base_dir);
148 }
149 }
150}
151
152states! {
153 Initial,
154 WithId,
155 WithAtLeastOneNode
156}
157
158pub struct JamchainConfigBuilder<State> {
160 config: JamchainConfig,
161 validation_context: Rc<RefCell<ValidationContext>>,
162 errors: Vec<anyhow::Error>,
163 _state: PhantomData<State>,
164}
165
166impl Default for JamchainConfigBuilder<Initial> {
167 fn default() -> Self {
168 Self {
169 config: JamchainConfig {
170 protocol_params_type: JamProtocolParameterType::Tiny,
171 id: "dev"
172 .try_into()
173 .expect(&format!("{DEFAULT_TYPESTATE} {THIS_IS_A_BUG}")),
174 default_command: Some(
175 "polkajam"
176 .try_into()
177 .expect(&format!("{DEFAULT_TYPESTATE} {THIS_IS_A_BUG}")),
178 ),
179 default_image: None,
180 default_resources: None,
181 default_args: vec![],
182 chain_spec_path: None,
183 chain_spec_command: None,
184 corevm_monitor_command: None,
185 corevm_builder_command: None,
186 genesis_overrides: None,
187 genesis: None,
188 nodes: vec![],
189 },
190 validation_context: Default::default(),
191 errors: vec![],
192 _state: PhantomData,
193 }
194 }
195}
196
197impl<A> JamchainConfigBuilder<A> {
198 fn transition<B>(
199 config: JamchainConfig,
200 validation_context: Rc<RefCell<ValidationContext>>,
201 errors: Vec<anyhow::Error>,
202 ) -> JamchainConfigBuilder<B> {
203 JamchainConfigBuilder {
204 config,
205 validation_context,
206 errors,
207 _state: PhantomData,
208 }
209 }
210
211 fn default_chain_context(&self) -> ChainDefaultContext {
212 ChainDefaultContext {
213 default_command: self.config.default_command.clone(),
214 default_image: self.config.default_image.clone(),
215 default_resources: self.config.default_resources.clone(),
216 default_db_snapshot: None,
217 default_args: self.config.default_args.clone(),
218 }
219 }
220
221 fn create_node_builder<F>(&self, f: F) -> JamNodeConfigBuilder<node::Buildable>
222 where
223 F: FnOnce(JamNodeConfigBuilder<node::Initial>) -> JamNodeConfigBuilder<node::Buildable>,
224 {
225 f(JamNodeConfigBuilder::new(
226 self.default_chain_context(),
227 self.validation_context.clone(),
228 ))
229 }
230
231 pub fn with_genesis(
236 self,
237 f: impl FnOnce(JamGenesisConfigBuilder) -> JamGenesisConfigBuilder,
238 ) -> Self {
239 let builder = match self.config.genesis.clone() {
240 Some(genesis) => JamGenesisConfigBuilder::from_config(genesis),
241 None => JamGenesisConfigBuilder::new(),
242 };
243 match f(builder).build() {
244 Ok(genesis) => Self::transition(
245 JamchainConfig {
246 genesis: Some(genesis),
247 ..self.config
248 },
249 self.validation_context,
250 self.errors,
251 ),
252 Err(errors) => Self::transition(
253 self.config,
254 self.validation_context,
255 merge_errors_vecs(
256 self.errors,
257 errors
258 .into_iter()
259 .map(|error| anyhow::anyhow!("genesis.{error}"))
260 .collect::<Vec<_>>(),
261 ),
262 ),
263 }
264 }
265
266 pub fn with_bootstrap_service(self, location: impl Into<AssetLocation>) -> Self {
269 let location = location.into();
270 self.with_genesis(|genesis| genesis.with_bootstrap_service(location))
271 }
272}
273
274impl JamchainConfigBuilder<Initial> {
275 pub fn new(
276 validation_context: Rc<RefCell<ValidationContext>>,
277 ) -> JamchainConfigBuilder<Initial> {
278 Self {
279 validation_context,
280 ..Self::default()
281 }
282 }
283
284 pub fn with_id<T>(self, chain: T) -> JamchainConfigBuilder<WithId>
286 where
287 T: TryInto<Chain>,
288 T::Error: Error + Send + Sync + 'static,
289 {
290 match chain.try_into() {
291 Ok(id) => Self::transition(
292 JamchainConfig { id, ..self.config },
293 self.validation_context,
294 self.errors,
295 ),
296 Err(error) => Self::transition(
297 self.config,
298 self.validation_context,
299 merge_errors(self.errors, FieldError::Chain(error.into()).into()),
300 ),
301 }
302 }
303}
304
305impl JamchainConfigBuilder<WithId> {
306 pub fn with_default_command<T>(self, command: T) -> Self
308 where
309 T: TryInto<Command>,
310 T::Error: Error + Send + Sync + 'static,
311 {
312 match command.try_into() {
313 Ok(command) => Self::transition(
314 JamchainConfig {
315 default_command: Some(command),
316 ..self.config
317 },
318 self.validation_context,
319 self.errors,
320 ),
321 Err(error) => Self::transition(
322 self.config,
323 self.validation_context,
324 merge_errors(self.errors, FieldError::DefaultCommand(error.into()).into()),
325 ),
326 }
327 }
328
329 pub fn with_default_image<T>(self, image: T) -> Self
331 where
332 T: TryInto<Image>,
333 T::Error: Error + Send + Sync + 'static,
334 {
335 match image.try_into() {
336 Ok(image) => Self::transition(
337 JamchainConfig {
338 default_image: Some(image),
339 ..self.config
340 },
341 self.validation_context,
342 self.errors,
343 ),
344 Err(error) => Self::transition(
345 self.config,
346 self.validation_context,
347 merge_errors(self.errors, FieldError::DefaultImage(error.into()).into()),
348 ),
349 }
350 }
351
352 pub fn with_default_resources(
354 self,
355 f: impl FnOnce(ResourcesBuilder) -> ResourcesBuilder,
356 ) -> Self {
357 match f(ResourcesBuilder::new()).build() {
358 Ok(default_resources) => Self::transition(
359 JamchainConfig {
360 default_resources: Some(default_resources),
361 ..self.config
362 },
363 self.validation_context,
364 self.errors,
365 ),
366 Err(errors) => Self::transition(
367 self.config,
368 self.validation_context,
369 merge_errors_vecs(
370 self.errors,
371 errors
372 .into_iter()
373 .map(|error| FieldError::DefaultResources(error).into())
374 .collect::<Vec<_>>(),
375 ),
376 ),
377 }
378 }
379
380 pub fn with_default_args(self, args: Vec<Arg>) -> Self {
382 Self::transition(
383 JamchainConfig {
384 default_args: args,
385 ..self.config
386 },
387 self.validation_context,
388 self.errors,
389 )
390 }
391
392 pub fn with_chain_spec_path(self, location: impl Into<AssetLocation>) -> Self {
394 Self::transition(
395 JamchainConfig {
396 chain_spec_path: Some(location.into()),
397 ..self.config
398 },
399 self.validation_context,
400 self.errors,
401 )
402 }
403
404 pub fn with_corevm_monitor_command<T>(self, command: T) -> Self
406 where
407 T: TryInto<Command>,
408 T::Error: Error + Send + Sync + 'static,
409 {
410 match command.try_into() {
411 Ok(command) => Self::transition(
412 JamchainConfig {
413 corevm_monitor_command: Some(command),
414 ..self.config
415 },
416 self.validation_context,
417 self.errors,
418 ),
419 Err(error) => Self::transition(
420 self.config,
421 self.validation_context,
422 merge_errors(self.errors, FieldError::DefaultCommand(error.into()).into()),
423 ),
424 }
425 }
426
427 pub fn with_corevm_builder_command<T>(self, command: T) -> Self
429 where
430 T: TryInto<Command>,
431 T::Error: Error + Send + Sync + 'static,
432 {
433 match command.try_into() {
434 Ok(command) => Self::transition(
435 JamchainConfig {
436 corevm_builder_command: Some(command),
437 ..self.config
438 },
439 self.validation_context,
440 self.errors,
441 ),
442 Err(error) => Self::transition(
443 self.config,
444 self.validation_context,
445 merge_errors(self.errors, FieldError::DefaultCommand(error.into()).into()),
446 ),
447 }
448 }
449
450 pub fn with_validator(
453 self,
454 f: impl FnOnce(JamNodeConfigBuilder<node::Initial>) -> JamNodeConfigBuilder<node::Buildable>,
455 ) -> JamchainConfigBuilder<WithAtLeastOneNode> {
456 match self
457 .create_node_builder(f)
458 .with_mode(JamNodeMode::Validator)
459 .build()
460 {
461 Ok(node) => Self::transition(
462 JamchainConfig {
463 nodes: [self.config.nodes, vec![node]].concat(),
464 ..self.config
465 },
466 self.validation_context,
467 self.errors,
468 ),
469 Err((name, errors)) => Self::transition(
470 self.config,
471 self.validation_context,
472 merge_errors_vecs(
473 self.errors,
474 errors
475 .into_iter()
476 .map(|error| ConfigError::Node(name.clone(), error).into())
477 .collect::<Vec<_>>(),
478 ),
479 ),
480 }
481 }
482
483 pub fn with_ordinary(
485 self,
486 f: impl FnOnce(JamNodeConfigBuilder<node::Initial>) -> JamNodeConfigBuilder<node::Buildable>,
487 ) -> JamchainConfigBuilder<WithAtLeastOneNode> {
488 match self
489 .create_node_builder(f)
490 .with_mode(JamNodeMode::Ordinary)
491 .build()
492 {
493 Ok(node) => Self::transition(
494 JamchainConfig {
495 nodes: [self.config.nodes, vec![node]].concat(),
496 ..self.config
497 },
498 self.validation_context,
499 self.errors,
500 ),
501 Err((name, errors)) => Self::transition(
502 self.config,
503 self.validation_context,
504 merge_errors_vecs(
505 self.errors,
506 errors
507 .into_iter()
508 .map(|error| ConfigError::Node(name.clone(), error).into())
509 .collect::<Vec<_>>(),
510 ),
511 ),
512 }
513 }
514
515 pub fn with_proxy(
517 self,
518 f: impl FnOnce(JamNodeConfigBuilder<node::Initial>) -> JamNodeConfigBuilder<node::Buildable>,
519 ) -> JamchainConfigBuilder<WithAtLeastOneNode> {
520 match self
521 .create_node_builder(f)
522 .with_mode(JamNodeMode::Proxy)
523 .build()
524 {
525 Ok(node) => Self::transition(
526 JamchainConfig {
527 nodes: [self.config.nodes, vec![node]].concat(),
528 ..self.config
529 },
530 self.validation_context,
531 self.errors,
532 ),
533 Err((name, errors)) => Self::transition(
534 self.config,
535 self.validation_context,
536 merge_errors_vecs(
537 self.errors,
538 errors
539 .into_iter()
540 .map(|error| ConfigError::Node(name.clone(), error).into())
541 .collect::<Vec<_>>(),
542 ),
543 ),
544 }
545 }
546
547 }
568
569impl JamchainConfigBuilder<WithAtLeastOneNode> {
570 pub fn with_validator(
573 self,
574 f: impl FnOnce(JamNodeConfigBuilder<node::Initial>) -> JamNodeConfigBuilder<node::Buildable>,
575 ) -> JamchainConfigBuilder<WithAtLeastOneNode> {
576 match self
577 .create_node_builder(f)
578 .with_mode(JamNodeMode::Validator)
579 .build()
580 {
581 Ok(node) => Self::transition(
582 JamchainConfig {
583 nodes: [self.config.nodes, vec![node]].concat(),
584 ..self.config
585 },
586 self.validation_context,
587 self.errors,
588 ),
589 Err((name, errors)) => Self::transition(
590 self.config,
591 self.validation_context,
592 merge_errors_vecs(
593 self.errors,
594 errors
595 .into_iter()
596 .map(|error| ConfigError::Node(name.clone(), error).into())
597 .collect::<Vec<_>>(),
598 ),
599 ),
600 }
601 }
602
603 pub fn with_ordinary(
605 self,
606 f: impl FnOnce(JamNodeConfigBuilder<node::Initial>) -> JamNodeConfigBuilder<node::Buildable>,
607 ) -> JamchainConfigBuilder<WithAtLeastOneNode> {
608 match self
609 .create_node_builder(f)
610 .with_mode(JamNodeMode::Ordinary)
611 .build()
612 {
613 Ok(node) => Self::transition(
614 JamchainConfig {
615 nodes: [self.config.nodes, vec![node]].concat(),
616 ..self.config
617 },
618 self.validation_context,
619 self.errors,
620 ),
621 Err((name, errors)) => Self::transition(
622 self.config,
623 self.validation_context,
624 merge_errors_vecs(
625 self.errors,
626 errors
627 .into_iter()
628 .map(|error| ConfigError::Node(name.clone(), error).into())
629 .collect::<Vec<_>>(),
630 ),
631 ),
632 }
633 }
634
635 pub fn with_proxy(
637 self,
638 f: impl FnOnce(JamNodeConfigBuilder<node::Initial>) -> JamNodeConfigBuilder<node::Buildable>,
639 ) -> JamchainConfigBuilder<WithAtLeastOneNode> {
640 match self
641 .create_node_builder(f)
642 .with_mode(JamNodeMode::Proxy)
643 .build()
644 {
645 Ok(node) => Self::transition(
646 JamchainConfig {
647 nodes: [self.config.nodes, vec![node]].concat(),
648 ..self.config
649 },
650 self.validation_context,
651 self.errors,
652 ),
653 Err((name, errors)) => Self::transition(
654 self.config,
655 self.validation_context,
656 merge_errors_vecs(
657 self.errors,
658 errors
659 .into_iter()
660 .map(|error| ConfigError::Node(name.clone(), error).into())
661 .collect::<Vec<_>>(),
662 ),
663 ),
664 }
665 }
666
667 pub fn build(self) -> Result<JamchainConfig, Vec<anyhow::Error>> {
669 let errors = merge_errors_vecs(self.errors, self.config.spec_source_errors());
670 if !errors.is_empty() {
671 return Err(errors
672 .into_iter()
673 .map(|error| ConfigError::Jamchain(error).into())
674 .collect::<Vec<_>>());
675 }
676
677 Ok(self.config)
678 }
679}
680
681#[cfg(test)]
682mod tests {
683 use super::*;
684
685 fn chain() -> JamchainConfigBuilder<WithId> {
686 JamchainConfigBuilder::new(Default::default()).with_id("dev")
687 }
688
689 #[test]
690 fn the_genesis_is_absent_by_default() {
691 let config = chain()
692 .with_validator(|node| node.with_name("jam0"))
693 .build()
694 .expect("the chain config builds");
695
696 assert_eq!(config.genesis(), None);
697 }
698
699 #[test]
701 fn the_genesis_is_built_up_across_calls() {
702 let config = chain()
703 .with_bootstrap_service("/blobs/bootstrap.jam")
704 .with_genesis(|g| g.with_service(5, |s| s.with_code("/blobs/svc.jam")))
705 .with_validator(|node| node.with_name("jam0"))
706 .with_genesis(|g| g.with_assigner([0], 5))
707 .build()
708 .expect("the chain config builds");
709
710 let genesis = config.genesis().expect("the genesis is set");
711 assert_eq!(
712 genesis.bootstrap_service(),
713 Some(&AssetLocation::from("/blobs/bootstrap.jam"))
714 );
715 assert!(genesis.services().contains_key(&5));
716 assert_eq!(genesis.privileges().assign()[&0], 5);
717 }
718
719 #[test]
720 fn genesis_errors_are_reported() {
721 let errors = chain()
722 .with_genesis(|g| g.with_service(5, |s| s.with_min_item_gas(1)))
723 .with_validator(|node| node.with_name("jam0"))
724 .build()
725 .unwrap_err();
726
727 assert_eq!(errors.len(), 1);
728 assert_eq!(
729 errors[0].to_string(),
730 "jamchain.genesis.services[5].code: a service needs its code"
731 );
732 }
733
734 #[test]
737 fn a_genesis_with_a_chain_spec_path_is_refused() {
738 let errors = chain()
739 .with_genesis(|g| g)
740 .with_chain_spec_path("/spec.json")
741 .with_validator(|node| node.with_name("jam0"))
742 .build()
743 .unwrap_err();
744
745 assert!(
746 errors[0]
747 .to_string()
748 .contains("genesis: can't be used with `chain_spec_path`"),
749 "{}",
750 errors[0]
751 );
752 }
753
754 #[test]
755 fn a_chain_spec_path_is_kept_as_given() {
756 let config = chain()
757 .with_chain_spec_path("/spec.json")
758 .with_validator(|node| node.with_name("jam0"))
759 .build()
760 .expect("the chain config builds");
761
762 assert_eq!(
763 config.chain_spec_path(),
764 Some(&AssetLocation::from("/spec.json"))
765 );
766 assert_eq!(config.genesis(), None);
767 }
768}