/
spec.rs
1827 lines (1614 loc) · 63.9 KB
/
spec.rs
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::{BTreeMap, HashMap},
fs::{self, File},
io::{self, Error, ErrorKind, Write},
path::Path,
str::FromStr,
};
use avalanche_types::{
avalanchego::{config as avalanchego_config, genesis as avalanchego_genesis},
constants,
coreth::chain_config as coreth_chain_config,
key, node, subnet,
subnet_evm::{chain_config as subnet_evm_chain_config, genesis as subnet_evm_genesis},
xsvm::genesis as xsvm_genesis,
};
use aws_manager::kms;
use lazy_static::lazy_static;
use rust_embed::RustEmbed;
use serde::{Deserialize, Serialize};
pub const VERSION: usize = 1;
/// Represents network-level configuration shared among all nodes.
/// The node-level configuration is generated during each
/// bootstrap process (e.g., certificates) and not defined
/// in this cluster-level "Config".
/// At the beginning, the user is expected to provide this configuration.
/// "Clone" is for deep-copying.
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
#[serde(rename_all = "snake_case")]
pub struct Spec {
#[serde(default)]
pub version: usize,
/// User-provided ID of the cluster/test.
/// This is NOT the avalanche node ID.
/// This is NOT the avalanche network ID.
#[serde(default)]
pub id: String,
/// AAD tag used for envelope encryption with KMS.
#[serde(default)]
pub aad_tag: String,
/// AWS resources if run in AWS.
pub aws_resources: crate::aws::Resources,
/// Defines how the underlying infrastructure is set up.
/// MUST BE NON-EMPTY.
pub machine: Machine,
/// Install artifacts to share with remote machines.
pub install_artifacts: InstallArtifacts,
/// Flag to pass to the "avalanched" command-line interface.
pub avalanched_config: crate::avalanched::Flags,
/// Set "true" to enable NLB.
#[serde(default)]
pub enable_nlb: bool,
/// Set "true" to disable CloudWatch log auto removal.
#[serde(default)]
pub disable_logs_auto_removal: bool,
/// Represents the configuration for "avalanchego".
/// Set as if run in remote machines.
/// For instance, "config-file" must be the path valid
/// in the remote machines.
/// MUST BE "kebab-case" to be compatible with "avalanchego".
pub avalanchego_config: avalanchego_config::Config,
/// If non-empty, the JSON-encoded data are saved to a file
/// in Path::new(&avalanchego_config.chain_config_dir).join("C").
pub coreth_chain_config: coreth_chain_config::Config,
/// If non-empty, the JSON-encoded data are saved to a file
/// and used for "--genesis" in Path::new(&avalanchego_config.genesis).
/// This includes "coreth_genesis::Genesis".
/// Names after "_template" since it has not included
/// initial stakers yet with to-be-created node IDs.
#[serde(skip_serializing_if = "Option::is_none")]
pub avalanchego_genesis_template: Option<avalanchego_genesis::Genesis>,
/// Use sorted map in order to map each tracked subnet id (placeholder)
/// to each subnet/chain configuration.
#[serde(skip_serializing_if = "Option::is_none")]
pub subnet_evms: Option<BTreeMap<String, SubnetEvm>>,
/// Use sorted map in order to map each tracked subnet id (placeholder)
/// to each subnet configuration.
#[serde(skip_serializing_if = "Option::is_none")]
pub xsvms: Option<BTreeMap<String, Xsvm>>,
#[serde(default)]
pub xsvms_split_validators: bool,
/// NOTE: Only required for custom networks with pre-funded wallets!
/// These are used for custom primary network genesis generation and will be pre-funded.
/// The first key will have locked P-chain balance with initial stake duration in genesis.
/// Except the first key in the list, all keys have immediately unlocked P-chain balance.
/// Should never be used for mainnet as it's store in plaintext for testing purposes only.
#[serde(skip_serializing_if = "Option::is_none")]
pub test_key_infos: Option<Vec<key::secp256k1::Info>>,
/// Created nodes at the start of the network.
/// May become stale.
#[serde(skip_serializing_if = "Option::is_none")]
pub created_nodes: Option<Vec<Node>>,
/// Created endpoints at the start of the network.
/// May become stale.
#[serde(skip_serializing_if = "Option::is_none")]
pub created_endpoints: Option<Endpoints>,
/// Interval in seconds to fetch system and avalanche node metrics.
/// Set to 0 to disable metrics collection.
#[serde(default)]
pub metrics_fetch_interval_seconds: u64,
/// Prometheus rules for telemetry.
/// "avalanched" reads this metrics and writes to disk (ALWAYS OVERWRITE).
#[serde(skip_serializing_if = "Option::is_none")]
pub prometheus_metrics_rules: Option<prometheus_manager::Rules>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct SubnetEvm {
pub genesis: subnet_evm_genesis::Genesis,
pub chain_config: subnet_evm_chain_config::Config,
pub subnet_config: subnet::config::Config,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct Xsvm {
pub genesis: xsvm_genesis::Genesis,
pub subnet_config: subnet::config::Config,
}
/// Defines "default-spec" option.
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
pub struct DefaultSpecOption {
pub log_level: String,
pub network_name: String,
pub key_files_dir: String,
pub keys_to_generate: usize,
pub keys_to_generate_type: String,
pub region: String,
pub preferred_az_index: usize,
pub instance_mode: String,
pub disable_spot_instance_for_anchor_nodes: bool,
pub volume_size_in_gb: u32,
pub ip_mode: String,
pub enable_nlb: bool,
pub disable_logs_auto_removal: bool,
pub metrics_fetch_interval_seconds: u64,
pub aad_tag: String,
pub nlb_acm_certificate_arn: String,
pub install_artifacts_aws_volume_provisioner_local_bin: String,
pub install_artifacts_aws_ip_provisioner_local_bin: String,
pub install_artifacts_avalanche_telemetry_cloudwatch_local_bin: String,
pub install_artifacts_avalanche_config_local_bin: String,
pub install_artifacts_avalanched_local_bin: String,
pub install_artifacts_avalanche_local_bin: String,
pub install_artifacts_plugin_local_dir: String,
pub avalanched_log_level: String,
pub avalanched_use_default_config: bool,
pub avalanched_publish_periodic_node_info: bool,
pub avalanchego_log_level: String,
pub avalanchego_http_tls_enabled: bool,
pub avalanchego_state_sync_ids: String,
pub avalanchego_state_sync_ips: String,
pub avalanchego_profile_continuous_enabled: bool,
pub avalanchego_profile_continuous_freq: String,
pub avalanchego_profile_continuous_max_files: String,
pub coreth_continuous_profiler_enabled: bool,
pub coreth_offline_pruning_enabled: bool,
pub coreth_state_sync_enabled: bool,
pub subnet_evms: usize,
pub subnet_evm_gas_limit: u64,
pub subnet_evm_min_max_gas_cost: u64,
pub subnet_evm_auto_contract_deployer_allow_list_config: bool,
pub subnet_evm_auto_contract_native_minter_config: bool,
pub subnet_evm_auto_fee_manager_config: bool,
pub subnet_evm_config_proposer_min_block_delay_seconds: u64,
pub xsvms: usize,
pub xsvms_split_validators: bool,
pub spec_file_path: String,
}
pub const ARCH_AMD64: &str = "amd64";
pub const ARCH_ARM64: &str = "arm64";
lazy_static! {
/// Avalanche consensus paper used "c5.large" for testing 125 ~ 2,000 nodes
/// Avalanche test net ("fuji") runs "c5.2xlarge"
///
/// https://aws.amazon.com/ec2/instance-types/c6a/
/// c6a.large: 2 vCPU + 4 GiB RAM
/// c6a.xlarge: 4 vCPU + 8 GiB RAM
/// c6a.2xlarge: 8 vCPU + 16 GiB RAM
/// c6a.4xlarge: 16 vCPU + 32 GiB RAM
/// c6a.8xlarge: 32 vCPU + 64 GiB RAM
///
/// https://aws.amazon.com/ec2/instance-types/m6a/
/// m6a.large: 2 vCPU + 8 GiB RAM
/// m6a.xlarge: 4 vCPU + 16 GiB RAM
/// m6a.2xlarge: 8 vCPU + 32 GiB RAM
/// m6a.4xlarge: 16 vCPU + 64 GiB RAM
/// m6a.8xlarge: 32 vCPU + 128 GiB RAM
///
/// https://aws.amazon.com/ec2/instance-types/m5/
/// m5.large: 2 vCPU + 8 GiB RAM
/// m5.xlarge: 4 vCPU + 16 GiB RAM
/// m5.2xlarge: 8 vCPU + 32 GiB RAM
/// m5.4xlarge: 16 vCPU + 64 GiB RAM
/// m5.8xlarge: 32 vCPU + 128 GiB RAM
///
/// https://aws.amazon.com/ec2/instance-types/c5/
/// c5.large: 2 vCPU + 4 GiB RAM
/// c5.xlarge: 4 vCPU + 8 GiB RAM
/// c5.2xlarge: 8 vCPU + 16 GiB RAM
/// c5.4xlarge: 16 vCPU + 32 GiB RAM
/// c5.9xlarge: 32 vCPU + 72 GiB RAM
///
/// https://aws.amazon.com/ec2/instance-types/r5/
/// r5.large: 2 vCPU + 16 GiB RAM
/// r5.xlarge: 4 vCPU + 32 GiB RAM
/// r5.2xlarge: 8 vCPU + 64 GiB RAM
/// r5.4xlarge: 16 vCPU + 128 GiB RAM
/// r5.8xlarge: 32 vCPU + 256 GiB RAM
///
/// https://aws.amazon.com/ec2/instance-types/t3/
/// t3.large: 2 vCPU + 8 GiB RAM
/// t3.xlarge: 4 vCPU + 16 GiB RAM
/// t3.2xlarge: 8 vCPU + 32 GiB RAM
///
pub static ref DEFAULT_EC2_INSTANCE_TYPES_AMD64: Vec<String> = vec![
String::from("c6a.xlarge"),
String::from("m6a.xlarge"),
String::from("m5.xlarge"),
String::from("c5.xlarge"),
];
/// Avalanche consensus paper used "c5.large" for testing 125 ~ 2,000 nodes
/// Avalanche test net ("fuji") runs "c5.2xlarge"
///
/// Graviton 3 (in preview)
/// https://aws.amazon.com/ec2/instance-types/c7g/
/// c7g.large: 2 vCPU + 8 GiB RAM
/// c7g.xlarge: 4 vCPU + 16 GiB RAM
/// c7g.2xlarge: 8 vCPU + 32 GiB RAM
///
/// Graviton 2
/// https://aws.amazon.com/ec2/instance-types/c6g/
/// c6g.large: 2 vCPU + 4 GiB RAM
/// c6g.xlarge: 4 vCPU + 8 GiB RAM
/// c6g.2xlarge: 8 vCPU + 16 GiB RAM
///
/// Graviton 2
/// https://aws.amazon.com/ec2/instance-types/m6g/
/// m6g.large: 2 vCPU + 8 GiB RAM
/// m6g.xlarge: 4 vCPU + 16 GiB RAM
/// m6g.2xlarge: 8 vCPU + 32 GiB RAM
///
/// Graviton 2
/// https://aws.amazon.com/ec2/instance-types/r6g/
/// r6g.large: 2 vCPU + 16 GiB RAM
/// r6g.xlarge: 4 vCPU + 32 GiB RAM
/// r6g.2xlarge: 8 vCPU + 64 GiB RAM
///
/// Graviton 2
/// https://aws.amazon.com/ec2/instance-types/t4/
/// t4g.large: 2 vCPU + 8 GiB RAM
/// t4g.xlarge: 4 vCPU + 16 GiB RAM
/// t4g.2xlarge: 8 vCPU + 32 GiB RAM
pub static ref DEFAULT_EC2_INSTANCE_TYPES_ARM64: Vec<String> = vec![
String::from("c6g.xlarge"),
String::from("m6g.xlarge"),
String::from("r6g.xlarge"),
String::from("t4g.xlarge"),
];
}
pub fn default_prometheus_rules() -> prometheus_manager::Rules {
#[derive(RustEmbed)]
#[folder = "artifacts/"]
#[prefix = "artifacts/"]
struct Asset;
let filters_raw = Asset::get("artifacts/default.metrics.rules.yaml").unwrap();
let filters_raw = std::str::from_utf8(filters_raw.data.as_ref()).unwrap();
serde_yaml::from_str(filters_raw).unwrap()
}
impl Spec {
/// Creates a default spec.
pub async fn default_aws(opts: DefaultSpecOption) -> Self {
let network_id = match constants::NETWORK_NAME_TO_NETWORK_ID.get(opts.network_name.as_str())
{
Some(v) => *v,
None => constants::DEFAULT_CUSTOM_NETWORK_ID,
};
let mut avalanched_config = crate::avalanched::Flags {
log_level: opts.avalanched_log_level,
use_default_config: opts.avalanched_use_default_config,
publish_periodic_node_info: None,
};
if opts.avalanched_publish_periodic_node_info {
avalanched_config.publish_periodic_node_info = Some(true);
}
let mut avalanchego_config = match network_id {
1 => avalanchego_config::Config::default_main(),
5 => avalanchego_config::Config::default_fuji(),
_ => avalanchego_config::Config::default_custom(),
};
avalanchego_config.log_level = Some(opts.avalanchego_log_level);
// only set values if non empty
// otherwise, avalanchego will fail with "couldn't load node config: read .: is a directory"
// TODO: use different certs than staking?
if opts.avalanchego_http_tls_enabled {
avalanchego_config.http_tls_enabled = Some(true);
avalanchego_config.http_tls_key_file = avalanchego_config.staking_tls_key_file.clone();
avalanchego_config.http_tls_cert_file =
avalanchego_config.staking_tls_cert_file.clone();
}
if !opts.avalanchego_state_sync_ids.is_empty() {
avalanchego_config.state_sync_ids = Some(opts.avalanchego_state_sync_ids.clone());
};
if !opts.avalanchego_state_sync_ips.is_empty() {
avalanchego_config.state_sync_ips = Some(opts.avalanchego_state_sync_ips.clone());
};
if opts.avalanchego_profile_continuous_enabled {
avalanchego_config.profile_continuous_enabled = Some(true);
}
if !opts.avalanchego_profile_continuous_freq.is_empty() {
avalanchego_config.profile_continuous_freq =
Some(opts.avalanchego_profile_continuous_freq.clone());
};
if !opts.avalanchego_profile_continuous_max_files.is_empty() {
let profile_continuous_max_files = opts.avalanchego_profile_continuous_max_files;
let profile_continuous_max_files = profile_continuous_max_files.parse::<u32>().unwrap();
avalanchego_config.profile_continuous_max_files = Some(profile_continuous_max_files);
};
let network_id = avalanchego_config.network_id;
let id = {
if !opts.spec_file_path.is_empty() {
let spec_file_stem = Path::new(&opts.spec_file_path).file_stem().unwrap();
spec_file_stem.to_str().unwrap().to_string()
} else {
match constants::NETWORK_ID_TO_NETWORK_NAME.get(&network_id) {
Some(v) => id_manager::time::with_prefix(format!("aops-{}", *v).as_str()),
None => id_manager::time::with_prefix("aops-custom"),
}
}
};
let (anchor_nodes, non_anchor_nodes) =
match constants::NETWORK_ID_TO_NETWORK_NAME.get(&network_id) {
// non-custom network only single node to utilize single AZ
Some(_) => (None, 1),
// custom network
None => (
Some(DEFAULT_MACHINE_ANCHOR_NODES),
DEFAULT_MACHINE_NON_ANCHOR_NODES,
),
};
if !opts.key_files_dir.is_empty() {
log::info!("creating key-files-dir '{}'", opts.key_files_dir);
fs::create_dir_all(&opts.key_files_dir).unwrap();
}
let key_type = key::secp256k1::KeyType::from_str(&opts.keys_to_generate_type).unwrap();
match key_type {
key::secp256k1::KeyType::Hot => log::info!("generating hot keys..."),
key::secp256k1::KeyType::AwsKms => log::info!("generating AWS KMS CMKs..."),
_ => panic!("unknown key type {}", key_type),
}
if key_type == key::secp256k1::KeyType::AwsKms && opts.keys_to_generate > 2 {
panic!(
"key::secp256k1::KeyType::AwsKms only supported up to 2 keys, got {}",
opts.keys_to_generate
);
}
let mut test_keys_infos: Vec<key::secp256k1::Info> = Vec::new();
let mut test_keys_read_only: Vec<key::secp256k1::public_key::Key> = Vec::new();
for i in 0..opts.keys_to_generate {
let (key_info, key_read_only) = {
match key_type {
key::secp256k1::KeyType::Hot => {
if i < key::secp256k1::TEST_KEYS.len() {
(
key::secp256k1::TEST_KEYS[i].to_info(network_id).unwrap(),
key::secp256k1::TEST_KEYS[i].to_public_key(),
)
} else {
let k = key::secp256k1::private_key::Key::generate().unwrap();
(k.to_info(network_id).unwrap(), k.to_public_key())
}
}
key::secp256k1::KeyType::AwsKms => {
let shared_config = aws_manager::load_config(Some(opts.region.clone()))
.await
.unwrap();
let kms_manager = kms::Manager::new(&shared_config);
let mut tags = HashMap::new();
tags.insert(String::from("Name"), format!("{id}-cmk-{i}"));
let cmk = key::secp256k1::kms::aws::Cmk::create(kms_manager.clone(), tags)
.await
.unwrap();
let cmk_info = cmk.to_info(network_id).unwrap();
println!("cmk_info: {}", cmk_info);
(cmk_info, cmk.to_public_key())
}
_ => panic!("unknown key type {}", key_type),
}
};
test_keys_infos.push(key_info.clone());
test_keys_read_only.push(key_read_only);
if key_type == key::secp256k1::KeyType::Hot && !opts.key_files_dir.is_empty() {
// file name is eth address with 0x, contents are "private_key_hex"
let p = Path::new(&opts.key_files_dir).join(Path::new(&key_info.eth_address));
log::info!("writing key file {:?}", p);
let mut f = File::create(p).unwrap();
f.write_all(
prefix_manager::strip_0x(&key_info.private_key_hex.clone().unwrap()).as_bytes(),
)
.unwrap();
}
}
let avalanchego_genesis_template = {
if avalanchego_config.is_custom_network() {
let g = avalanchego_genesis::Genesis::new(network_id, &test_keys_read_only)
.expect("unexpected None genesis");
Some(g)
} else {
None
}
};
let subnet_evms = {
if opts.subnet_evms > 0 {
let mut genesis = subnet_evm_genesis::Genesis::new(&test_keys_read_only)
.expect("failed to generate genesis");
let mut admin_addresses: Vec<String> = Vec::new();
for key_info in test_keys_infos.iter() {
admin_addresses.push(key_info.eth_address.clone());
}
let mut chain_config = subnet_evm_genesis::ChainConfig::default();
if opts.subnet_evm_gas_limit > 0 {
let mut fee_config = subnet_evm_genesis::FeeConfig::default();
fee_config.gas_limit = Some(opts.subnet_evm_gas_limit);
chain_config.fee_config = Some(fee_config);
genesis.gas_limit = primitive_types::U256::from(opts.subnet_evm_gas_limit);
}
if opts.subnet_evm_min_max_gas_cost > 0 {
if let Some(chain_config_fee_config) = &chain_config.fee_config {
let mut chain_config_fee_config = chain_config_fee_config.clone();
chain_config_fee_config.min_block_gas_cost =
Some(opts.subnet_evm_min_max_gas_cost);
chain_config_fee_config.max_block_gas_cost =
Some(opts.subnet_evm_min_max_gas_cost);
chain_config.fee_config = Some(chain_config_fee_config);
}
}
if opts.subnet_evm_auto_contract_deployer_allow_list_config {
chain_config.contract_deployer_allow_list_config =
Some(subnet_evm_genesis::ContractDeployerAllowListConfig {
allow_list_admins: Some(admin_addresses.clone()),
..subnet_evm_genesis::ContractDeployerAllowListConfig::default()
});
}
if opts.subnet_evm_auto_contract_native_minter_config {
chain_config.contract_native_minter_config =
Some(subnet_evm_genesis::ContractNativeMinterConfig {
allow_list_admins: Some(admin_addresses.clone()),
..subnet_evm_genesis::ContractNativeMinterConfig::default()
});
}
if opts.subnet_evm_auto_fee_manager_config {
chain_config.fee_manager_config = Some(subnet_evm_genesis::FeeManagerConfig {
allow_list_admins: Some(admin_addresses),
..subnet_evm_genesis::FeeManagerConfig::default()
});
}
genesis.config = Some(chain_config);
let chain_config = subnet_evm_chain_config::Config::default();
let mut subnet_config = subnet::config::Config::default();
if opts.subnet_evm_config_proposer_min_block_delay_seconds > 0 {
subnet_config.proposer_min_block_delay = opts
.subnet_evm_config_proposer_min_block_delay_seconds
* 1000
* 1000
* 1000;
}
let subnet_evm = SubnetEvm {
genesis,
chain_config,
subnet_config,
};
let mut subnet_evms = BTreeMap::new();
for i in 0..opts.subnet_evms {
subnet_evms.insert(
format!("{}{}", i + 1, random_manager::string(5)),
subnet_evm.clone(),
);
}
Some(subnet_evms)
} else {
None
}
};
let xsvms = {
if opts.xsvms > 0 {
let genesis = xsvm_genesis::Genesis::new(&test_keys_read_only)
.expect("failed to generate genesis");
let mut subnet_config = subnet::config::Config::default();
if opts.subnet_evm_config_proposer_min_block_delay_seconds > 0 {
subnet_config.proposer_min_block_delay = opts
.subnet_evm_config_proposer_min_block_delay_seconds
* 1000
* 1000
* 1000;
}
let xsvm = Xsvm {
genesis,
subnet_config,
};
let mut xsvms = BTreeMap::new();
for i in 0..opts.xsvms {
xsvms.insert(
format!("{}{}", i + 1, random_manager::string(5)),
xsvm.clone(),
);
}
Some(xsvms)
} else {
None
}
};
// [year][month][date]-[system host-based id]
let s3_bucket = format!(
"avalanche-ops-{}-{}-{}",
id_manager::time::timestamp(6),
id_manager::system::string(10),
opts.region
);
let mut aws_resources = crate::aws::Resources {
region: opts.region.clone(),
s3_bucket,
..crate::aws::Resources::default()
};
if !opts.nlb_acm_certificate_arn.is_empty() {
aws_resources.nlb_acm_certificate_arn = Some(opts.nlb_acm_certificate_arn);
}
let mut kms_cmk_secp256k1_cmks = Vec::new();
for test_key_info in test_keys_infos.iter() {
if test_key_info.key_type == key::secp256k1::KeyType::AwsKms {
kms_cmk_secp256k1_cmks.push(crate::aws::KmsCmk {
id: test_key_info.id.clone().unwrap(),
arn: test_key_info.id.clone().unwrap(),
})
}
}
if !kms_cmk_secp256k1_cmks.is_empty() {
aws_resources.kms_cmk_secp256k1_cmks = Some(kms_cmk_secp256k1_cmks);
}
let mut install_artifacts = InstallArtifacts {
avalanched_local_bin: None,
aws_volume_provisioner_local_bin: None,
aws_ip_provisioner_local_bin: None,
avalanche_telemetry_cloudwatch_local_bin: None,
avalanche_config_local_bin: None,
avalanchego_local_bin: None,
plugin_local_dir: None,
};
if !opts
.install_artifacts_aws_volume_provisioner_local_bin
.is_empty()
{
install_artifacts.aws_volume_provisioner_local_bin =
Some(opts.install_artifacts_aws_volume_provisioner_local_bin);
}
if !opts
.install_artifacts_aws_ip_provisioner_local_bin
.is_empty()
{
install_artifacts.aws_ip_provisioner_local_bin =
Some(opts.install_artifacts_aws_ip_provisioner_local_bin);
}
if !opts
.install_artifacts_avalanche_telemetry_cloudwatch_local_bin
.is_empty()
{
install_artifacts.avalanche_telemetry_cloudwatch_local_bin =
Some(opts.install_artifacts_avalanche_telemetry_cloudwatch_local_bin);
}
if !opts.install_artifacts_avalanche_config_local_bin.is_empty() {
install_artifacts.avalanche_config_local_bin =
Some(opts.install_artifacts_avalanche_config_local_bin);
}
if !opts.install_artifacts_avalanched_local_bin.is_empty() {
install_artifacts.avalanched_local_bin =
Some(opts.install_artifacts_avalanched_local_bin);
}
if !opts.install_artifacts_avalanche_local_bin.is_empty() {
install_artifacts.avalanchego_local_bin =
Some(opts.install_artifacts_avalanche_local_bin);
}
if !opts.install_artifacts_plugin_local_dir.is_empty() {
install_artifacts.plugin_local_dir = Some(opts.install_artifacts_plugin_local_dir);
}
let mut coreth_chain_config = coreth_chain_config::Config::default();
if opts.coreth_continuous_profiler_enabled {
coreth_chain_config.continuous_profiler_dir =
Some(String::from(coreth_chain_config::DEFAULT_PROFILE_DIR));
coreth_chain_config.continuous_profiler_frequency =
Some(coreth_chain_config::DEFAULT_PROFILE_FREQUENCY);
coreth_chain_config.continuous_profiler_max_files =
Some(coreth_chain_config::DEFAULT_PROFILE_MAX_FILES);
}
if opts.coreth_offline_pruning_enabled {
coreth_chain_config.offline_pruning_enabled = Some(true);
}
if opts.coreth_state_sync_enabled {
coreth_chain_config.state_sync_enabled = Some(true);
if !opts.avalanchego_state_sync_ids.is_empty() {
coreth_chain_config.state_sync_ids = Some(opts.avalanchego_state_sync_ids.clone());
}
}
let state_sync_enabled = if let Some(b) = coreth_chain_config.state_sync_enabled {
b
} else {
false
};
let volume_size_in_gb = if opts.volume_size_in_gb > 0 {
opts.volume_size_in_gb
} else {
if avalanchego_config.is_mainnet() {
if state_sync_enabled {
500
} else {
1024
}
} else if !avalanchego_config.is_custom_network() {
// fuji/*
if state_sync_enabled {
250
} else {
600
}
} else {
if state_sync_enabled {
200
} else {
400
}
}
};
let mut instance_types = Vec::new();
for instance_type in DEFAULT_EC2_INSTANCE_TYPES_AMD64.iter() {
if opts.region == "ap-northeast-2".to_string() {
if instance_type.starts_with("c6a.") || instance_type.starts_with("m6a.") {
continue;
}
}
instance_types.push(instance_type.clone());
}
let machine = Machine {
anchor_nodes,
non_anchor_nodes,
// TODO: support "arm64"
arch: ARCH_AMD64.to_string(),
instance_types,
instance_mode: opts.instance_mode,
disable_spot_instance_for_anchor_nodes: opts.disable_spot_instance_for_anchor_nodes,
ip_mode: opts.ip_mode,
volume_size_in_gb,
};
Self {
version: VERSION,
id,
aad_tag: opts.aad_tag,
aws_resources,
machine,
install_artifacts,
avalanched_config,
enable_nlb: opts.enable_nlb,
disable_logs_auto_removal: opts.disable_logs_auto_removal,
avalanchego_config,
coreth_chain_config,
avalanchego_genesis_template,
subnet_evms,
xsvms,
xsvms_split_validators: opts.xsvms_split_validators,
test_key_infos: Some(test_keys_infos),
created_nodes: None,
created_endpoints: None,
metrics_fetch_interval_seconds: opts.metrics_fetch_interval_seconds,
prometheus_metrics_rules: Some(default_prometheus_rules()),
}
}
/// Converts to string in YAML format.
pub fn encode_yaml(&self) -> io::Result<String> {
match serde_yaml::to_string(&self) {
Ok(s) => Ok(s),
Err(e) => Err(Error::new(
ErrorKind::Other,
format!("failed to serialize Spec to YAML {}", e),
)),
}
}
/// Saves the current spec to disk
/// and overwrites the file.
pub fn sync(&self, file_path: &str) -> io::Result<()> {
log::info!("syncing Spec to '{}'", file_path);
let path = Path::new(file_path);
let parent_dir = path.parent().expect("unexpected None parent");
fs::create_dir_all(parent_dir)?;
let d = serde_yaml::to_string(self).map_err(|e| {
Error::new(
ErrorKind::Other,
format!("failed to serialize Spec info to YAML {}", e),
)
})?;
let mut f = File::create(file_path)?;
f.write_all(d.as_bytes())?;
Ok(())
}
pub fn load(file_path: &str) -> io::Result<Self> {
log::info!("loading Spec from {}", file_path);
if !Path::new(file_path).exists() {
return Err(Error::new(
ErrorKind::NotFound,
format!("file {} does not exists", file_path),
));
}
let f = File::open(file_path).map_err(|e| {
Error::new(
ErrorKind::Other,
format!("failed to open {} ({})", file_path, e),
)
})?;
serde_yaml::from_reader(f)
.map_err(|e| Error::new(ErrorKind::InvalidInput, format!("invalid YAML: {}", e)))
}
/// Validates the spec.
pub fn validate(&self) -> io::Result<()> {
log::info!("validating Spec");
if self.id.is_empty() {
return Err(Error::new(ErrorKind::InvalidInput, "'id' cannot be empty"));
}
// some AWS resources have tag limit of 32-character
if self.id.len() > 28 {
return Err(Error::new(
ErrorKind::InvalidInput,
format!("'id' length cannot be >28 (got {})", self.id.len()),
));
}
if self.aws_resources.region.is_empty() {
return Err(Error::new(
ErrorKind::InvalidInput,
"'machine.region' cannot be empty",
));
}
if self.machine.non_anchor_nodes < MIN_MACHINE_NON_ANCHOR_NODES {
return Err(Error::new(
ErrorKind::InvalidInput,
format!(
"'machine.non_anchor_nodes' {} <minimum {}",
self.machine.non_anchor_nodes, MIN_MACHINE_NON_ANCHOR_NODES
),
));
}
if self.machine.non_anchor_nodes > MAX_MACHINE_NON_ANCHOR_NODES {
return Err(Error::new(
ErrorKind::InvalidInput,
format!(
"'machine.non_anchor_nodes' {} >maximum {}",
self.machine.non_anchor_nodes, MAX_MACHINE_NON_ANCHOR_NODES
),
));
}
if !self.avalanchego_config.is_custom_network() && self.machine.non_anchor_nodes != 1 {
return Err(Error::new(
ErrorKind::InvalidInput,
format!(
"'machine.non_anchor_nodes' must be 1 (set to {}) in order to maximize the benefit of static EBS provision per AZ",
self.machine.non_anchor_nodes
),
));
}
if let Some(v) = &self.install_artifacts.aws_volume_provisioner_local_bin {
if !Path::new(v).exists() {
return Err(Error::new(
ErrorKind::InvalidInput,
format!("aws_volume_provisioner_bin {} does not exist", v),
));
}
}
if let Some(v) = &self.install_artifacts.aws_ip_provisioner_local_bin {
if !Path::new(v).exists() {
return Err(Error::new(
ErrorKind::InvalidInput,
format!("aws_ip_provisioner_bin {} does not exist", v),
));
}
}
if let Some(v) = &self.install_artifacts.avalanched_local_bin {
if !Path::new(v).exists() {
return Err(Error::new(
ErrorKind::InvalidInput,
format!("avalanched_bin {} does not exist", v),
));
}
}
if let Some(v) = &self.install_artifacts.avalanchego_local_bin {
if !Path::new(v).exists() {
return Err(Error::new(
ErrorKind::InvalidInput,
format!("avalanchego_bin {} does not exist", v),
));
}
}
if let Some(v) = &self.install_artifacts.plugin_local_dir {
if !Path::new(v).exists() {
return Err(Error::new(
ErrorKind::InvalidInput,
format!("plugin_dir {} does not exist", v),
));
}
}
if !self.avalanchego_config.is_custom_network() {
if self.avalanchego_genesis_template.is_some() {
return Err(Error::new(
ErrorKind::InvalidInput,
format!(
"cannot specify 'avalanchego_genesis_template' for network_id {:?}",
self.avalanchego_config.network_id
),
));
}
if self.machine.anchor_nodes.unwrap_or(0) > 0 {
return Err(Error::new(
ErrorKind::InvalidInput,
format!(
"cannot specify non-zero 'machine.anchor_nodes' for network_id {:?}",
self.avalanchego_config.network_id
),
));
}
} else {
if self.avalanchego_genesis_template.is_none() {
return Err(Error::new(
ErrorKind::InvalidInput,
format!(
"must specify 'avalanchego_genesis_template' for network_id {:?}",
self.avalanchego_config.network_id
),
));
}
if self.machine.anchor_nodes.unwrap_or(0) == 0 {
return Err(Error::new(
ErrorKind::InvalidInput,
"cannot specify 0 for 'machine.anchor_nodes' for custom network",
));
}
if self.machine.anchor_nodes.unwrap_or(0) < MIN_MACHINE_ANCHOR_NODES {
return Err(Error::new(
ErrorKind::InvalidInput,
format!(
"'machine.anchor_nodes' {} below min {}",
self.machine.anchor_nodes.unwrap_or(0),
MIN_MACHINE_ANCHOR_NODES
),
));
}
if self.machine.anchor_nodes.unwrap_or(0) > MAX_MACHINE_ANCHOR_NODES {
return Err(Error::new(
ErrorKind::InvalidInput,
format!(
"'machine.anchor_nodes' {} exceeds limit {}",
self.machine.anchor_nodes.unwrap_or(0),
MAX_MACHINE_ANCHOR_NODES
),
));
}
}
Ok(())
}
}
/// RUST_LOG=debug cargo test --package avalancheup-aws --lib -- spec::test_spec --exact --show-output
#[test]
fn test_spec() {
use std::fs;
let _ = env_logger::builder().is_test(true).try_init();
let mut f = tempfile::NamedTempFile::new().unwrap();
let ret = f.write_all(&vec![0]);
assert!(ret.is_ok());
let avalanche_config_bin = f.path().to_str().unwrap();
let mut f = tempfile::NamedTempFile::new().unwrap();
let ret = f.write_all(&vec![0]);
assert!(ret.is_ok());
let avalanched_bin = f.path().to_str().unwrap();
let mut f = tempfile::NamedTempFile::new().unwrap();
let ret = f.write_all(&vec![0]);
assert!(ret.is_ok());
let avalanchego_bin = f.path().to_str().unwrap();
let tmp_dir = tempfile::tempdir().unwrap();
let plugin_path = tmp_dir.path().join(random_manager::string(10));
let mut f = File::create(&plugin_path).unwrap();
let ret = f.write_all(&vec![0]);
assert!(ret.is_ok());
let plugin_dir = tmp_dir.path().as_os_str().to_str().unwrap();
// test just to see how "read_dir" works in Rust
for entry in fs::read_dir(plugin_dir).unwrap() {
let entry = entry.unwrap();
let path = entry.path();
log::info!("read_dir: {:?}", path);
}
let id = random_manager::string(10);
let bucket = format!("test-{}", id_manager::time::timestamp(8));
let contents = format!(
r#"