-
Notifications
You must be signed in to change notification settings - Fork 674
/
config.rs
3261 lines (3023 loc) · 130 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
// Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation
// Copyright (C) 2020-2024 Stacks Open Internet Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
use std::collections::{HashMap, HashSet};
use std::net::{Ipv4Addr, SocketAddr, ToSocketAddrs};
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use std::{cmp, fs, thread};
use clarity::vm::costs::ExecutionCost;
use clarity::vm::types::{AssetIdentifier, PrincipalData, QualifiedContractIdentifier};
use lazy_static::lazy_static;
use rand::RngCore;
use serde::Deserialize;
use stacks::burnchains::affirmation::AffirmationMap;
use stacks::burnchains::bitcoin::BitcoinNetworkType;
use stacks::burnchains::{Burnchain, MagicBytes, PoxConstants, BLOCKSTACK_MAGIC_MAINNET};
use stacks::chainstate::nakamoto::signer_set::NakamotoSigners;
use stacks::chainstate::stacks::boot::MINERS_NAME;
use stacks::chainstate::stacks::index::marf::MARFOpenOpts;
use stacks::chainstate::stacks::index::storage::TrieHashCalculationMode;
use stacks::chainstate::stacks::miner::{BlockBuilderSettings, MinerStatus};
use stacks::chainstate::stacks::MAX_BLOCK_LEN;
use stacks::core::mempool::{MemPoolWalkSettings, MemPoolWalkTxTypes};
use stacks::core::{
MemPoolDB, StacksEpoch, StacksEpochExtension, StacksEpochId,
BITCOIN_TESTNET_FIRST_BLOCK_HEIGHT, BITCOIN_TESTNET_STACKS_25_BURN_HEIGHT,
BITCOIN_TESTNET_STACKS_25_REORGED_HEIGHT, 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, ProportionalDotProduct, UnitMetric};
use stacks::cost_estimates::{CostEstimator, FeeEstimator, PessimisticEstimator, UnitEstimator};
use stacks::net::atlas::AtlasConfig;
use stacks::net::connection::ConnectionOptions;
use stacks::net::{Neighbor, NeighborKey};
use stacks::types::chainstate::BurnchainHeaderHash;
use stacks::types::EpochList;
use stacks::util_lib::boot::boot_code_id;
use stacks::util_lib::db::Error as DBError;
use stacks_common::consts::SIGNER_SLOTS_PER_USER;
use stacks_common::types::chainstate::StacksAddress;
use stacks_common::types::net::PeerAddress;
use stacks_common::types::Address;
use stacks_common::util::get_epoch_time_ms;
use stacks_common::util::hash::hex_bytes;
use stacks_common::util::secp256k1::{Secp256k1PrivateKey, Secp256k1PublicKey};
use crate::chain_data::MinerStats;
pub const DEFAULT_SATS_PER_VB: u64 = 50;
pub const OP_TX_BLOCK_COMMIT_ESTIM_SIZE: u64 = 380;
pub const OP_TX_DELEGATE_STACKS_ESTIM_SIZE: u64 = 230;
pub const OP_TX_LEADER_KEY_ESTIM_SIZE: u64 = 290;
pub const OP_TX_PRE_STACKS_ESTIM_SIZE: u64 = 280;
pub const OP_TX_STACK_STX_ESTIM_SIZE: u64 = 250;
pub const OP_TX_TRANSFER_STACKS_ESTIM_SIZE: u64 = 230;
pub const OP_TX_VOTE_AGG_ESTIM_SIZE: u64 = 230;
pub const OP_TX_ANY_ESTIM_SIZE: u64 = fmax!(
OP_TX_BLOCK_COMMIT_ESTIM_SIZE,
OP_TX_DELEGATE_STACKS_ESTIM_SIZE,
OP_TX_LEADER_KEY_ESTIM_SIZE,
OP_TX_PRE_STACKS_ESTIM_SIZE,
OP_TX_STACK_STX_ESTIM_SIZE,
OP_TX_TRANSFER_STACKS_ESTIM_SIZE,
OP_TX_VOTE_AGG_ESTIM_SIZE
);
const DEFAULT_MAX_RBF_RATE: u64 = 150; // 1.5x
const DEFAULT_RBF_FEE_RATE_INCREMENT: u64 = 5;
const INV_REWARD_CYCLES_TESTNET: u64 = 6;
const DEFAULT_MIN_TIME_BETWEEN_BLOCKS_MS: u64 = 1_000;
const DEFAULT_FIRST_REJECTION_PAUSE_MS: u64 = 5_000;
const DEFAULT_SUBSEQUENT_REJECTION_PAUSE_MS: u64 = 10_000;
const DEFAULT_BLOCK_COMMIT_DELAY_MS: u64 = 20_000;
const DEFAULT_TENURE_COST_LIMIT_PER_BLOCK_PERCENTAGE: u8 = 25;
#[derive(Clone, Deserialize, Default, Debug)]
#[serde(deny_unknown_fields)]
pub struct ConfigFile {
pub __path: Option<String>, // Only used for config file reloads
pub burnchain: Option<BurnchainConfigFile>,
pub node: Option<NodeConfigFile>,
pub ustx_balance: Option<Vec<InitialBalanceFile>>,
/// Deprecated: use `ustx_balance` instead
pub mstx_balance: Option<Vec<InitialBalanceFile>>,
pub events_observer: Option<HashSet<EventObserverConfigFile>>,
pub connection_options: Option<ConnectionOptionsFile>,
pub fee_estimation: Option<FeeEstimationConfigFile>,
pub miner: Option<MinerConfigFile>,
pub atlas: Option<AtlasConfigFile>,
}
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}"))?;
let mut f = Self::from_str(&content)?;
f.__path = Some(path.to_string());
Ok(f)
}
#[allow(clippy::should_implement_trait)]
pub fn from_str(content: &str) -> Result<ConfigFile, String> {
let mut config: ConfigFile =
toml::from_str(content).map_err(|e| format!("Invalid toml: {e}"))?;
if let Some(mstx_balance) = config.mstx_balance.take() {
warn!("'mstx_balance' in the config is deprecated; please use 'ustx_balance' instead.");
match config.ustx_balance {
Some(ref mut ustx_balance) => {
ustx_balance.extend(mstx_balance);
}
None => {
config.ustx_balance = Some(mstx_balance);
}
}
}
Ok(config)
}
pub fn xenon() -> ConfigFile {
let mut burnchain = BurnchainConfigFile {
mode: Some("xenon".to_string()),
rpc_port: Some(18332),
peer_port: Some(18333),
peer_host: Some("bitcoind.testnet.stacks.co".to_string()),
magic_bytes: Some("T2".into()),
..BurnchainConfigFile::default()
};
burnchain.add_affirmation_overrides_xenon();
let node = NodeConfigFile {
bootstrap_node: Some("029266faff4c8e0ca4f934f34996a96af481df94a89b0c9bd515f3536a95682ddc@seed.testnet.hiro.so:30444".to_string()),
miner: Some(false),
stacker: 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,02539449ad94e6e6392d8c1deb2b4e61f80ae2a18964349bc14336d8b903c46a8c@cet.stacksnodes.org:20444,02ececc8ce79b8adf813f13a0255f8ae58d4357309ba0cedd523d9f1a306fcfb79@sgt.stacksnodes.org:20444,0303144ba518fe7a0fb56a8a7d488f950307a4330f146e1e1458fc63fb33defe96@est.stacksnodes.org:20444".to_string()),
miner: Some(false),
stacker: 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),
stacker: 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),
stacker: 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 config_path: Option<String>,
pub burnchain: BurnchainConfig,
pub node: NodeConfig,
pub initial_balances: Vec<InitialBalance>,
pub events_observers: HashSet<EventObserverConfig>,
pub connection_options: ConnectionOptions,
pub miner: MinerConfig,
pub estimation: FeeEstimationConfig,
pub atlas: AtlasConfig,
}
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: 32, // 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
walk_seed_probability: 0.1, // 10% of the time when not in IBD, walk to a non-seed node even if we aren't connected to a seed node
log_neighbors_freq: 60_000, // every minute, log all peer connections
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 {
/// get the up-to-date burnchain options from the config.
/// If the config file can't be loaded, then return the existing config
pub fn get_burnchain_config(&self) -> BurnchainConfig {
let Some(path) = &self.config_path else {
return self.burnchain.clone();
};
let Ok(config_file) = ConfigFile::from_path(path.as_str()) else {
return self.burnchain.clone();
};
let Ok(config) = Config::from_config_file(config_file, false) else {
return self.burnchain.clone();
};
config.burnchain
}
/// get the up-to-date miner options from the config
/// If the config can't be loaded for some reason, then return the existing config
pub fn get_miner_config(&self) -> MinerConfig {
let Some(path) = &self.config_path else {
return self.miner.clone();
};
let Ok(config_file) = ConfigFile::from_path(path.as_str()) else {
return self.miner.clone();
};
let Ok(config) = Config::from_config_file(config_file, false) else {
return self.miner.clone();
};
config.miner
}
pub fn get_node_config(&self, resolve_bootstrap_nodes: bool) -> NodeConfig {
let Some(path) = &self.config_path else {
return self.node.clone();
};
let Ok(config_file) = ConfigFile::from_path(path.as_str()) else {
return self.node.clone();
};
let Ok(config) = Config::from_config_file(config_file, resolve_bootstrap_nodes) else {
return self.node.clone();
};
config.node
}
/// Apply any test settings to this burnchain config struct
#[cfg_attr(test, mutants::skip)]
fn apply_test_settings(&self, burnchain: &mut Burnchain) {
if self.burnchain.get_bitcoin_network().1 == BitcoinNetworkType::Mainnet {
return;
}
if let Some(first_burn_block_height) = self.burnchain.first_burn_block_height {
debug!(
"Override first_block_height from {} to {first_burn_block_height}",
burnchain.first_block_height
);
burnchain.first_block_height = first_burn_block_height;
}
if let Some(first_burn_block_timestamp) = self.burnchain.first_burn_block_timestamp {
debug!(
"Override first_block_timestamp from {} to {first_burn_block_timestamp}",
burnchain.first_block_timestamp
);
burnchain.first_block_timestamp = first_burn_block_timestamp;
}
if let Some(first_burn_block_hash) = &self.burnchain.first_burn_block_hash {
debug!(
"Override first_burn_block_hash from {} to {first_burn_block_hash}",
burnchain.first_block_hash
);
burnchain.first_block_hash = BurnchainHeaderHash::from_hex(first_burn_block_hash)
.expect("Invalid first_burn_block_hash");
}
if let Some(pox_prepare_length) = self.burnchain.pox_prepare_length {
debug!("Override pox_prepare_length to {pox_prepare_length}");
burnchain.pox_constants.prepare_length = pox_prepare_length;
}
if let Some(pox_reward_length) = self.burnchain.pox_reward_length {
debug!("Override pox_reward_length to {pox_reward_length}");
burnchain.pox_constants.reward_cycle_length = pox_reward_length;
}
if let Some(v1_unlock_height) = self.burnchain.pox_2_activation {
debug!(
"Override v1_unlock_height from {} to {v1_unlock_height}",
burnchain.pox_constants.v1_unlock_height
);
burnchain.pox_constants.v1_unlock_height = v1_unlock_height;
}
if let Some(epochs) = &self.burnchain.epochs {
if let Some(epoch) = epochs.get(StacksEpochId::Epoch10) {
// Epoch 1.0 start height can be equal to the first block height iff epoch 2.0
// start height is also equal to the first block height.
assert!(
epoch.start_height <= burnchain.first_block_height,
"FATAL: Epoch 1.0 start height must be at or before the first block height"
);
}
if let Some(epoch) = epochs.get(StacksEpochId::Epoch20) {
assert_eq!(
epoch.start_height, burnchain.first_block_height,
"FATAL: Epoch 2.0 start height must match the first block height"
);
}
if let Some(epoch) = epochs.get(StacksEpochId::Epoch21) {
// Override v1_unlock_height to the start_height of epoch2.1
debug!(
"Override v2_unlock_height from {} to {}",
burnchain.pox_constants.v1_unlock_height,
epoch.start_height + 1
);
burnchain.pox_constants.v1_unlock_height = epoch.start_height as u32 + 1;
}
if let Some(epoch) = epochs.get(StacksEpochId::Epoch22) {
// Override v2_unlock_height to the start_height of epoch2.2
debug!(
"Override v2_unlock_height from {} to {}",
burnchain.pox_constants.v2_unlock_height,
epoch.start_height + 1
);
burnchain.pox_constants.v2_unlock_height = epoch.start_height as u32 + 1;
}
if let Some(epoch) = epochs.get(StacksEpochId::Epoch24) {
// Override pox_3_activation_height to the start_height of epoch2.4
debug!(
"Override pox_3_activation_height from {} to {}",
burnchain.pox_constants.pox_3_activation_height, epoch.start_height
);
burnchain.pox_constants.pox_3_activation_height = epoch.start_height as u32;
}
if let Some(epoch) = epochs.get(StacksEpochId::Epoch25) {
// Override pox_4_activation_height to the start_height of epoch2.5
debug!(
"Override pox_4_activation_height from {} to {}",
burnchain.pox_constants.pox_4_activation_height, epoch.start_height
);
burnchain.pox_constants.pox_4_activation_height = epoch.start_height as u32;
burnchain.pox_constants.v3_unlock_height = epoch.start_height as u32 + 1;
}
}
if let Some(sunset_start) = self.burnchain.sunset_start {
debug!(
"Override sunset_start from {} to {sunset_start}",
burnchain.pox_constants.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 {sunset_end}",
burnchain.pox_constants.sunset_end
);
burnchain.pox_constants.sunset_end = sunset_end.into();
}
// check if the Epoch 3.0 burnchain settings as configured are going to be valid.
self.check_nakamoto_config(burnchain);
}
fn check_nakamoto_config(&self, burnchain: &Burnchain) {
let epochs = StacksEpoch::get_epochs(
self.burnchain.get_bitcoin_network().1,
self.burnchain.epochs.as_ref(),
);
let Some(epoch_30) = epochs.get(StacksEpochId::Epoch30) else {
// no Epoch 3.0, so just return
return;
};
if burnchain.pox_constants.prepare_length < 3 {
panic!(
"FATAL: Nakamoto rules require a prepare length >= 3. Prepare length set to {}",
burnchain.pox_constants.prepare_length
);
}
if burnchain.is_in_prepare_phase(epoch_30.start_height) {
panic!(
"FATAL: Epoch 3.0 must start *during* a reward phase, not a prepare phase. Epoch 3.0 start set to: {}. PoX Parameters: {:?}",
epoch_30.start_height,
&burnchain.pox_constants
);
}
let activation_reward_cycle = burnchain
.block_height_to_reward_cycle(epoch_30.start_height)
.expect("FATAL: Epoch 3.0 starts before the first burnchain block");
if activation_reward_cycle < 2 {
panic!(
"FATAL: Epoch 3.0 must start at or after the second reward cycle. Epoch 3.0 start set to: {}. PoX Parameters: {:?}",
epoch_30.start_height,
&burnchain.pox_constants
);
}
}
/// Connect to the MempoolDB using the configured cost estimation
pub fn connect_mempool_db(&self) -> Result<MemPoolDB, DBError> {
// create estimators, metric instances for RPC handler
let cost_estimator = self
.make_cost_estimator()
.unwrap_or_else(|| Box::new(UnitEstimator));
let metric = self
.make_cost_metric()
.unwrap_or_else(|| Box::new(UnitMetric));
MemPoolDB::open(
self.is_mainnet(),
self.burnchain.chain_id,
&self.get_chainstate_path_str(),
cost_estimator,
metric,
)
}
/// 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: {v1_unlock_height} <= {}\nburnchain: {burnchain:?}", epoch21.start_height
);
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:?}"
);
}
}
// TODO: add tests from mutation testing results #4866
#[cfg_attr(test, mutants::skip)]
fn make_epochs(
conf_epochs: &[StacksEpochConfigFile],
burn_mode: &str,
bitcoin_network: BitcoinNetworkType,
pox_2_activation: Option<u32>,
) -> Result<EpochList<ExecutionCost>, 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 if epoch_name == EPOCH_CONFIG_2_2_0 {
Ok(StacksEpochId::Epoch22)
} else if epoch_name == EPOCH_CONFIG_2_3_0 {
Ok(StacksEpochId::Epoch23)
} else if epoch_name == EPOCH_CONFIG_2_4_0 {
Ok(StacksEpochId::Epoch24)
} else if epoch_name == EPOCH_CONFIG_2_5_0 {
Ok(StacksEpochId::Epoch25)
} else if epoch_name == EPOCH_CONFIG_3_0_0 {
Ok(StacksEpochId::Epoch30)
} 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(),
);
}
let expected_list = [
StacksEpochId::Epoch10,
StacksEpochId::Epoch20,
StacksEpochId::Epoch2_05,
StacksEpochId::Epoch21,
StacksEpochId::Epoch22,
StacksEpochId::Epoch23,
StacksEpochId::Epoch24,
StacksEpochId::Epoch25,
StacksEpochId::Epoch30,
];
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 = {expected_epoch}, Found 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 = {epoch_id}, Configured = {}",
&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 = {pox_2_activation}, epoch 2.1 start height = {}", last_epoch.start_height))?;
}
}
Ok(EpochList::new(&out_epochs))
}
pub fn from_config_file(
config_file: ConfigFile,
resolve_bootstrap_nodes: bool,
) -> Result<Config, String> {
Self::from_config_default(config_file, Config::default(), resolve_bootstrap_nodes)
}
fn from_config_default(
config_file: ConfigFile,
default: Config,
resolve_bootstrap_nodes: bool,
) -> Result<Config, String> {
let Config {
node: default_node_config,
burnchain: default_burnchain_config,
miner: miner_default_config,
estimation: default_estimator,
..
} = default;
// First parse the burnchain config
let burnchain = match config_file.burnchain {
Some(burnchain) => burnchain.into_config_default(default_burnchain_config)?,
None => default_burnchain_config,
};
let supported_modes = [
"mocknet",
"helium",
"neon",
"argon",
"krypton",
"xenon",
"mainnet",
"nakamoto-neon",
];
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("Config is missing the setting `burnchain.local_mining_public_key` (mandatory for helium)".into());
}
let is_mainnet = burnchain.mode == "mainnet";
// Parse the node config
let (mut node, bootstrap_node, deny_nodes) = match config_file.node {
Some(node) => {
let deny_nodes = node.deny_nodes.clone();
let bootstrap_node = node.bootstrap_node.clone();
let node_config = node.into_config_default(default_node_config)?;
(node_config, bootstrap_node, deny_nodes)
}
None => (default_node_config, None, None),
};
if let Some(bootstrap_node) = bootstrap_node {
if resolve_bootstrap_nodes {
node.set_bootstrap_nodes(
bootstrap_node,
burnchain.chain_id,
burnchain.peer_version,
);
}
} else if is_mainnet && resolve_bootstrap_nodes {
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);
}
// Validate the node config
if is_mainnet && node.use_test_genesis_chainstate == Some(true) {
return Err("Attempted to run mainnet node with `use_test_genesis_chainstate`".into());
}
if node.stacker || node.miner {
node.add_miner_stackerdb(is_mainnet);
node.add_signers_stackerdbs(is_mainnet);
}
let miner = match config_file.miner {
Some(miner) => miner.into_config_default(miner_default_config)?,
None => miner_default_config,
};
let initial_balances: Vec<InitialBalance> = match config_file.ustx_balance {
Some(balances) => {
if is_mainnet && !balances.is_empty() {
return Err(
"Attempted to run mainnet node with specified `initial_balances`".into(),
);
}
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 = HashSet::new();
for observer in raw_observers {
let events_keys: Vec<EventKeyType> = observer
.events_keys
.iter()
.map(|e| EventKeyType::from_string(e).unwrap())
.collect();
observers.insert(EventObserverConfig {
endpoint: observer.endpoint,
events_keys,
timeout_ms: observer.timeout_ms.unwrap_or(1_000),
});
}
observers
}
None => HashSet::new(),
};
// check for observer config in env vars
if let Ok(val) = std::env::var("STACKS_EVENT_OBSERVER") {
events_observers.insert(EventObserverConfig {
endpoint: val,
events_keys: vec![EventKeyType::AnyEvent],
timeout_ms: 1_000,
});
};
let connection_options = match config_file.connection_options {
Some(opts) => opts.into_config(is_mainnet)?,
None => HELIUM_DEFAULT_CONNECTION_OPTIONS.clone(),
};
let estimation = match config_file.fee_estimation {
Some(f) => FeeEstimationConfig::from(f),
None => default_estimator,
};
let atlas = match config_file.atlas {
Some(f) => f.into_config(is_mainnet),
None => AtlasConfig::new(is_mainnet),
};
atlas
.validate()
.map_err(|e| format!("Atlas config error: {e}"))?;
if miner.mining_key.is_none() && miner.pre_nakamoto_mock_signing {
return Err("Cannot use pre_nakamoto_mock_signing without a mining_key".to_string());
}
Ok(Config {
config_path: config_file.__path,
node,
burnchain,
initial_balances,
events_observers,
connection_options,
estimation,
miner,
atlas,
})
}
/// Returns the path working directory path, and ensures it exists.
pub fn get_working_dir(&self) -> PathBuf {
let path = PathBuf::from(&self.node.working_dir);
fs::create_dir_all(&path).unwrap_or_else(|_| {
panic!(
"Failed to create working directory at {}",
path.to_string_lossy()
)
});
path
}
fn get_burnchain_path(&self) -> PathBuf {
let mut path = PathBuf::from(&self.node.working_dir);
path.push(&self.burnchain.mode);
path.push("burnchain");
path
}
pub fn get_chainstate_path(&self) -> PathBuf {
let mut path = PathBuf::from(&self.node.working_dir);
path.push(&self.burnchain.mode);
path.push("chainstate");
path
}
/// Returns the path `{get_chainstate_path()}/estimates`, and ensures it exists.
pub fn get_estimates_path(&self) -> PathBuf {
let mut path = self.get_chainstate_path();
path.push("estimates");
fs::create_dir_all(&path).unwrap_or_else(|_| {
panic!(
"Failed to create `estimates` directory at {}",
path.to_string_lossy()
)
});
path
}
pub fn get_chainstate_path_str(&self) -> String {
self.get_chainstate_path()
.to_str()
.expect("Unable to produce path")
.to_string()
}
pub fn get_burnchain_path_str(&self) -> String {
self.get_burnchain_path()
.to_str()
.expect("Unable to produce path")
.to_string()
}
pub fn get_burn_db_path(&self) -> String {
self.get_burnchain_path()
.to_str()
.expect("Unable to produce path")
.to_string()
}
pub fn get_burn_db_file_path(&self) -> String {
let mut path = self.get_burnchain_path();
path.push("sortition");
path.to_str().expect("Unable to produce path").to_string()
}
pub fn get_spv_headers_file_path(&self) -> String {
let mut path = self.get_burnchain_path();
path.set_file_name("headers.sqlite");
path.to_str().expect("Unable to produce path").to_string()
}