-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathchain_spec.rs
More file actions
2145 lines (1909 loc) · 73.5 KB
/
Copy pathchain_spec.rs
File metadata and controls
2145 lines (1909 loc) · 73.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::{
collections::HashMap,
path::{Path, PathBuf},
};
use anyhow::anyhow;
use configuration::{
types::{AssetLocation, Chain, ChainSpecRuntime, JsonOverrides, ParaId},
HrmpChannelConfig,
};
use provider::{
constants::NODE_CONFIG_DIR,
types::{GenerateFileCommand, GenerateFilesOptions, TransferedFile},
DynNamespace, ProviderError,
};
use sc_chain_spec::{GenericChainSpec, GenesisConfigBuilderRuntimeCaller};
use serde::{Deserialize, Serialize};
use serde_json::json;
use support::{constants::THIS_IS_A_BUG, fs::FileSystem, replacer::apply_replacements};
use tokio::process::Command;
use tracing::{debug, info, trace, warn};
use super::errors::GeneratorError;
use crate::{
network_spec::{node::NodeSpec, parachain::ParachainSpec, relaychain::RelaychainSpec},
ScopedFilesystem,
};
// TODO: (javier) move to state
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum Context {
Relay,
Para { relay_chain: Chain, para_id: ParaId },
}
/// Posible chain-spec formats
#[derive(Debug, Clone, Copy)]
enum ChainSpecFormat {
Plain,
Raw,
}
/// Key types to replace in spec
#[derive(Debug, Clone, Copy)]
enum KeyType {
Session,
Aura,
Grandpa,
}
#[derive(Debug, Clone, Copy, Default)]
enum SessionKeyType {
// Default derivarion (e.g `//`)
#[default]
Default,
// Stash detivarion (e.g `//<name>/stash`)
Stash,
// EVM session type
Evm,
}
type MaybeExpectedPath = Option<PathBuf>;
/// Represents the different path contexts needed for chain spec generation
struct ChainSpecPaths {
/// Local filesystem path
local: String,
/// Path inside the pod/container
in_pod: String,
/// Path to use in command arguments
in_args: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum CommandInContext {
Local(String, MaybeExpectedPath),
Remote(String, MaybeExpectedPath),
}
impl CommandInContext {
fn cmd(&self) -> &str {
match self {
CommandInContext::Local(cmd, _) | CommandInContext::Remote(cmd, _) => cmd.as_ref(),
}
}
}
#[derive(Debug)]
pub struct ParaGenesisConfig<T: AsRef<Path>> {
pub(crate) state_path: T,
pub(crate) wasm_path: T,
pub(crate) id: u32,
pub(crate) as_parachain: bool,
}
/// Presets to check if is not set by the user.
/// We check if the preset is valid for the runtime in order
/// and if non of them are preset we fallback to the `default config`.
const DEFAULT_PRESETS_TO_CHECK: [&str; 3] = ["local_testnet", "development", "dev"];
/// Chain-spec builder representation
///
/// Multiple options are supported, and the current order is:
/// IF [`asset_location`] is _some_ -> Use this chain_spec by copying the file from [`AssetLocation`]
/// ELSE IF [`runtime_location`] is _some_ -> generate the chain-spec using the sc-chain-spec builder.
/// ELSE -> Fallback to use the `default` or customized cmd.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChainSpec {
// Name of the spec file, most of the times could be the same as the chain_name. (e.g rococo-local)
chain_spec_name: String,
// Location of the chain-spec to use
asset_location: Option<AssetLocation>,
// Location of the runtime to use
runtime: Option<ChainSpecRuntime>,
maybe_plain_path: Option<PathBuf>,
chain_name: Option<String>,
raw_path: Option<PathBuf>,
// The binary to build the chain-spec
command: Option<CommandInContext>,
// Imgae to use for build the chain-spec
image: Option<String>,
// Contex of the network (e.g relay or para)
context: Context,
}
impl ChainSpec {
pub(crate) fn new(chain_spec_name: impl Into<String>, context: Context) -> Self {
Self {
chain_spec_name: chain_spec_name.into(),
chain_name: None,
maybe_plain_path: None,
asset_location: None,
runtime: None,
raw_path: None,
command: None,
image: None,
context,
}
}
pub(crate) fn chain_spec_name(&self) -> &str {
self.chain_spec_name.as_ref()
}
pub(crate) fn chain_name(&self) -> Option<&str> {
self.chain_name.as_deref()
}
pub(crate) fn set_chain_name(mut self, chain_name: impl Into<String>) -> Self {
self.chain_name = Some(chain_name.into());
self
}
pub(crate) fn asset_location(mut self, location: AssetLocation) -> Self {
self.asset_location = Some(location);
self
}
pub(crate) fn runtime(mut self, chain_spec_runtime: ChainSpecRuntime) -> Self {
self.runtime = Some(chain_spec_runtime);
self
}
pub(crate) fn command(
mut self,
command: impl Into<String>,
is_local: bool,
expected_path: Option<&str>,
) -> Self {
let maybe_expected_path = expected_path.map(PathBuf::from);
let cmd = if is_local {
CommandInContext::Local(command.into(), maybe_expected_path)
} else {
CommandInContext::Remote(command.into(), maybe_expected_path)
};
self.command = Some(cmd);
self
}
pub(crate) fn image(mut self, image: Option<String>) -> Self {
self.image = image;
self
}
/// Build the chain-spec
///
/// Chain spec generation flow:
/// if chain_spec_path is set -> use this chain_spec
/// else if runtime_path is set and cmd is compatible with chain-spec-builder -> use the chain-spec-builder
/// else if chain_spec_command is set -> use this cmd for generate the chain_spec
/// else -> use the default command.
pub async fn build<'a, T>(
&mut self,
ns: &DynNamespace,
scoped_fs: &ScopedFilesystem<'a, T>,
) -> Result<(), GeneratorError>
where
T: FileSystem,
{
if self.asset_location.is_none() && self.command.is_none() && self.runtime.is_none() {
return Err(GeneratorError::ChainSpecGeneration(
"Can not build the chain spec without set the command, asset_location or runtime"
.to_string(),
));
}
let maybe_plain_spec_path = PathBuf::from(format!("{}-plain.json", self.chain_spec_name));
// if asset_location is some, then copy the asset to the `base_dir` of the ns with the name `<name>-plain.json`
if let Some(location) = self.asset_location.as_ref() {
let maybe_plain_spec_full_path = scoped_fs.full_path(maybe_plain_spec_path.as_path());
location
.dump_asset(maybe_plain_spec_full_path)
.await
.map_err(|e| {
GeneratorError::ChainSpecGeneration(format!(
"Error {e} dumping location {location:?}"
))
})?;
} else if let Some(runtime) = self.runtime.as_ref() {
trace!(
"Creating chain-spec with runtime from localtion: {}",
runtime.location
);
// First dump the runtime into the ns scoped fs, since we want to easily reproduce
let runtime_file_name = PathBuf::from(format!("{}-runtime.wasm", self.chain_spec_name));
let runtime_path_ns = scoped_fs.full_path(runtime_file_name.as_path());
runtime
.location
.dump_asset(runtime_path_ns)
.await
.map_err(|e| {
GeneratorError::ChainSpecGeneration(format!(
"Error {e} dumping location {:?}",
runtime.location
))
})?;
// list the presets to check if match with the supplied one or one of the defaults
let runtime_code = scoped_fs.read(runtime_file_name.as_path()).await?;
let caller: GenesisConfigBuilderRuntimeCaller =
GenesisConfigBuilderRuntimeCaller::new(&runtime_code[..]);
let presets = caller.preset_names().map_err(|e| {
GeneratorError::ChainSpecGeneration(format!(
"getting default config from runtime should work: {e}"
))
})?;
// check the preset to use with this priorities:
// - IF user provide a preset (and if present) use it
// - else (user don't provide preset or the provided one isn't preset)
// check the [`DEFAULT_PRESETS_TO_CHECK`] in order to find one valid
// - If we can't find any valid preset use the `default config` from the runtime
let preset_to_check = if let Some(preset) = &runtime.preset {
[vec![preset.as_str()], DEFAULT_PRESETS_TO_CHECK.to_vec()].concat()
} else {
DEFAULT_PRESETS_TO_CHECK.to_vec()
};
let preset = preset_to_check
.iter()
.find(|preset| presets.iter().any(|item| item == *preset));
trace!("presets: {:?} - preset to use: {:?}", presets, preset);
let builder = if let Some(preset) = preset {
GenericChainSpec::<()>::builder(&runtime_code[..], ())
.with_genesis_config_preset_name(preset)
} else {
// default config
let default_config = caller.get_default_config().map_err(|e| {
GeneratorError::ChainSpecGeneration(format!(
"getting default config from runtime should work: {e}"
))
})?;
GenericChainSpec::<()>::builder(&runtime_code[..], ())
.with_genesis_config(default_config)
};
let builder = if let Context::Para {
relay_chain: _,
para_id: _,
} = &self.context
{
builder.with_id(self.chain_spec_name())
} else {
builder
};
let builder = if let Some(chain_name) = self.chain_name.as_ref() {
builder.with_name(chain_name)
} else {
builder
};
let chain_spec = builder.build();
let contents = chain_spec.as_json(false).map_err(|e| {
GeneratorError::ChainSpecGeneration(format!(
"getting chain-spec as json should work, err: {e}"
))
})?;
scoped_fs.write(&maybe_plain_spec_path, contents).await?;
} else {
trace!("Creating chain-spec with command");
// we should create the chain-spec using command.
let mut replacement_value = String::default();
if let Some(chain_name) = self.chain_name.as_ref() {
if !chain_name.is_empty() {
replacement_value.clone_from(chain_name);
}
};
// SAFETY: we ensure that command is some with the first check of the fn
// default as empty
let sanitized_cmd = if replacement_value.is_empty() {
// we need to remove the `--chain` flag
self.command.as_ref().unwrap().cmd().replace("--chain", "")
} else {
self.command.as_ref().unwrap().cmd().to_owned()
};
let full_cmd = apply_replacements(
&sanitized_cmd,
&HashMap::from([("chainName", replacement_value.as_str())]),
);
trace!("full_cmd: {:?}", full_cmd);
let parts: Vec<&str> = full_cmd.split_whitespace().collect();
let Some((cmd, args)) = parts.split_first() else {
return Err(GeneratorError::ChainSpecGeneration(format!(
"Invalid generator command: {full_cmd}"
)));
};
trace!("cmd: {:?} - args: {:?}", cmd, args);
let generate_command =
GenerateFileCommand::new(cmd, maybe_plain_spec_path.clone()).args(args);
if let Some(cmd) = &self.command {
match cmd {
CommandInContext::Local(_, expected_path) => {
build_locally(generate_command, scoped_fs, expected_path.as_deref()).await?
},
CommandInContext::Remote(_, expected_path) => {
let options = GenerateFilesOptions::new(
vec![generate_command],
self.image.clone(),
expected_path.clone(),
);
ns.generate_files(options).await?;
},
}
}
}
// check if the _generated_ spec is in raw mode.
if is_raw(maybe_plain_spec_path.clone(), scoped_fs).await? {
let spec_path = PathBuf::from(format!("{}.json", self.chain_spec_name));
let tf_file = TransferedFile::new(
&PathBuf::from_iter([ns.base_dir(), &maybe_plain_spec_path]),
&spec_path,
);
scoped_fs.copy_files(vec![&tf_file]).await.map_err(|e| {
GeneratorError::ChainSpecGeneration(format!(
"Error copying file: {tf_file}, err: {e}"
))
})?;
self.raw_path = Some(spec_path);
} else {
self.maybe_plain_path = Some(maybe_plain_spec_path);
}
Ok(())
}
pub async fn build_raw<'a, T>(
&mut self,
ns: &DynNamespace,
scoped_fs: &ScopedFilesystem<'a, T>,
relay_chain_id: Option<Chain>,
) -> Result<(), GeneratorError>
where
T: FileSystem,
{
warn!("Building raw version from {:?}", self);
// raw path already set, no more work to do here...
let None = self.raw_path else {
return Ok(());
};
// expected raw path
let raw_spec_path = PathBuf::from(format!("{}.json", self.chain_spec_name));
match self
.try_build_raw_with_generic(scoped_fs, relay_chain_id.clone(), raw_spec_path.as_path())
.await
{
Ok(_) => return Ok(()),
Err(err) => {
if Self::should_retry_with_command(&err) && self.command.is_some() {
warn!(
"GenericChainSpec raw generation failed ({}). Falling back to command execution.",
err
);
} else {
return Err(err);
}
},
}
self.build_raw_with_command(ns, scoped_fs, raw_spec_path, relay_chain_id)
.await?;
Ok(())
}
async fn try_build_raw_with_generic<'a, T>(
&mut self,
scoped_fs: &ScopedFilesystem<'a, T>,
relay_chain_id: Option<Chain>,
raw_spec_path: &Path,
) -> Result<(), GeneratorError>
where
T: FileSystem,
{
// `build_raw` is always called after `build`, so `maybe_plain_path` must be set at this point
let (json_content, _) = self.read_spec(scoped_fs).await?;
let json_bytes: Vec<u8> = json_content.as_bytes().into();
let chain_spec = GenericChainSpec::<()>::from_json_bytes(json_bytes).map_err(|e| {
GeneratorError::ChainSpecGeneration(format!(
"Error loading chain-spec from json_bytes, err: {e}"
))
})?;
self.raw_path = Some(raw_spec_path.to_path_buf());
let contents = chain_spec.as_json(true).map_err(|e| {
GeneratorError::ChainSpecGeneration(format!(
"getting chain-spec as json should work, err: {e}"
))
})?;
let contents = self
.ensure_para_fields_in_raw(&contents, relay_chain_id)
.await?;
self.write_spec(scoped_fs, contents).await?;
Ok(())
}
async fn build_raw_with_command<'a, T>(
&mut self,
ns: &DynNamespace,
scoped_fs: &ScopedFilesystem<'a, T>,
raw_spec_path: PathBuf,
relay_chain_id: Option<Chain>,
) -> Result<(), GeneratorError>
where
T: FileSystem,
{
let temp_name = format!(
"temp-build-raw-{}-{}",
self.chain_spec_name,
rand::random::<u8>()
);
let cmd = self.get_command_ref()?;
let maybe_plain_path = self.get_plain_path_ref()?;
let paths = self.resolve_chain_spec_paths(ns, maybe_plain_path, &temp_name);
let generate_command = self.prepare_raw_spec_command(cmd, &paths, raw_spec_path.clone())?;
self.execute_generate_command(
ns,
scoped_fs,
cmd,
generate_command,
&paths,
&temp_name,
)
.await?;
self.finalize_raw_spec(scoped_fs, raw_spec_path, relay_chain_id)
.await?;
Ok(())
}
fn get_command_ref(&self) -> Result<&CommandInContext, GeneratorError> {
self.command
.as_ref()
.ok_or(GeneratorError::ChainSpecGeneration(
"Invalid command".into(),
))
}
fn get_plain_path_ref(&self) -> Result<&PathBuf, GeneratorError> {
self.maybe_plain_path
.as_ref()
.ok_or(GeneratorError::ChainSpecGeneration(
"Invalid plain path".into(),
))
}
fn resolve_chain_spec_paths(
&self,
ns: &DynNamespace,
maybe_plain_path: &PathBuf,
temp_name: &str,
) -> ChainSpecPaths {
let local = format!(
"{}/{}",
ns.base_dir().to_string_lossy(),
maybe_plain_path.display()
);
let in_pod = format!("{}/{}", NODE_CONFIG_DIR, maybe_plain_path.display());
let in_args = if matches!(self.command, Some(CommandInContext::Local(_, _))) {
local.clone()
} else if ns.capabilities().prefix_with_full_path {
format!(
"{}/{}{}",
ns.base_dir().to_string_lossy(),
temp_name,
&in_pod
)
} else {
in_pod.clone()
};
ChainSpecPaths {
local,
in_pod,
in_args,
}
}
fn prepare_raw_spec_command(
&self,
cmd: &CommandInContext,
paths: &ChainSpecPaths,
raw_spec_path: PathBuf,
) -> Result<GenerateFileCommand, GeneratorError> {
let mut full_cmd = apply_replacements(
cmd.cmd(),
&HashMap::from([("chainName", paths.in_args.as_str())]),
);
if !full_cmd.contains("--raw") {
full_cmd = format!("{full_cmd} --raw");
}
trace!("full_cmd: {:?}", full_cmd);
let (program, args) = Self::parse_command_string(&full_cmd)?;
trace!("cmd: {:?} - args: {:?}", program, args);
Ok(GenerateFileCommand::new(program, raw_spec_path).args(&args))
}
fn parse_command_string(full_cmd: &str) -> Result<(&str, Vec<&str>), GeneratorError> {
let parts: Vec<&str> = full_cmd.split_whitespace().collect();
let Some((program, args)) = parts.split_first() else {
return Err(GeneratorError::ChainSpecGeneration(format!(
"Invalid generator command: {full_cmd}"
)));
};
Ok((program, args.to_vec()))
}
async fn execute_generate_command<'a, T>(
&self,
ns: &DynNamespace,
scoped_fs: &ScopedFilesystem<'a, T>,
cmd: &CommandInContext,
generate_command: GenerateFileCommand,
paths: &ChainSpecPaths,
temp_name: &str,
) -> Result<(), GeneratorError>
where
T: FileSystem,
{
match cmd {
CommandInContext::Local(_, expected_path) => {
build_locally(generate_command, scoped_fs, expected_path.as_deref()).await
},
CommandInContext::Remote(_, expected_path) => {
let options = GenerateFilesOptions::with_files(
vec![generate_command],
self.image.clone(),
&[TransferedFile::new(&paths.local, &paths.in_pod)],
expected_path.clone(),
)
.temp_name(temp_name.to_string());
trace!("calling generate_files with options: {:#?}", options);
ns.generate_files(options).await.map_err(Into::into)
},
}
}
async fn finalize_raw_spec<'a, T>(
&mut self,
scoped_fs: &ScopedFilesystem<'a, T>,
raw_spec_path: PathBuf,
relay_chain_id: Option<Chain>,
) -> Result<(), GeneratorError>
where
T: FileSystem,
{
self.raw_path = Some(raw_spec_path);
let (content, _) = self.read_spec(scoped_fs).await?;
let content = self
.ensure_para_fields_in_raw(&content, relay_chain_id)
.await?;
self.write_spec(scoped_fs, content).await?;
Ok(())
}
async fn ensure_para_fields_in_raw(
&mut self,
content: &str,
relay_chain_id: Option<Chain>,
) -> Result<String, GeneratorError> {
if let Context::Para {
relay_chain: _,
para_id,
} = &self.context
{
let mut chain_spec_json: serde_json::Value =
serde_json::from_str(content).map_err(|e| {
GeneratorError::ChainSpecGeneration(format!(
"getting chain-spec as json should work, err: {e}"
))
})?;
let mut needs_write = false;
if chain_spec_json["relay_chain"].is_null() {
chain_spec_json["relay_chain"] = json!(relay_chain_id);
needs_write = true;
}
if chain_spec_json["para_id"].is_null() {
chain_spec_json["para_id"] = json!(para_id);
needs_write = true;
}
if needs_write {
let contents = serde_json::to_string_pretty(&chain_spec_json).map_err(|e| {
GeneratorError::ChainSpecGeneration(format!(
"getting chain-spec json as pretty string should work, err: {e}"
))
})?;
return Ok(contents);
}
}
Ok(content.to_string())
}
fn should_retry_with_command(err: &GeneratorError) -> bool {
match err {
GeneratorError::ChainSpecGeneration(msg) => {
let msg_lower = msg.to_lowercase();
msg_lower.contains("genesisbuilder_get_preset") || msg_lower.contains("_get_preset")
},
_ => false,
}
}
/// Override the :code in chain-spec raw version
pub async fn override_code<'a, T>(
&mut self,
scoped_fs: &ScopedFilesystem<'a, T>,
wasm_override: &AssetLocation,
) -> Result<(), GeneratorError>
where
T: FileSystem,
{
// first ensure we have the raw version of the chain-spec
let Some(_) = self.raw_path else {
return Err(GeneratorError::OverridingWasm(String::from(
"Raw path should be set at this point.",
)));
};
let (content, _) = self.read_spec(scoped_fs).await?;
// read override wasm
let override_content = wasm_override.get_asset().await.map_err(|_| {
GeneratorError::OverridingWasm(format!(
"Can not get asset to override wasm, asset: {wasm_override}"
))
})?;
// read spec to json value
let mut chain_spec_json: serde_json::Value =
serde_json::from_str(&content).map_err(|_| {
GeneratorError::ChainSpecGeneration("Can not parse chain-spec as json".into())
})?;
// override :code
let Some(code) = chain_spec_json.pointer_mut("/genesis/raw/top/0x3a636f6465") else {
return Err(GeneratorError::OverridingWasm(String::from(
"Pointer '/genesis/raw/top/0x3a636f6465' should be valid in the raw spec.",
)));
};
info!(
"🖋 Overriding ':code' (0x3a636f6465) in raw chain-spec with content of {}",
wasm_override
);
*code = json!(format!("0x{}", hex::encode(override_content)));
let overrided_content = serde_json::to_string_pretty(&chain_spec_json).map_err(|_| {
GeneratorError::ChainSpecGeneration("can not parse chain-spec value as json".into())
})?;
// save it
self.write_spec(scoped_fs, overrided_content).await?;
Ok(())
}
pub async fn override_raw_spec<'a, T>(
&mut self,
scoped_fs: &ScopedFilesystem<'a, T>,
raw_spec_overrides: &JsonOverrides,
) -> Result<(), GeneratorError>
where
T: FileSystem,
{
// first ensure we have the raw version of the chain-spec
let Some(_) = self.raw_path else {
return Err(GeneratorError::OverridingRawSpec(String::from(
"Raw path should be set at this point.",
)));
};
let (content, _) = self.read_spec(scoped_fs).await?;
// read overrides to json value
let override_content: serde_json::Value = raw_spec_overrides.get().await.map_err(|_| {
GeneratorError::OverridingRawSpec(format!(
"Can not parse raw_spec_override contents as json: {raw_spec_overrides}"
))
})?;
// read spec to json value
let mut chain_spec_json: serde_json::Value =
serde_json::from_str(&content).map_err(|_| {
GeneratorError::ChainSpecGeneration("Can not parse chain-spec as json".into())
})?;
// merge overrides with existing spec
merge(&mut chain_spec_json, &override_content);
// save changes
let overrided_content = serde_json::to_string_pretty(&chain_spec_json).map_err(|_| {
GeneratorError::ChainSpecGeneration("can not parse chain-spec value as json".into())
})?;
self.write_spec(scoped_fs, overrided_content).await?;
Ok(())
}
pub fn raw_path(&self) -> Option<&Path> {
self.raw_path.as_deref()
}
pub fn set_asset_location(&mut self, location: AssetLocation) {
self.asset_location = Some(location)
}
pub async fn read_chain_id<'a, T>(
&self,
scoped_fs: &ScopedFilesystem<'a, T>,
) -> Result<String, GeneratorError>
where
T: FileSystem,
{
let (content, _) = self.read_spec(scoped_fs).await?;
ChainSpec::chain_id_from_spec(&content)
}
async fn read_spec<'a, T>(
&self,
scoped_fs: &ScopedFilesystem<'a, T>,
) -> Result<(String, ChainSpecFormat), GeneratorError>
where
T: FileSystem,
{
let (path, format) = match (self.maybe_plain_path.as_ref(), self.raw_path.as_ref()) {
(Some(path), None) => (path, ChainSpecFormat::Plain),
(None, Some(path)) => (path, ChainSpecFormat::Raw),
(Some(_), Some(path)) => {
// if we have both paths return the raw
(path, ChainSpecFormat::Raw)
},
(None, None) => unreachable!(),
};
let content = scoped_fs.read_to_string(path.clone()).await.map_err(|_| {
GeneratorError::ChainSpecGeneration(format!(
"Can not read chain-spec from {}",
path.to_string_lossy()
))
})?;
Ok((content, format))
}
async fn write_spec<'a, T>(
&self,
scoped_fs: &ScopedFilesystem<'a, T>,
content: impl Into<String>,
) -> Result<(), GeneratorError>
where
T: FileSystem,
{
let (path, _format) = match (self.maybe_plain_path.as_ref(), self.raw_path.as_ref()) {
(Some(path), None) => (path, ChainSpecFormat::Plain),
(None, Some(path)) => (path, ChainSpecFormat::Raw),
(Some(_), Some(path)) => {
// if we have both paths return the raw
(path, ChainSpecFormat::Raw)
},
(None, None) => unreachable!(),
};
scoped_fs.write(path, content.into()).await.map_err(|_| {
GeneratorError::ChainSpecGeneration(format!(
"Can not write chain-spec from {}",
path.to_string_lossy()
))
})?;
Ok(())
}
// TODO: (javier) move this fns to state aware
pub async fn customize_para<'a, T>(
&self,
para: &ParachainSpec,
relay_chain_id: &str,
scoped_fs: &ScopedFilesystem<'a, T>,
) -> Result<(), GeneratorError>
where
T: FileSystem,
{
let (content, format) = self.read_spec(scoped_fs).await?;
let mut chain_spec_json: serde_json::Value =
serde_json::from_str(&content).map_err(|_| {
GeneratorError::ChainSpecGeneration("Can not parse chain-spec as json".into())
})?;
if let Some(para_id) = chain_spec_json.get_mut("para_id") {
*para_id = json!(para.id);
};
if let Some(para_id) = chain_spec_json.get_mut("paraId") {
*para_id = json!(para.id);
};
if let Some(relay_chain_id_field) = chain_spec_json.get_mut("relay_chain") {
*relay_chain_id_field = json!(relay_chain_id);
};
if let ChainSpecFormat::Plain = format {
let pointer = get_runtime_config_pointer(&chain_spec_json)
.map_err(GeneratorError::ChainSpecGeneration)?;
// make genesis overrides first.
if let Some(overrides) = ¶.genesis_overrides {
let percolated_overrides = percolate_overrides(&pointer, overrides)
.map_err(|e| GeneratorError::ChainSpecGeneration(e.to_string()))?;
if let Some(genesis) = chain_spec_json.pointer_mut(&pointer) {
merge(genesis, percolated_overrides);
}
}
clear_authorities(&pointer, &mut chain_spec_json, &self.context);
let key_type_to_use = if para.is_evm_based {
SessionKeyType::Evm
} else {
SessionKeyType::Default
};
// Get validators to add as authorities
let validators: Vec<&NodeSpec> = para
.collators
.iter()
.filter(|node| node.is_validator)
.collect();
// check chain key types
if chain_spec_json
.pointer(&format!("{pointer}/session"))
.is_some()
{
add_authorities(&pointer, &mut chain_spec_json, &validators, key_type_to_use);
} else if chain_spec_json
.pointer(&format!("{pointer}/aura"))
.is_some()
{
add_aura_authorities(&pointer, &mut chain_spec_json, &validators, KeyType::Aura);
} else {
warn!("Can't customize keys, not `session` or `aura` find in the chain-spec file");
};
// Add nodes to collator
let invulnerables: Vec<&NodeSpec> = para
.collators
.iter()
.filter(|node| node.is_invulnerable)
.collect();
add_collator_selection(
&pointer,
&mut chain_spec_json,
&invulnerables,
key_type_to_use,
);
// override `parachainInfo/parachainId`
override_parachain_info(&pointer, &mut chain_spec_json, para.id);
// write spec
let content = serde_json::to_string_pretty(&chain_spec_json).map_err(|_| {
GeneratorError::ChainSpecGeneration("can not parse chain-spec value as json".into())
})?;
self.write_spec(scoped_fs, content).await?;
} else {
warn!("⚠️ Chain spec for para_id: {} is in raw mode", para.id);
}
Ok(())
}
pub async fn customize_relay<'a, T, U>(
&self,
relaychain: &RelaychainSpec,
hrmp_channels: &[HrmpChannelConfig],
para_artifacts: Vec<ParaGenesisConfig<U>>,
scoped_fs: &ScopedFilesystem<'a, T>,
) -> Result<(), GeneratorError>
where
T: FileSystem,
U: AsRef<Path>,
{
let (content, format) = self.read_spec(scoped_fs).await?;
let mut chain_spec_json: serde_json::Value =
serde_json::from_str(&content).map_err(|_| {
GeneratorError::ChainSpecGeneration("Can not parse chain-spec as json".into())
})?;
if let ChainSpecFormat::Plain = format {
// get the tokenDecimals property or set the default (12)
let token_decimals =
if let Some(val) = chain_spec_json.pointer("/properties/tokenDecimals") {
let val = val.as_u64().unwrap_or(12);
if val > u8::MAX as u64 {
12
} else {
val as u8
}
} else {
12
};
// get the config pointer
let pointer = get_runtime_config_pointer(&chain_spec_json)
.map_err(GeneratorError::ChainSpecGeneration)?;
// make genesis overrides first.
if let Some(overrides) = &relaychain.runtime_genesis_patch {
let percolated_overrides = percolate_overrides(&pointer, overrides)
.map_err(|e| GeneratorError::ChainSpecGeneration(e.to_string()))?;
if let Some(patch_section) = chain_spec_json.pointer_mut(&pointer) {
merge(patch_section, percolated_overrides);
}
}
// get min stake (to store if neede later)
let staking_min = get_staking_min(&pointer, &mut chain_spec_json);
// Clear authorities
clear_authorities(&pointer, &mut chain_spec_json, &self.context);
// add balances
add_balances(
&pointer,
&mut chain_spec_json,
&relaychain.nodes,
token_decimals,
staking_min,
);
// add staking
add_staking(
&pointer,
&mut chain_spec_json,
&relaychain.nodes,
staking_min,
);