1use std::{
8 collections::BTreeMap,
9 fmt::{self, Display},
10 path::Path,
11 str::FromStr,
12};
13
14use anyhow::anyhow;
15use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
16
17use crate::shared::types::AssetLocation;
18
19pub type JamServiceId = u32;
21pub type JamCoreIndex = u16;
23
24pub const JAM_BOOTSTRAP_SERVICE_ID: JamServiceId = 0;
26
27#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
29pub struct JamGenesisConfig {
30 #[serde(default = "default_true", skip_serializing_if = "is_true")]
33 with_defaults: bool,
34 #[serde(default, skip_serializing_if = "Option::is_none")]
36 bootstrap_service: Option<AssetLocation>,
37 #[serde(default, skip_serializing_if = "Option::is_none")]
40 config_file: Option<AssetLocation>,
41 #[serde(default, skip_serializing_if = "Option::is_none")]
43 protocol_parameters: Option<serde_json::Value>,
44 #[serde(
46 default,
47 skip_serializing_if = "BTreeMap::is_empty",
48 with = "string_keyed"
49 )]
50 services: BTreeMap<JamServiceId, JamGenesisService>,
51 #[serde(
53 default,
54 skip_serializing_if = "BTreeMap::is_empty",
55 with = "string_keyed"
56 )]
57 auth_queues: BTreeMap<JamCoreIndex, Vec<JamAuthorizer>>,
58 #[serde(default, skip_serializing_if = "JamGenesisPrivileges::is_empty")]
59 privileges: JamGenesisPrivileges,
60}
61
62impl Default for JamGenesisConfig {
63 fn default() -> Self {
64 Self {
65 with_defaults: true,
66 bootstrap_service: None,
67 config_file: None,
68 protocol_parameters: None,
69 services: BTreeMap::new(),
70 auth_queues: BTreeMap::new(),
71 privileges: JamGenesisPrivileges::default(),
72 }
73 }
74}
75
76impl JamGenesisConfig {
77 pub fn with_defaults(&self) -> bool {
79 self.with_defaults
80 }
81
82 pub fn bootstrap_service(&self) -> Option<&AssetLocation> {
84 self.bootstrap_service.as_ref()
85 }
86
87 pub fn config_file(&self) -> Option<&AssetLocation> {
89 self.config_file.as_ref()
90 }
91
92 pub fn protocol_parameters(&self) -> Option<&serde_json::Value> {
94 self.protocol_parameters.as_ref()
95 }
96
97 pub fn services(&self) -> &BTreeMap<JamServiceId, JamGenesisService> {
99 &self.services
100 }
101
102 pub fn auth_queues(&self) -> &BTreeMap<JamCoreIndex, Vec<JamAuthorizer>> {
104 &self.auth_queues
105 }
106
107 pub fn privileges(&self) -> &JamGenesisPrivileges {
109 &self.privileges
110 }
111
112 pub fn asset_locations(&self) -> Vec<&AssetLocation> {
114 let mut locations: Vec<&AssetLocation> = self
115 .bootstrap_service
116 .iter()
117 .chain(self.config_file.iter())
118 .collect();
119 for service in self.services.values() {
120 locations.push(&service.code);
121 locations.extend(service.preimages.iter());
122 }
123 for authorizer in self.auth_queues.values().flatten() {
124 if let JamAuthorizer::Code { code, .. } = authorizer {
125 locations.push(code);
126 }
127 }
128 locations
129 }
130
131 pub(crate) fn resolve_relative_paths(&mut self, base_dir: &Path) {
133 let resolve = |location: &mut AssetLocation| {
134 if let AssetLocation::FilePath(path) = location {
135 if path.is_relative() {
136 *path = base_dir.join(&*path);
137 }
138 }
139 };
140 self.bootstrap_service.iter_mut().for_each(resolve);
141 self.config_file.iter_mut().for_each(resolve);
142 for service in self.services.values_mut() {
143 resolve(&mut service.code);
144 service.preimages.iter_mut().for_each(resolve);
145 }
146 for authorizer in self.auth_queues.values_mut().flatten() {
147 if let JamAuthorizer::Code { code, .. } = authorizer {
148 resolve(code);
149 }
150 }
151 }
152}
153
154#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
156pub struct JamGenesisService {
157 code: AssetLocation,
159 #[serde(default, skip_serializing_if = "JamBalance::is_minimum")]
161 balance: JamBalance,
162 #[serde(default, skip_serializing_if = "is_zero")]
164 min_item_gas: u64,
165 #[serde(default, skip_serializing_if = "is_zero")]
167 min_memo_gas: u64,
168 #[serde(default, skip_serializing_if = "JamAmount::is_zero")]
170 deposit_offset: JamAmount,
171 #[serde(default, skip_serializing_if = "Vec::is_empty")]
173 preimages: Vec<AssetLocation>,
174 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
176 storage: BTreeMap<JamBytes, JamBytes>,
177}
178
179impl JamGenesisService {
180 pub fn code(&self) -> &AssetLocation {
181 &self.code
182 }
183
184 pub fn balance(&self) -> JamBalance {
185 self.balance
186 }
187
188 pub fn min_item_gas(&self) -> u64 {
189 self.min_item_gas
190 }
191
192 pub fn min_memo_gas(&self) -> u64 {
193 self.min_memo_gas
194 }
195
196 pub fn deposit_offset(&self) -> u64 {
197 self.deposit_offset.0
198 }
199
200 pub fn preimages(&self) -> &[AssetLocation] {
201 &self.preimages
202 }
203
204 pub fn storage(&self) -> &BTreeMap<JamBytes, JamBytes> {
205 &self.storage
206 }
207}
208
209#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
211#[serde(default)]
212pub struct JamGenesisPrivileges {
213 #[serde(alias = "bless", skip_serializing_if = "is_zero_u32")]
215 manager: JamServiceId,
216 #[serde(alias = "designate", skip_serializing_if = "is_zero_u32")]
218 delegator: JamServiceId,
219 #[serde(alias = "register", skip_serializing_if = "is_zero_u32")]
221 registrar: JamServiceId,
222 #[serde(skip_serializing_if = "BTreeMap::is_empty", with = "string_keyed")]
224 assign: BTreeMap<JamCoreIndex, JamServiceId>,
225 #[serde(skip_serializing_if = "BTreeMap::is_empty", with = "string_keyed")]
227 always_acc: BTreeMap<JamServiceId, u64>,
228}
229
230impl JamGenesisPrivileges {
231 pub fn manager(&self) -> JamServiceId {
232 self.manager
233 }
234
235 pub fn delegator(&self) -> JamServiceId {
236 self.delegator
237 }
238
239 pub fn registrar(&self) -> JamServiceId {
240 self.registrar
241 }
242
243 pub fn assign(&self) -> &BTreeMap<JamCoreIndex, JamServiceId> {
244 &self.assign
245 }
246
247 pub fn always_acc(&self) -> &BTreeMap<JamServiceId, u64> {
248 &self.always_acc
249 }
250
251 fn is_empty(&self) -> bool {
252 self == &Self::default()
253 }
254}
255
256#[derive(Debug, Clone, Copy, PartialEq, Eq)]
261pub enum JamBalance {
262 Exact(u64),
264 MinimumPlus(u64),
266}
267
268impl Default for JamBalance {
269 fn default() -> Self {
270 Self::MinimumPlus(0)
271 }
272}
273
274impl JamBalance {
275 fn is_minimum(&self) -> bool {
276 self == &Self::MinimumPlus(0)
277 }
278}
279
280impl From<u64> for JamBalance {
281 fn from(balance: u64) -> Self {
282 Self::Exact(balance)
283 }
284}
285
286impl FromStr for JamBalance {
287 type Err = anyhow::Error;
288
289 fn from_str(s: &str) -> Result<Self, Self::Err> {
290 let s = s.trim();
291 if s == "min" {
292 return Ok(Self::MinimumPlus(0));
293 }
294 if let Some(extra) = s.strip_prefix("min+") {
295 return Ok(Self::MinimumPlus(JamAmount::from_str(extra.trim())?.0));
296 }
297 Ok(Self::Exact(JamAmount::from_str(s)?.0))
298 }
299}
300
301impl Display for JamBalance {
302 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
303 match self {
304 Self::Exact(balance) => write!(f, "{}", JamAmount(*balance)),
305 Self::MinimumPlus(0) => write!(f, "min"),
306 Self::MinimumPlus(extra) => write!(f, "min+{}", JamAmount(*extra)),
307 }
308 }
309}
310
311impl Serialize for JamBalance {
312 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
313 match self {
314 Self::Exact(balance) => JamAmount(*balance).serialize(serializer),
315 other => serializer.serialize_str(&other.to_string()),
316 }
317 }
318}
319
320impl<'de> Deserialize<'de> for JamBalance {
321 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
322 deserializer.deserialize_any(NumberOrStrVisitor::<Self>::new(
323 "a balance: an integer, \"max\", \"min\" or \"min+<amount>\"",
324 ))
325 }
326}
327
328#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
331pub struct JamAmount(pub u64);
332
333impl JamAmount {
334 fn is_zero(&self) -> bool {
335 self.0 == 0
336 }
337}
338
339impl FromStr for JamAmount {
340 type Err = anyhow::Error;
341
342 fn from_str(s: &str) -> Result<Self, Self::Err> {
343 if s == "max" {
344 return Ok(Self(u64::MAX));
345 }
346 s.replace('_', "")
347 .parse()
348 .map(Self)
349 .map_err(|e| anyhow!("'{s}' is not an amount: {e}"))
350 }
351}
352
353impl From<u64> for JamAmount {
354 fn from(value: u64) -> Self {
355 Self(value)
356 }
357}
358
359impl Display for JamAmount {
360 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
361 if self.0 == u64::MAX {
362 write!(f, "max")
363 } else {
364 write!(f, "{}", self.0)
365 }
366 }
367}
368
369impl Serialize for JamAmount {
370 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
371 if self.0 <= i64::MAX as u64 {
373 serializer.serialize_u64(self.0)
374 } else {
375 serializer.serialize_str(&self.to_string())
376 }
377 }
378}
379
380impl<'de> Deserialize<'de> for JamAmount {
381 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
382 deserializer.deserialize_any(NumberOrStrVisitor::<Self>::new(
383 "an amount: an integer or \"max\"",
384 ))
385 }
386}
387
388struct NumberOrStrVisitor<T> {
390 expecting: &'static str,
391 _marker: std::marker::PhantomData<T>,
392}
393
394impl<T> NumberOrStrVisitor<T> {
395 fn new(expecting: &'static str) -> Self {
396 Self {
397 expecting,
398 _marker: std::marker::PhantomData,
399 }
400 }
401}
402
403impl<T> de::Visitor<'_> for NumberOrStrVisitor<T>
404where
405 T: From<u64> + FromStr<Err = anyhow::Error>,
406{
407 type Value = T;
408
409 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
410 formatter.write_str(self.expecting)
411 }
412
413 fn visit_u64<E: de::Error>(self, v: u64) -> Result<T, E> {
414 Ok(T::from(v))
415 }
416
417 fn visit_i64<E: de::Error>(self, v: i64) -> Result<T, E> {
418 u64::try_from(v)
419 .map(T::from)
420 .map_err(|_| E::custom(format!("{v} is negative")))
421 }
422
423 fn visit_str<E: de::Error>(self, v: &str) -> Result<T, E> {
424 T::from_str(v).map_err(E::custom)
425 }
426}
427
428#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
430pub struct JamBytes(pub Vec<u8>);
431
432impl JamBytes {
433 pub fn as_bytes(&self) -> &[u8] {
434 &self.0
435 }
436}
437
438impl From<Vec<u8>> for JamBytes {
439 fn from(bytes: Vec<u8>) -> Self {
440 Self(bytes)
441 }
442}
443
444impl From<&[u8]> for JamBytes {
445 fn from(bytes: &[u8]) -> Self {
446 Self(bytes.to_vec())
447 }
448}
449
450impl<const N: usize> From<&[u8; N]> for JamBytes {
451 fn from(bytes: &[u8; N]) -> Self {
452 Self(bytes.to_vec())
453 }
454}
455
456impl<const N: usize> From<[u8; N]> for JamBytes {
457 fn from(bytes: [u8; N]) -> Self {
458 Self(bytes.to_vec())
459 }
460}
461
462impl FromStr for JamBytes {
463 type Err = anyhow::Error;
464
465 fn from_str(s: &str) -> Result<Self, Self::Err> {
466 let digits = s.strip_prefix("0x").unwrap_or(s);
467 hex::decode(digits)
468 .map(Self)
469 .map_err(|e| anyhow!("'{s}' is not hex: {e}"))
470 }
471}
472
473impl Display for JamBytes {
474 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
475 write!(f, "0x{}", hex::encode(&self.0))
476 }
477}
478
479impl Serialize for JamBytes {
480 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
481 serializer.serialize_str(&self.to_string())
482 }
483}
484
485impl<'de> Deserialize<'de> for JamBytes {
486 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
487 let s = String::deserialize(deserializer)?;
488 s.parse().map_err(de::Error::custom)
489 }
490}
491
492#[derive(Debug, Clone, PartialEq)]
498pub enum JamAuthorizer {
499 Null,
501 Hash([u8; 32]),
503 Code {
505 code: AssetLocation,
506 config: JamBytes,
507 },
508}
509
510impl JamAuthorizer {
511 pub fn code(code: impl Into<AssetLocation>) -> Self {
513 Self::Code {
514 code: code.into(),
515 config: JamBytes::default(),
516 }
517 }
518
519 pub fn code_with_config(code: impl Into<AssetLocation>, config: impl Into<Vec<u8>>) -> Self {
521 Self::Code {
522 code: code.into(),
523 config: JamBytes(config.into()),
524 }
525 }
526}
527
528#[derive(Serialize, Deserialize)]
529#[serde(untagged)]
530enum JamAuthorizerRepr {
531 Text(String),
532 Code {
533 code: AssetLocation,
534 #[serde(default, skip_serializing_if = "is_empty_bytes")]
535 config: JamBytes,
536 },
537}
538
539impl Serialize for JamAuthorizer {
540 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
541 match self {
542 Self::Null => JamAuthorizerRepr::Text("null".into()),
543 Self::Hash(hash) => JamAuthorizerRepr::Text(JamBytes(hash.to_vec()).to_string()),
544 Self::Code { code, config } => JamAuthorizerRepr::Code {
545 code: code.clone(),
546 config: config.clone(),
547 },
548 }
549 .serialize(serializer)
550 }
551}
552
553impl<'de> Deserialize<'de> for JamAuthorizer {
554 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
555 match JamAuthorizerRepr::deserialize(deserializer).map_err(|_| {
556 de::Error::custom(
557 "an authorizer: \"null\", a 0x-prefixed 32-byte hash, or { code = \"..\", config = \"0x..\" }",
558 )
559 })? {
560 JamAuthorizerRepr::Text(text) if text == "null" => Ok(Self::Null),
561 JamAuthorizerRepr::Text(text) => {
562 let bytes = JamBytes::from_str(&text).map_err(de::Error::custom)?;
563 let hash: [u8; 32] = bytes.0.try_into().map_err(|_| {
564 de::Error::custom(format!("authorizer hash '{text}' is not 32 bytes"))
565 })?;
566 Ok(Self::Hash(hash))
567 },
568 JamAuthorizerRepr::Code { code, config } => Ok(Self::Code { code, config }),
569 }
570 }
571}
572
573pub struct JamGenesisConfigBuilder {
575 config: JamGenesisConfig,
576 errors: Vec<anyhow::Error>,
577}
578
579impl Default for JamGenesisConfigBuilder {
580 fn default() -> Self {
581 Self::new()
582 }
583}
584
585impl JamGenesisConfigBuilder {
586 pub fn new() -> Self {
587 Self {
588 config: JamGenesisConfig::default(),
589 errors: vec![],
590 }
591 }
592
593 pub(crate) fn from_config(config: JamGenesisConfig) -> Self {
595 Self {
596 config,
597 errors: vec![],
598 }
599 }
600
601 pub fn with_bootstrap_service(mut self, location: impl Into<AssetLocation>) -> Self {
603 self.config.bootstrap_service = Some(location.into());
604 self
605 }
606
607 pub fn without_defaults(mut self) -> Self {
609 self.config.with_defaults = false;
610 self
611 }
612
613 pub fn with_config_file(mut self, location: impl Into<AssetLocation>) -> Self {
615 self.config.config_file = Some(location.into());
616 self
617 }
618
619 pub fn with_protocol_parameters(mut self, parameters: impl Into<serde_json::Value>) -> Self {
621 let parameters = parameters.into();
622 if parameters.is_object() {
623 self.config.protocol_parameters = Some(parameters);
624 } else {
625 self.errors.push(anyhow!(
626 "protocol_parameters: must be an object with every parameter"
627 ));
628 }
629 self
630 }
631
632 pub fn with_service(
634 mut self,
635 id: JamServiceId,
636 f: impl FnOnce(JamGenesisServiceBuilder) -> JamGenesisServiceBuilder,
637 ) -> Self {
638 match f(JamGenesisServiceBuilder::new()).build() {
639 Ok(service) => {
640 self.config.services.insert(id, service);
641 },
642 Err(errors) => self.errors.extend(
643 errors
644 .into_iter()
645 .map(|error| anyhow!("services[{id}].{error}")),
646 ),
647 }
648 self
649 }
650
651 pub fn with_auth_queue(
653 mut self,
654 core: JamCoreIndex,
655 authorizers: impl IntoIterator<Item = JamAuthorizer>,
656 ) -> Self {
657 self.config
658 .auth_queues
659 .insert(core, authorizers.into_iter().collect());
660 self
661 }
662
663 pub fn with_assigner(
665 mut self,
666 cores: impl IntoIterator<Item = JamCoreIndex>,
667 id: JamServiceId,
668 ) -> Self {
669 for core in cores {
670 self.config.privileges.assign.insert(core, id);
671 }
672 self
673 }
674
675 pub fn with_manager(mut self, id: JamServiceId) -> Self {
677 self.config.privileges.manager = id;
678 self
679 }
680
681 pub fn with_delegator(mut self, id: JamServiceId) -> Self {
683 self.config.privileges.delegator = id;
684 self
685 }
686
687 pub fn with_registrar(mut self, id: JamServiceId) -> Self {
689 self.config.privileges.registrar = id;
690 self
691 }
692
693 pub fn with_always_acc(mut self, id: JamServiceId, gas: u64) -> Self {
695 self.config.privileges.always_acc.insert(id, gas);
696 self
697 }
698
699 pub fn build(self) -> Result<JamGenesisConfig, Vec<anyhow::Error>> {
700 if self.errors.is_empty() {
701 Ok(self.config)
702 } else {
703 Err(self.errors)
704 }
705 }
706}
707
708pub struct JamGenesisServiceBuilder {
710 code: Option<AssetLocation>,
711 service: JamGenesisService,
712}
713
714impl JamGenesisServiceBuilder {
715 fn new() -> Self {
716 Self {
717 code: None,
718 service: JamGenesisService {
719 code: AssetLocation::FilePath(Default::default()),
720 balance: JamBalance::default(),
721 min_item_gas: 0,
722 min_memo_gas: 0,
723 deposit_offset: JamAmount::default(),
724 preimages: vec![],
725 storage: BTreeMap::new(),
726 },
727 }
728 }
729
730 pub fn with_code(mut self, location: impl Into<AssetLocation>) -> Self {
732 self.code = Some(location.into());
733 self
734 }
735
736 pub fn with_balance(mut self, balance: impl Into<JamBalance>) -> Self {
738 self.service.balance = balance.into();
739 self
740 }
741
742 pub fn with_min_item_gas(mut self, gas: u64) -> Self {
744 self.service.min_item_gas = gas;
745 self
746 }
747
748 pub fn with_min_memo_gas(mut self, gas: u64) -> Self {
750 self.service.min_memo_gas = gas;
751 self
752 }
753
754 pub fn with_deposit_offset(mut self, offset: u64) -> Self {
756 self.service.deposit_offset = JamAmount(offset);
757 self
758 }
759
760 pub fn with_preimage(mut self, location: impl Into<AssetLocation>) -> Self {
762 self.service.preimages.push(location.into());
763 self
764 }
765
766 pub fn with_storage(mut self, key: impl Into<Vec<u8>>, value: impl Into<Vec<u8>>) -> Self {
768 self.service
769 .storage
770 .insert(JamBytes(key.into()), JamBytes(value.into()));
771 self
772 }
773
774 fn build(self) -> Result<JamGenesisService, Vec<anyhow::Error>> {
775 match self.code {
776 Some(code) => Ok(JamGenesisService {
777 code,
778 ..self.service
779 }),
780 None => Err(vec![anyhow!("code: a service needs its code")]),
781 }
782 }
783}
784
785fn default_true() -> bool {
786 true
787}
788
789fn is_true(value: &bool) -> bool {
790 *value
791}
792
793fn is_zero(value: &u64) -> bool {
794 *value == 0
795}
796
797fn is_zero_u32(value: &u32) -> bool {
798 *value == 0
799}
800
801fn is_empty_bytes(value: &JamBytes) -> bool {
802 value.0.is_empty()
803}
804
805mod string_keyed {
807 use std::{collections::BTreeMap, fmt::Display, str::FromStr};
808
809 use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
810
811 pub fn serialize<K, V, S>(map: &BTreeMap<K, V>, serializer: S) -> Result<S::Ok, S::Error>
812 where
813 K: Display,
814 V: Serialize,
815 S: Serializer,
816 {
817 map.iter()
818 .map(|(k, v)| (k.to_string(), v))
819 .collect::<BTreeMap<_, _>>()
820 .serialize(serializer)
821 }
822
823 pub fn deserialize<'de, K, V, D>(deserializer: D) -> Result<BTreeMap<K, V>, D::Error>
824 where
825 K: FromStr + Ord,
826 K::Err: Display,
827 V: Deserialize<'de>,
828 D: Deserializer<'de>,
829 {
830 BTreeMap::<String, V>::deserialize(deserializer)?
831 .into_iter()
832 .map(|(k, v)| {
833 k.parse()
834 .map(|k| (k, v))
835 .map_err(|e| de::Error::custom(format!("key '{k}': {e}")))
836 })
837 .collect()
838 }
839}
840
841#[cfg(test)]
842mod tests {
843 use super::*;
844
845 const TOML: &str = r#"
846bootstrap_service = "/blobs/bootstrap.jam"
847
848[services.5]
849code = "/blobs/my-service.jam"
850balance = "min+1000000"
851min_item_gas = 10
852deposit_offset = "max"
853preimages = ["https://example.com/auth.jam"]
854storage = { "0x6772656574696e67" = "0x68656c6c6f" }
855
856[services.6]
857code = "/blobs/other.jam"
858balance = "18446744073709551615"
859
860[auth_queues]
8610 = [{ code = "/blobs/auth.jam", config = "0x0102" }]
8621 = ["null", "0x0101010101010101010101010101010101010101010101010101010101010101"]
863
864[privileges]
865bless = 5
866assign = { 0 = 5 }
867always_acc = { 5 = 1000 }
868"#;
869
870 #[test]
871 fn a_genesis_is_read_from_toml() {
872 let genesis: JamGenesisConfig = toml::from_str(TOML).unwrap();
873
874 assert!(genesis.with_defaults());
875 assert_eq!(
876 genesis.bootstrap_service(),
877 Some(&AssetLocation::from("/blobs/bootstrap.jam"))
878 );
879 let service = &genesis.services()[&5];
880 assert_eq!(service.balance(), JamBalance::MinimumPlus(1_000_000));
881 assert_eq!(service.min_item_gas(), 10);
882 assert_eq!(service.deposit_offset(), u64::MAX);
883 assert_eq!(
884 service.storage()[&JamBytes(b"greeting".to_vec())],
885 JamBytes(b"hello".to_vec())
886 );
887 assert_eq!(
888 genesis.services()[&6].balance(),
889 JamBalance::Exact(u64::MAX)
890 );
891 assert_eq!(
892 genesis.auth_queues()[&0],
893 vec![JamAuthorizer::code_with_config("/blobs/auth.jam", [1, 2])]
894 );
895 assert_eq!(
896 genesis.auth_queues()[&1],
897 vec![JamAuthorizer::Null, JamAuthorizer::Hash([1; 32])]
898 );
899 assert_eq!(genesis.privileges().manager(), 5);
900 assert_eq!(genesis.privileges().assign()[&0], 5);
901 assert_eq!(genesis.privileges().always_acc()[&5], 1000);
902 }
903
904 #[test]
905 fn a_genesis_round_trips_through_toml_and_json() {
906 let genesis: JamGenesisConfig = toml::from_str(TOML).unwrap();
907
908 let again: JamGenesisConfig = toml::from_str(&toml::to_string(&genesis).unwrap()).unwrap();
909 assert_eq!(again, genesis);
910
911 let again: JamGenesisConfig =
912 serde_json::from_str(&serde_json::to_string(&genesis).unwrap()).unwrap();
913 assert_eq!(again, genesis);
914 }
915
916 #[test]
917 fn an_empty_genesis_is_the_default() {
918 let genesis: JamGenesisConfig = toml::from_str("").unwrap();
919 assert_eq!(genesis, JamGenesisConfig::default());
920 assert!(genesis.with_defaults());
921 assert_eq!(toml::to_string(&genesis).unwrap(), "");
922 }
923
924 #[test]
925 fn balances_are_parsed() {
926 for (text, expected) in [
927 ("1000", JamBalance::Exact(1000)),
928 ("1_000", JamBalance::Exact(1000)),
929 ("max", JamBalance::Exact(u64::MAX)),
930 ("min", JamBalance::MinimumPlus(0)),
931 ("min+7", JamBalance::MinimumPlus(7)),
932 ("min+max", JamBalance::MinimumPlus(u64::MAX)),
933 ] {
934 assert_eq!(text.parse::<JamBalance>().unwrap(), expected, "{text}");
935 assert_eq!(
936 expected.to_string().parse::<JamBalance>().unwrap(),
937 expected
938 );
939 }
940 assert!("min-1".parse::<JamBalance>().is_err());
941 assert!("lots".parse::<JamBalance>().is_err());
942 }
943
944 #[test]
945 fn bad_values_are_refused() {
946 for bad in [
947 "[auth_queues]\n0 = [\"0x01\"]",
948 "[auth_queues]\nzero = [\"null\"]",
949 "[services.5]\nbalance = 1",
950 "[services.5]\ncode = \"a.jam\"\nstorage = { \"zz\" = \"0x00\" }",
951 "[services.5]\ncode = \"a.jam\"\nbalance = -1",
952 ] {
953 assert!(
954 toml::from_str::<JamGenesisConfig>(bad).is_err(),
955 "accepted: {bad}"
956 );
957 }
958 }
959
960 #[test]
961 fn the_builder_matches_the_toml() {
962 let built = JamGenesisConfigBuilder::new()
963 .with_bootstrap_service("/blobs/bootstrap.jam")
964 .with_service(5, |s| {
965 s.with_code("/blobs/my-service.jam")
966 .with_balance(JamBalance::MinimumPlus(1_000_000))
967 .with_min_item_gas(10)
968 .with_deposit_offset(u64::MAX)
969 .with_preimage("https://example.com/auth.jam")
970 .with_storage(b"greeting".to_vec(), b"hello".to_vec())
971 })
972 .with_service(6, |s| {
973 s.with_code("/blobs/other.jam").with_balance(u64::MAX)
974 })
975 .with_auth_queue(
976 0,
977 [JamAuthorizer::code_with_config("/blobs/auth.jam", [1, 2])],
978 )
979 .with_auth_queue(1, [JamAuthorizer::Null, JamAuthorizer::Hash([1; 32])])
980 .with_manager(5)
981 .with_assigner([0], 5)
982 .with_always_acc(5, 1000)
983 .build()
984 .unwrap();
985
986 assert_eq!(built, toml::from_str(TOML).unwrap());
987 }
988
989 #[test]
990 fn the_builder_collects_errors() {
991 let errors = JamGenesisConfigBuilder::new()
992 .with_service(5, |s| s.with_min_item_gas(1))
993 .with_protocol_parameters(serde_json::json!("tiny"))
994 .build()
995 .unwrap_err();
996
997 assert_eq!(errors.len(), 2);
998 assert!(errors[0].to_string().contains("services[5].code"));
999 assert!(errors[1].to_string().contains("protocol_parameters"));
1000 }
1001
1002 #[test]
1003 fn relative_paths_are_resolved_against_the_base_dir() {
1004 let mut genesis = JamGenesisConfigBuilder::new()
1005 .with_bootstrap_service("./bootstrap.jam")
1006 .with_service(5, |s| {
1007 s.with_code("svc.jam")
1008 .with_preimage("/abs/pre.jam")
1009 .with_preimage("https://example.com/x.jam")
1010 })
1011 .with_auth_queue(0, [JamAuthorizer::code("auth.jam")])
1012 .build()
1013 .unwrap();
1014
1015 genesis.resolve_relative_paths(Path::new("/net"));
1016
1017 assert_eq!(
1018 genesis.bootstrap_service(),
1019 Some(&AssetLocation::from("/net/./bootstrap.jam"))
1020 );
1021 let service = &genesis.services()[&5];
1022 assert_eq!(service.code(), &AssetLocation::from("/net/svc.jam"));
1023 assert_eq!(service.preimages()[0], AssetLocation::from("/abs/pre.jam"));
1024 assert_eq!(
1025 service.preimages()[1],
1026 AssetLocation::from("https://example.com/x.jam")
1027 );
1028 assert_eq!(
1029 genesis.auth_queues()[&0],
1030 vec![JamAuthorizer::code("/net/auth.jam")]
1031 );
1032 }
1033}