forked from stacks-network/stacks-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.rs
2081 lines (1925 loc) · 81.1 KB
/
config.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::convert::TryInto;
use std::fs;
use std::net::{SocketAddr, ToSocketAddrs};
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::Mutex;
use rand::RngCore;
use stacks::burnchains::bitcoin::BitcoinNetworkType;
use stacks::burnchains::Burnchain;
use stacks::burnchains::{MagicBytes, BLOCKSTACK_MAGIC_MAINNET};
use stacks::chainstate::stacks::index::marf::MARFOpenOpts;
use stacks::chainstate::stacks::index::storage::TrieHashCalculationMode;
use stacks::chainstate::stacks::miner::BlockBuilderSettings;
use stacks::chainstate::stacks::miner::MinerStatus;
use stacks::chainstate::stacks::MAX_BLOCK_LEN;
use stacks::core::mempool::MemPoolWalkSettings;
use stacks::core::StacksEpoch;
use stacks::core::StacksEpochExtension;
use stacks::core::StacksEpochId;
use stacks::core::{
CHAIN_ID_MAINNET, CHAIN_ID_TESTNET, PEER_VERSION_MAINNET, PEER_VERSION_TESTNET,
};
use stacks::cost_estimates::fee_medians::WeightedMedianFeeRateEstimator;
use stacks::cost_estimates::fee_rate_fuzzer::FeeRateFuzzer;
use stacks::cost_estimates::fee_scalar::ScalarFeeRateEstimator;
use stacks::cost_estimates::metrics::CostMetric;
use stacks::cost_estimates::metrics::ProportionalDotProduct;
use stacks::cost_estimates::CostEstimator;
use stacks::cost_estimates::FeeEstimator;
use stacks::cost_estimates::PessimisticEstimator;
use stacks::net::connection::ConnectionOptions;
use stacks::net::{Neighbor, NeighborKey, PeerAddress};
use stacks::util::get_epoch_time_ms;
use stacks::util::hash::hex_bytes;
use stacks::util::secp256k1::Secp256k1PrivateKey;
use stacks::util::secp256k1::Secp256k1PublicKey;
use stacks::vm::costs::ExecutionCost;
use stacks::vm::types::{AssetIdentifier, PrincipalData, QualifiedContractIdentifier};
const DEFAULT_SATS_PER_VB: u64 = 50;
const DEFAULT_MAX_RBF_RATE: u64 = 150; // 1.5x
const DEFAULT_RBF_FEE_RATE_INCREMENT: u64 = 5;
const LEADER_KEY_TX_ESTIM_SIZE: u64 = 290;
const BLOCK_COMMIT_TX_ESTIM_SIZE: u64 = 350;
const INV_REWARD_CYCLES_TESTNET: u64 = 6;
#[derive(Clone, Deserialize, Default, Debug)]
pub struct ConfigFile {
pub burnchain: Option<BurnchainConfigFile>,
pub node: Option<NodeConfigFile>,
pub ustx_balance: Option<Vec<InitialBalanceFile>>,
pub events_observer: Option<Vec<EventObserverConfigFile>>,
pub connection_options: Option<ConnectionOptionsFile>,
pub fee_estimation: Option<FeeEstimationConfigFile>,
pub miner: Option<MinerConfigFile>,
}
#[derive(Clone, Deserialize, Default)]
pub struct LegacyMstxConfigFile {
pub mstx_balance: Option<Vec<InitialBalanceFile>>,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_config_file() {
assert_eq!(
format!("Invalid path: No such file or directory (os error 2)"),
ConfigFile::from_path("some_path").unwrap_err()
);
assert_eq!(
format!("Invalid toml: unexpected character found: `/` at line 1 column 1"),
ConfigFile::from_str("//[node]").unwrap_err()
);
assert!(ConfigFile::from_str("").is_ok());
}
#[test]
fn test_config() {
assert_eq!(
format!("node.seed should be a hex encoded string"),
Config::from_config_file(
ConfigFile::from_str(
r#"
[node]
seed = "invalid-hex-value"
"#,
)
.unwrap()
)
.unwrap_err()
);
assert_eq!(
format!("node.local_peer_seed should be a hex encoded string"),
Config::from_config_file(
ConfigFile::from_str(
r#"
[node]
local_peer_seed = "invalid-hex-value"
"#,
)
.unwrap()
)
.unwrap_err()
);
let expected_err_prefix =
"Invalid burnchain.peer_host: failed to lookup address information:";
let actual_err_msg = Config::from_config_file(
ConfigFile::from_str(
r#"
[burnchain]
peer_host = "bitcoin2.blockstack.com"
"#,
)
.unwrap(),
)
.unwrap_err();
assert_eq!(
expected_err_prefix,
&actual_err_msg[..expected_err_prefix.len()]
);
assert!(Config::from_config_file(ConfigFile::from_str("").unwrap()).is_ok());
}
#[test]
fn should_load_legacy_mstx_balances_toml() {
let config = ConfigFile::from_str(
r#"
[[ustx_balance]]
address = "ST2QKZ4FKHAH1NQKYKYAYZPY440FEPK7GZ1R5HBP2"
amount = 10000000000000000
[[ustx_balance]]
address = "ST319CF5WV77KYR1H3GT0GZ7B8Q4AQPY42ETP1VPF"
amount = 10000000000000000
[[mstx_balance]] # legacy property name
address = "ST221Z6TDTC5E0BYR2V624Q2ST6R0Q71T78WTAX6H"
amount = 10000000000000000
[[mstx_balance]] # legacy property name
address = "ST2TFVBMRPS5SSNP98DQKQ5JNB2B6NZM91C4K3P7B"
amount = 10000000000000000
"#,
);
let config = config.unwrap();
assert!(config.ustx_balance.is_some());
let balances = config
.ustx_balance
.expect("Failed to parse stx balances from toml");
assert_eq!(balances.len(), 4);
assert_eq!(
balances[0].address,
"ST2QKZ4FKHAH1NQKYKYAYZPY440FEPK7GZ1R5HBP2"
);
assert_eq!(
balances[1].address,
"ST319CF5WV77KYR1H3GT0GZ7B8Q4AQPY42ETP1VPF"
);
assert_eq!(
balances[2].address,
"ST221Z6TDTC5E0BYR2V624Q2ST6R0Q71T78WTAX6H"
);
assert_eq!(
balances[3].address,
"ST2TFVBMRPS5SSNP98DQKQ5JNB2B6NZM91C4K3P7B"
);
}
}
impl ConfigFile {
pub fn from_path(path: &str) -> Result<ConfigFile, String> {
let content = fs::read_to_string(path).map_err(|e| format!("Invalid path: {}", &e))?;
Self::from_str(&content)
}
pub fn from_str(content: &str) -> Result<ConfigFile, String> {
let mut config: ConfigFile =
toml::from_str(content).map_err(|e| format!("Invalid toml: {}", e))?;
let legacy_config: LegacyMstxConfigFile = toml::from_str(content).unwrap();
if let Some(mstx_balance) = legacy_config.mstx_balance {
warn!("'mstx_balance' inside toml config is deprecated, replace with 'ustx_balance'");
config.ustx_balance = match config.ustx_balance {
Some(balance) => Some([balance, mstx_balance].concat()),
None => Some(mstx_balance),
};
}
Ok(config)
}
pub fn xenon() -> ConfigFile {
let burnchain = BurnchainConfigFile {
mode: Some("xenon".to_string()),
rpc_port: Some(18332),
peer_port: Some(18333),
peer_host: Some("bitcoind.xenon.blockstack.org".to_string()),
magic_bytes: Some("T2".into()),
..BurnchainConfigFile::default()
};
let node = NodeConfigFile {
bootstrap_node: Some("029266faff4c8e0ca4f934f34996a96af481df94a89b0c9bd515f3536a95682ddc@seed.testnet.hiro.so:20444".to_string()),
miner: Some(false),
..NodeConfigFile::default()
};
let balances = vec![
InitialBalanceFile {
address: "ST2QKZ4FKHAH1NQKYKYAYZPY440FEPK7GZ1R5HBP2".to_string(),
amount: 10000000000000000,
},
InitialBalanceFile {
address: "ST319CF5WV77KYR1H3GT0GZ7B8Q4AQPY42ETP1VPF".to_string(),
amount: 10000000000000000,
},
InitialBalanceFile {
address: "ST221Z6TDTC5E0BYR2V624Q2ST6R0Q71T78WTAX6H".to_string(),
amount: 10000000000000000,
},
InitialBalanceFile {
address: "ST2TFVBMRPS5SSNP98DQKQ5JNB2B6NZM91C4K3P7B".to_string(),
amount: 10000000000000000,
},
];
ConfigFile {
burnchain: Some(burnchain),
node: Some(node),
ustx_balance: Some(balances),
..ConfigFile::default()
}
}
pub fn mainnet() -> ConfigFile {
let burnchain = BurnchainConfigFile {
mode: Some("mainnet".to_string()),
rpc_port: Some(8332),
peer_port: Some(8333),
peer_host: Some("bitcoin.blockstack.com".to_string()),
username: Some("blockstack".to_string()),
password: Some("blockstacksystem".to_string()),
magic_bytes: Some("X2".to_string()),
..BurnchainConfigFile::default()
};
let node = NodeConfigFile {
bootstrap_node: Some("02196f005965cebe6ddc3901b7b1cc1aa7a88f305bb8c5893456b8f9a605923893@seed.mainnet.hiro.so:20444".to_string()),
miner: Some(false),
..NodeConfigFile::default()
};
ConfigFile {
burnchain: Some(burnchain),
node: Some(node),
ustx_balance: None,
..ConfigFile::default()
}
}
pub fn helium() -> ConfigFile {
// ## Settings for local testnet, relying on a local bitcoind server
// ## running with the following bitcoin.conf:
// ##
// ## chain=regtest
// ## disablewallet=0
// ## txindex=1
// ## server=1
// ## rpcuser=helium
// ## rpcpassword=helium
// ##
let burnchain = BurnchainConfigFile {
mode: Some("helium".to_string()),
commit_anchor_block_within: Some(10_000),
rpc_port: Some(18443),
peer_port: Some(18444),
peer_host: Some("0.0.0.0".to_string()),
username: Some("helium".to_string()),
password: Some("helium".to_string()),
local_mining_public_key: Some("04ee0b1602eb18fef7986887a7e8769a30c9df981d33c8380d255edef003abdcd243a0eb74afdf6740e6c423e62aec631519a24cf5b1d62bf8a3e06ddc695dcb77".to_string()),
..BurnchainConfigFile::default()
};
let node = NodeConfigFile {
miner: Some(false),
..NodeConfigFile::default()
};
ConfigFile {
burnchain: Some(burnchain),
node: Some(node),
..ConfigFile::default()
}
}
pub fn mocknet() -> ConfigFile {
let burnchain = BurnchainConfigFile {
mode: Some("mocknet".to_string()),
commit_anchor_block_within: Some(10_000),
..BurnchainConfigFile::default()
};
let node = NodeConfigFile {
miner: Some(false),
..NodeConfigFile::default()
};
let balances = vec![
InitialBalanceFile {
// "mnemonic": "point approve language letter cargo rough similar wrap focus edge polar task olympic tobacco cinnamon drop lawn boring sort trade senior screen tiger climb",
// "privateKey": "539e35c740079b79f931036651ad01f76d8fe1496dbd840ba9e62c7e7b355db001",
// "btcAddress": "n1htkoYKuLXzPbkn9avC2DJxt7X85qVNCK",
address: "ST3EQ88S02BXXD0T5ZVT3KW947CRMQ1C6DMQY8H19".to_string(),
amount: 10000000000000000,
},
InitialBalanceFile {
// "mnemonic": "laugh capital express view pull vehicle cluster embark service clerk roast glance lumber glove purity project layer lyrics limb junior reduce apple method pear",
// "privateKey": "075754fb099a55e351fe87c68a73951836343865cd52c78ae4c0f6f48e234f3601",
// "btcAddress": "n2ZGZ7Zau2Ca8CLHGh11YRnLw93b4ufsDR",
address: "ST3KCNDSWZSFZCC6BE4VA9AXWXC9KEB16FBTRK36T".to_string(),
amount: 10000000000000000,
},
InitialBalanceFile {
// "mnemonic": "level garlic bean design maximum inhale daring alert case worry gift frequent floor utility crowd twenty burger place time fashion slow produce column prepare",
// "privateKey": "374b6734eaff979818c5f1367331c685459b03b1a2053310906d1408dc928a0001",
// "btcAddress": "mhY4cbHAFoXNYvXdt82yobvVuvR6PHeghf",
address: "STB2BWB0K5XZGS3FXVTG3TKS46CQVV66NAK3YVN8".to_string(),
amount: 10000000000000000,
},
InitialBalanceFile {
// "mnemonic": "drop guess similar uphold alarm remove fossil riot leaf badge lobster ability mesh parent lawn today student olympic model assault syrup end scorpion lab",
// "privateKey": "26f235698d02803955b7418842affbee600fc308936a7ca48bf5778d1ceef9df01",
// "btcAddress": "mkEDDqbELrKYGUmUbTAyQnmBAEz4V1MAro",
address: "STSTW15D618BSZQB85R058DS46THH86YQQY6XCB7".to_string(),
amount: 10000000000000000,
},
];
ConfigFile {
burnchain: Some(burnchain),
node: Some(node),
ustx_balance: Some(balances),
..ConfigFile::default()
}
}
}
#[derive(Clone, Debug)]
pub struct Config {
pub burnchain: BurnchainConfig,
pub node: NodeConfig,
pub initial_balances: Vec<InitialBalance>,
pub events_observers: Vec<EventObserverConfig>,
pub connection_options: ConnectionOptions,
pub miner: MinerConfig,
pub estimation: FeeEstimationConfig,
}
lazy_static! {
static ref HELIUM_DEFAULT_CONNECTION_OPTIONS: ConnectionOptions = ConnectionOptions {
inbox_maxlen: 100,
outbox_maxlen: 100,
timeout: 15,
idle_timeout: 15, // how long a HTTP connection can be idle before it's closed
heartbeat: 3600,
// can't use u64::max, because sqlite stores as i64.
private_key_lifetime: 9223372036854775807,
num_neighbors: 16, // number of neighbors whose inventories we track
num_clients: 750, // number of inbound p2p connections
soft_num_neighbors: 16, // soft-limit on the number of neighbors whose inventories we track
soft_num_clients: 750, // soft limit on the number of inbound p2p connections
max_neighbors_per_host: 1, // maximum number of neighbors per host we permit
max_clients_per_host: 4, // maximum number of inbound p2p connections per host we permit
soft_max_neighbors_per_host: 1, // soft limit on the number of neighbors per host we permit
soft_max_neighbors_per_org: 32, // soft limit on the number of neighbors per AS we permit (TODO: for now it must be greater than num_neighbors)
soft_max_clients_per_host: 4, // soft limit on how many inbound p2p connections per host we permit
max_http_clients: 1000, // maximum number of HTTP connections
max_neighbors_of_neighbor: 10, // maximum number of neighbors we'll handshake with when doing a neighbor walk (I/O for this can be expensive, so keep small-ish)
walk_interval: 60, // how often, in seconds, we do a neighbor walk
inv_sync_interval: 45, // how often, in seconds, we refresh block inventories
inv_reward_cycles: 3, // how many reward cycles to look back on, for mainnet
download_interval: 10, // how often, in seconds, we do a block download scan (should be less than inv_sync_interval)
dns_timeout: 15_000,
max_inflight_blocks: 6,
max_inflight_attachments: 6,
.. std::default::Default::default()
};
}
impl Config {
/// Apply any test settings to this burnchain config struct
fn apply_test_settings(&self, burnchain: &mut Burnchain) {
if self.burnchain.get_bitcoin_network().1 == BitcoinNetworkType::Mainnet {
return;
}
if let Some(v1_unlock_height) = self.burnchain.pox_2_activation {
debug!(
"Override v1_unlock_height from {} to {}",
burnchain.pox_constants.v1_unlock_height, v1_unlock_height
);
burnchain.pox_constants.v1_unlock_height = v1_unlock_height;
}
if let Some(sunset_start) = self.burnchain.sunset_start {
debug!(
"Override sunset_start from {} to {}",
burnchain.pox_constants.sunset_start, sunset_start
);
burnchain.pox_constants.sunset_start = sunset_start.into();
}
if let Some(sunset_end) = self.burnchain.sunset_end {
debug!(
"Override sunset_end from {} to {}",
burnchain.pox_constants.sunset_end, sunset_end
);
burnchain.pox_constants.sunset_end = sunset_end.into();
}
}
/// Load up a Burnchain and apply config settings to it.
/// Use this over the Burnchain constructors.
/// Panics if we are unable to instantiate a burnchain (e.g. becase we're using an unrecognized
/// chain ID or something).
pub fn get_burnchain(&self) -> Burnchain {
let (network_name, _) = self.burnchain.get_bitcoin_network();
let mut burnchain = {
let working_dir = self.get_burn_db_path();
match Burnchain::new(&working_dir, &self.burnchain.chain, &network_name) {
Ok(burnchain) => burnchain,
Err(e) => {
error!("Failed to instantiate burnchain: {}", e);
panic!()
}
}
};
self.apply_test_settings(&mut burnchain);
burnchain
}
/// Assert that a burnchain's PoX constants are consistent with the list of epoch start and end
/// heights. Panics if this is not the case.
pub fn assert_valid_epoch_settings(burnchain: &Burnchain, epochs: &[StacksEpoch]) {
// sanity check: epochs must be contiguous and ordered
// (this panics if it's not the case)
test_debug!("Validate epochs: {:#?}", epochs);
let _ = StacksEpoch::validate_epochs(epochs);
// sanity check: v1_unlock_height must happen after pox-2 instantiation
let epoch21_index = StacksEpoch::find_epoch_by_id(&epochs, StacksEpochId::Epoch21)
.expect("FATAL: no epoch 2.1 defined");
let epoch21 = &epochs[epoch21_index];
let v1_unlock_height = burnchain.pox_constants.v1_unlock_height as u64;
assert!(
v1_unlock_height > epoch21.start_height,
"FATAL: v1 unlock height occurs at or before pox-2 activation: {} <= {}\nburnchain: {:?}", v1_unlock_height, epoch21.start_height, burnchain
);
let epoch21_rc = burnchain
.block_height_to_reward_cycle(epoch21.start_height)
.expect("FATAL: epoch 21 starts before the first burnchain block");
let v1_unlock_rc = burnchain
.block_height_to_reward_cycle(v1_unlock_height)
.expect("FATAL: v1 unlock height is before the first burnchain block");
if epoch21_rc + 1 == v1_unlock_rc {
// if v1_unlock_height is in the reward cycle after epoch_21, then it must not fall on
// the reward cycle boundary.
assert!(
!burnchain.is_reward_cycle_start(v1_unlock_height),
"FATAL: v1 unlock height is at a reward cycle boundary\nburnchain: {:?}",
burnchain
);
}
}
fn make_epochs(
conf_epochs: &[StacksEpochConfigFile],
burn_mode: &str,
bitcoin_network: BitcoinNetworkType,
pox_2_activation: Option<u32>,
) -> Result<Vec<StacksEpoch>, String> {
let default_epochs = match bitcoin_network {
BitcoinNetworkType::Mainnet => {
Err("Cannot configure epochs in mainnet mode".to_string())
}
BitcoinNetworkType::Testnet => Ok(stacks::core::STACKS_EPOCHS_TESTNET.to_vec()),
BitcoinNetworkType::Regtest => Ok(stacks::core::STACKS_EPOCHS_REGTEST.to_vec()),
}?;
let mut matched_epochs = vec![];
for configured_epoch in conf_epochs.iter() {
let epoch_name = &configured_epoch.epoch_name;
let epoch_id = if epoch_name == EPOCH_CONFIG_1_0_0 {
Ok(StacksEpochId::Epoch10)
} else if epoch_name == EPOCH_CONFIG_2_0_0 {
Ok(StacksEpochId::Epoch20)
} else if epoch_name == EPOCH_CONFIG_2_0_5 {
Ok(StacksEpochId::Epoch2_05)
} else if epoch_name == EPOCH_CONFIG_2_1_0 {
Ok(StacksEpochId::Epoch21)
} else {
Err(format!("Unknown epoch name specified: {}", epoch_name))
}?;
matched_epochs.push((epoch_id, configured_epoch.start_height));
}
matched_epochs.sort_by_key(|(epoch_id, _)| *epoch_id);
// epochs must be sorted the same both by start height and by epoch
let mut check_sort = matched_epochs.clone();
check_sort.sort_by_key(|(_, start)| *start);
if matched_epochs != check_sort {
return Err(
"Configured epochs must have start heights in the correct epoch order".to_string(),
);
}
// epochs must be a prefix of [1.0, 2.0, 2.05, 2.1]
let expected_list = [
StacksEpochId::Epoch10,
StacksEpochId::Epoch20,
StacksEpochId::Epoch2_05,
StacksEpochId::Epoch21,
];
for (expected_epoch, configured_epoch) in expected_list
.iter()
.zip(matched_epochs.iter().map(|(epoch_id, _)| epoch_id))
{
if expected_epoch != configured_epoch {
return Err(format!(
"Configured epochs may not skip an epoch. Expected epoch = {}, Found epoch = {}",
expected_epoch, configured_epoch));
}
}
// Stacks 1.0 must start at 0
if matched_epochs[0].1 != 0 {
return Err("Stacks 1.0 must start at height = 0".into());
}
if matched_epochs.len() > default_epochs.len() {
return Err(format!(
"Cannot configure more epochs than support by this node. Supported epoch count: {}",
default_epochs.len()
));
}
let mut out_epochs = default_epochs[..matched_epochs.len()].to_vec();
for (i, (epoch_id, start_height)) in matched_epochs.iter().enumerate() {
if epoch_id != &out_epochs[i].epoch_id {
return Err(
format!("Unmatched epochs in configuration and node implementation. Implemented = {}, Configured = {}",
epoch_id, &out_epochs[i].epoch_id));
}
// end_height = next epoch's start height || i64::max if last epoch
let end_height = if i + 1 < matched_epochs.len() {
matched_epochs[i + 1].1
} else {
i64::MAX
};
out_epochs[i].start_height = u64::try_from(*start_height)
.map_err(|_| "Start height must be a non-negative integer")?;
out_epochs[i].end_height = u64::try_from(end_height)
.map_err(|_| "End height must be a non-negative integer")?;
}
if burn_mode == "mocknet" {
for epoch in out_epochs.iter_mut() {
epoch.block_limit = ExecutionCost::max_value();
}
}
if let Some(pox_2_activation) = pox_2_activation {
let last_epoch = out_epochs
.iter()
.find(|&e| e.epoch_id == StacksEpochId::Epoch21)
.ok_or("Cannot configure pox_2_activation if epoch 2.1 is not configured")?;
if last_epoch.start_height > pox_2_activation as u64 {
Err(format!("Cannot configure pox_2_activation at a lower height than the Epoch 2.1 start height. pox_2_activation = {}, epoch 2.1 start height = {}", pox_2_activation, last_epoch.start_height))?;
}
}
Ok(out_epochs)
}
pub fn from_config_file(config_file: ConfigFile) -> Result<Config, String> {
let default_node_config = NodeConfig::default();
let mut has_require_affirmed_anchor_blocks = false;
let (mut node, bootstrap_node, deny_nodes) = match config_file.node {
Some(node) => {
let rpc_bind = node.rpc_bind.unwrap_or(default_node_config.rpc_bind);
let node_config = NodeConfig {
name: node.name.unwrap_or(default_node_config.name),
seed: match node.seed {
Some(seed) => hex_bytes(&seed)
.map_err(|_e| format!("node.seed should be a hex encoded string"))?,
None => default_node_config.seed,
},
working_dir: std::env::var("STACKS_WORKING_DIR")
.unwrap_or(node.working_dir.unwrap_or(default_node_config.working_dir)),
rpc_bind: rpc_bind.clone(),
p2p_bind: node.p2p_bind.unwrap_or(default_node_config.p2p_bind),
p2p_address: node.p2p_address.unwrap_or(rpc_bind.clone()),
bootstrap_node: vec![],
deny_nodes: vec![],
data_url: match node.data_url {
Some(data_url) => data_url,
None => format!("http://{}", rpc_bind),
},
local_peer_seed: match node.local_peer_seed {
Some(seed) => hex_bytes(&seed).map_err(|_e| {
format!("node.local_peer_seed should be a hex encoded string")
})?,
None => default_node_config.local_peer_seed,
},
miner: node.miner.unwrap_or(default_node_config.miner),
mock_mining: node.mock_mining.unwrap_or(default_node_config.mock_mining),
mine_microblocks: node
.mine_microblocks
.unwrap_or(default_node_config.mine_microblocks),
microblock_frequency: node
.microblock_frequency
.unwrap_or(default_node_config.microblock_frequency),
max_microblocks: node
.max_microblocks
.unwrap_or(default_node_config.max_microblocks),
wait_time_for_microblocks: node
.wait_time_for_microblocks
.unwrap_or(default_node_config.wait_time_for_microblocks),
wait_time_for_blocks: node
.wait_time_for_blocks
.unwrap_or(default_node_config.wait_time_for_blocks),
prometheus_bind: node.prometheus_bind,
marf_cache_strategy: node.marf_cache_strategy,
marf_defer_hashing: node
.marf_defer_hashing
.unwrap_or(default_node_config.marf_defer_hashing),
pox_sync_sample_secs: node
.pox_sync_sample_secs
.unwrap_or(default_node_config.pox_sync_sample_secs),
use_test_genesis_chainstate: node.use_test_genesis_chainstate,
always_use_affirmation_maps: node
.always_use_affirmation_maps
.unwrap_or(default_node_config.always_use_affirmation_maps),
// miners should always try to mine, even if they don't have the anchored
// blocks in the canonical affirmation map. Followers, however, can stall.
require_affirmed_anchor_blocks: match node.require_affirmed_anchor_blocks {
Some(x) => {
has_require_affirmed_anchor_blocks = true;
x
}
None => {
has_require_affirmed_anchor_blocks = false;
!node.miner.unwrap_or(!default_node_config.miner)
}
},
// chainstate fault_injection activation for hide_blocks.
// you can't set this in the config file.
fault_injection_hide_blocks: false,
chain_liveness_poll_time_secs: node
.chain_liveness_poll_time_secs
.unwrap_or(default_node_config.chain_liveness_poll_time_secs),
};
(node_config, node.bootstrap_node, node.deny_nodes)
}
None => (default_node_config, None, None),
};
let default_burnchain_config = BurnchainConfig::default();
let burnchain = match config_file.burnchain {
Some(mut burnchain) => {
if burnchain.mode.as_deref() == Some("xenon") {
if burnchain.magic_bytes.is_none() {
burnchain.magic_bytes = ConfigFile::xenon().burnchain.unwrap().magic_bytes;
}
}
let burnchain_mode = burnchain.mode.unwrap_or(default_burnchain_config.mode);
if &burnchain_mode == "mainnet" {
// check magic bytes and set if not defined
let mainnet_magic = ConfigFile::mainnet().burnchain.unwrap().magic_bytes;
if burnchain.magic_bytes.is_none() {
burnchain.magic_bytes = mainnet_magic.clone();
}
if burnchain.magic_bytes != mainnet_magic {
return Err(format!(
"Attempted to run mainnet node with bad magic bytes '{}'",
burnchain.magic_bytes.as_ref().unwrap()
));
}
if node.use_test_genesis_chainstate == Some(true) {
return Err(format!(
"Attempted to run mainnet node with `use_test_genesis_chainstate`"
));
}
if let Some(ref balances) = config_file.ustx_balance {
if balances.len() > 0 {
return Err(format!(
"Attempted to run mainnet node with specified `initial_balances`"
));
}
}
} else {
// testnet requires that we use the 2.05 rules for anchor block affirmations,
// because reward cycle 360 (and possibly future ones) has a different anchor
// block choice in 2.05 rules than in 2.1 rules.
if !has_require_affirmed_anchor_blocks {
debug!("Set `require_affirmed_anchor_blocks` to `false` for non-mainnet config");
node.require_affirmed_anchor_blocks = false;
}
}
let mut result = BurnchainConfig {
chain: burnchain.chain.unwrap_or(default_burnchain_config.chain),
chain_id: if &burnchain_mode == "mainnet" {
CHAIN_ID_MAINNET
} else {
CHAIN_ID_TESTNET
},
peer_version: if &burnchain_mode == "mainnet" {
PEER_VERSION_MAINNET
} else {
PEER_VERSION_TESTNET
},
mode: burnchain_mode,
burn_fee_cap: burnchain
.burn_fee_cap
.unwrap_or(default_burnchain_config.burn_fee_cap),
commit_anchor_block_within: burnchain
.commit_anchor_block_within
.unwrap_or(default_burnchain_config.commit_anchor_block_within),
peer_host: match burnchain.peer_host {
Some(peer_host) => {
// Using std::net::LookupHost would be preferable, but it's
// unfortunately unstable at this point.
// https://doc.rust-lang.org/1.6.0/std/net/struct.LookupHost.html
let mut sock_addrs = format!("{}:1", &peer_host)
.to_socket_addrs()
.map_err(|e| format!("Invalid burnchain.peer_host: {}", &e))?;
let sock_addr = match sock_addrs.next() {
Some(addr) => addr,
None => {
return Err(format!(
"No IP address could be queried for '{}'",
&peer_host
));
}
};
format!("{}", sock_addr.ip())
}
None => default_burnchain_config.peer_host,
},
peer_port: burnchain
.peer_port
.unwrap_or(default_burnchain_config.peer_port),
rpc_port: burnchain
.rpc_port
.unwrap_or(default_burnchain_config.rpc_port),
rpc_ssl: burnchain
.rpc_ssl
.unwrap_or(default_burnchain_config.rpc_ssl),
username: burnchain.username,
password: burnchain.password,
timeout: burnchain
.timeout
.unwrap_or(default_burnchain_config.timeout),
magic_bytes: burnchain
.magic_bytes
.map(|magic_ascii| {
assert_eq!(magic_ascii.len(), 2, "Magic bytes must be length-2");
assert!(magic_ascii.is_ascii(), "Magic bytes must be ASCII");
MagicBytes::from(magic_ascii.as_bytes())
})
.unwrap_or(default_burnchain_config.magic_bytes),
local_mining_public_key: burnchain.local_mining_public_key,
process_exit_at_block_height: burnchain.process_exit_at_block_height,
poll_time_secs: burnchain
.poll_time_secs
.unwrap_or(default_burnchain_config.poll_time_secs),
satoshis_per_byte: burnchain
.satoshis_per_byte
.unwrap_or(default_burnchain_config.satoshis_per_byte),
max_rbf: burnchain
.max_rbf
.unwrap_or(default_burnchain_config.max_rbf),
leader_key_tx_estimated_size: burnchain
.leader_key_tx_estimated_size
.unwrap_or(default_burnchain_config.leader_key_tx_estimated_size),
block_commit_tx_estimated_size: burnchain
.block_commit_tx_estimated_size
.unwrap_or(default_burnchain_config.block_commit_tx_estimated_size),
rbf_fee_increment: burnchain
.rbf_fee_increment
.unwrap_or(default_burnchain_config.rbf_fee_increment),
// will be overwritten below
epochs: default_burnchain_config.epochs,
ast_precheck_size_height: burnchain.ast_precheck_size_height,
pox_2_activation: burnchain
.pox_2_activation
.or(default_burnchain_config.pox_2_activation),
sunset_start: burnchain
.sunset_start
.or(default_burnchain_config.sunset_start),
sunset_end: burnchain.sunset_end.or(default_burnchain_config.sunset_end),
wallet_name: burnchain
.wallet_name
.unwrap_or(default_burnchain_config.wallet_name.clone()),
};
if let BitcoinNetworkType::Mainnet = result.get_bitcoin_network().1 {
// check that pox_2_activation hasn't been set in mainnet
if result.pox_2_activation.is_some()
|| result.sunset_start.is_some()
|| result.sunset_end.is_some()
{
return Err("PoX-2 parameters are not configurable in mainnet".into());
}
}
if let Some(ref conf_epochs) = burnchain.epochs {
result.epochs = Some(Self::make_epochs(
conf_epochs,
&result.mode,
result.get_bitcoin_network().1,
burnchain.pox_2_activation,
)?);
}
result
}
None => default_burnchain_config,
};
let miner_default_config = MinerConfig::default();
let miner = match config_file.miner {
Some(ref miner) => MinerConfig {
min_tx_fee: miner.min_tx_fee.unwrap_or(miner_default_config.min_tx_fee),
first_attempt_time_ms: miner
.first_attempt_time_ms
.unwrap_or(miner_default_config.first_attempt_time_ms),
subsequent_attempt_time_ms: miner
.subsequent_attempt_time_ms
.unwrap_or(miner_default_config.subsequent_attempt_time_ms),
microblock_attempt_time_ms: miner
.microblock_attempt_time_ms
.unwrap_or(miner_default_config.microblock_attempt_time_ms),
probability_pick_no_estimate_tx: miner
.probability_pick_no_estimate_tx
.unwrap_or(miner_default_config.probability_pick_no_estimate_tx),
block_reward_recipient: miner.block_reward_recipient.as_ref().map(|c| {
PrincipalData::parse(&c)
.expect(&format!("FATAL: not a valid principal identifier: {}", c))
}),
segwit: miner.segwit.unwrap_or(miner_default_config.segwit),
wait_for_block_download: miner_default_config.wait_for_block_download,
nonce_cache_size: miner
.nonce_cache_size
.unwrap_or(miner_default_config.nonce_cache_size),
candidate_retry_cache_size: miner
.candidate_retry_cache_size
.unwrap_or(miner_default_config.candidate_retry_cache_size),
unprocessed_block_deadline_secs: miner
.unprocessed_block_deadline_secs
.unwrap_or(miner_default_config.unprocessed_block_deadline_secs),
},
None => miner_default_config,
};
let supported_modes = vec![
"mocknet", "helium", "neon", "argon", "krypton", "xenon", "mainnet",
];
if !supported_modes.contains(&burnchain.mode.as_str()) {
return Err(format!(
"Setting burnchain.network not supported (should be: {})",
supported_modes.join(", ")
));
}
if burnchain.mode == "helium" && burnchain.local_mining_public_key.is_none() {
return Err(format!("Config is missing the setting `burnchain.local_mining_public_key` (mandatory for helium)"));
}
if let Some(bootstrap_node) = bootstrap_node {
node.set_bootstrap_nodes(bootstrap_node, burnchain.chain_id, burnchain.peer_version);
} else {
if burnchain.mode == "mainnet" {
let bootstrap_node = ConfigFile::mainnet().node.unwrap().bootstrap_node.unwrap();
node.set_bootstrap_nodes(
bootstrap_node,
burnchain.chain_id,
burnchain.peer_version,
);
}
}
if let Some(deny_nodes) = deny_nodes {
node.set_deny_nodes(deny_nodes, burnchain.chain_id, burnchain.peer_version);
}
let initial_balances: Vec<InitialBalance> = match config_file.ustx_balance {
Some(balances) => balances
.iter()
.map(|balance| {
let address: PrincipalData =
PrincipalData::parse_standard_principal(&balance.address)
.unwrap()
.into();
InitialBalance {
address,
amount: balance.amount,
}
})
.collect(),
None => vec![],
};
let mut events_observers = match config_file.events_observer {
Some(raw_observers) => {
let mut observers = vec![];
for observer in raw_observers {
let events_keys: Vec<EventKeyType> = observer
.events_keys
.iter()
.map(|e| EventKeyType::from_string(e).unwrap())
.collect();
let endpoint = format!("{}", observer.endpoint);
observers.push(EventObserverConfig {
endpoint,
events_keys,
});
}
observers
}
None => vec![],
};
// check for observer config in env vars
match std::env::var("STACKS_EVENT_OBSERVER") {
Ok(val) => events_observers.push(EventObserverConfig {
endpoint: val,
events_keys: vec![EventKeyType::AnyEvent],
}),
_ => (),
};
let connection_options = match config_file.connection_options {
Some(opts) => {
let ip_addr = match opts.public_ip_address {
Some(public_ip_address) => {
let addr = public_ip_address.parse::<SocketAddr>().unwrap();
debug!("addr.parse {:?}", addr);
Some((PeerAddress::from_socketaddr(&addr), addr.port()))
}
None => None,
};
let mut read_only_call_limit = HELIUM_DEFAULT_CONNECTION_OPTIONS
.read_only_call_limit
.clone();
opts.read_only_call_limit_write_length.map(|x| {
read_only_call_limit.write_length = x;
});
opts.read_only_call_limit_write_count.map(|x| {
read_only_call_limit.write_count = x;
});
opts.read_only_call_limit_read_length.map(|x| {
read_only_call_limit.read_length = x;
});
opts.read_only_call_limit_read_count.map(|x| {
read_only_call_limit.read_count = x;
});
opts.read_only_call_limit_runtime.map(|x| {
read_only_call_limit.runtime = x;
});
ConnectionOptions {
read_only_call_limit,
inbox_maxlen: opts
.inbox_maxlen
.unwrap_or_else(|| HELIUM_DEFAULT_CONNECTION_OPTIONS.inbox_maxlen.clone()),
outbox_maxlen: opts
.outbox_maxlen
.unwrap_or_else(|| HELIUM_DEFAULT_CONNECTION_OPTIONS.outbox_maxlen.clone()),
timeout: opts
.timeout
.unwrap_or_else(|| HELIUM_DEFAULT_CONNECTION_OPTIONS.timeout.clone()),
idle_timeout: opts
.idle_timeout
.unwrap_or_else(|| HELIUM_DEFAULT_CONNECTION_OPTIONS.idle_timeout.clone()),
heartbeat: opts