• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

stacks-network / stacks-core / 23943353420

03 Apr 2026 10:35AM UTC coverage: 77.562% (-8.2%) from 85.712%
23943353420

Pull #7078

github

09bba5
web-flow
Merge 3c3fa993b into c529ad924
Pull Request #7078: feat: add Clarity side-table copy and validation

3645 of 4204 new or added lines in 18 files covered. (86.7%)

19325 existing lines in 183 files now uncovered.

171986 of 221739 relevant lines covered (77.56%)

7709430.55 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

87.18
/stacks-node/src/node.rs
1
use std::collections::{HashMap, HashSet};
2
use std::net::SocketAddr;
3
use std::thread::JoinHandle;
4
use std::{env, thread, time};
5

6
use rand::RngCore;
7
use stacks::burnchains::bitcoin::BitcoinNetworkType;
8
use stacks::burnchains::db::BurnchainDB;
9
use stacks::burnchains::{PoxConstants, Txid};
10
use stacks::chainstate::burn::db::sortdb::SortitionDB;
11
use stacks::chainstate::burn::operations::leader_block_commit::{
12
    RewardSetInfo, BURN_BLOCK_MINED_AT_MODULUS,
13
};
14
use stacks::chainstate::burn::operations::{
15
    BlockstackOperationType, LeaderBlockCommitOp, LeaderKeyRegisterOp,
16
};
17
use stacks::chainstate::burn::ConsensusHash;
18
use stacks::chainstate::stacks::address::PoxAddress;
19
use stacks::chainstate::stacks::db::{
20
    ChainStateBootData, ChainstateAccountBalance, ChainstateAccountLockup, ChainstateBNSName,
21
    ChainstateBNSNamespace, ClarityTx, StacksChainState, StacksEpochReceipt, StacksHeaderInfo,
22
};
23
use stacks::chainstate::stacks::events::{
24
    StacksTransactionEvent, StacksTransactionReceipt, TransactionOrigin,
25
};
26
use stacks::chainstate::stacks::{
27
    CoinbasePayload, StacksBlock, StacksMicroblock, StacksTransaction, StacksTransactionSigner,
28
    TransactionAnchorMode, TransactionPayload, TransactionVersion,
29
};
30
use stacks::core::mempool::MemPoolDB;
31
use stacks::core::{EpochList, STACKS_EPOCH_2_1_MARKER};
32
use stacks::cost_estimates::metrics::UnitMetric;
33
use stacks::cost_estimates::UnitEstimator;
34
use stacks::net::atlas::{AtlasConfig, AtlasDB, AttachmentInstance};
35
use stacks::net::db::PeerDB;
36
use stacks::net::p2p::PeerNetwork;
37
use stacks::net::stackerdb::StackerDBs;
38
use stacks::net::RPCHandlerArgs;
39
use stacks::util_lib::strings::UrlString;
40
use stacks_common::types::chainstate::{BlockHeaderHash, BurnchainHeaderHash, TrieHash, VRFSeed};
41
use stacks_common::types::net::PeerAddress;
42
use stacks_common::util::get_epoch_time_secs;
43
use stacks_common::util::hash::Sha256Sum;
44
use stacks_common::util::secp256k1::Secp256k1PrivateKey;
45
use stacks_common::util::vrf::VRFPublicKey;
46

47
use super::{BurnchainController, BurnchainTip, Config, EventDispatcher, Keychain, Tenure};
48
use crate::burnchains::make_bitcoin_indexer;
49
use crate::genesis_data::USE_TEST_GENESIS_CHAINSTATE;
50
use crate::run_loop;
51
use crate::run_loop::RegisteredKey;
52

53
#[derive(Debug, Clone)]
54
pub struct ChainTip {
55
    pub metadata: StacksHeaderInfo,
56
    pub block: StacksBlock,
57
    pub receipts: Vec<StacksTransactionReceipt>,
58
}
59

60
impl ChainTip {
61
    pub fn genesis(
16✔
62
        first_burnchain_block_hash: &BurnchainHeaderHash,
16✔
63
        first_burnchain_block_height: u64,
16✔
64
        first_burnchain_block_timestamp: u64,
16✔
65
    ) -> ChainTip {
16✔
66
        ChainTip {
16✔
67
            metadata: StacksHeaderInfo::genesis(
16✔
68
                TrieHash([0u8; 32]),
16✔
69
                first_burnchain_block_hash,
16✔
70
                first_burnchain_block_height as u32,
16✔
71
                first_burnchain_block_timestamp,
16✔
72
            ),
16✔
73
            block: StacksBlock::genesis_block(),
16✔
74
            receipts: vec![],
16✔
75
        }
16✔
76
    }
16✔
77
}
78

79
/// Node is a structure modelising an active node working on the stacks chain.
80
pub struct Node {
81
    pub chain_state: StacksChainState,
82
    pub config: Config,
83
    active_registered_key: Option<RegisteredKey>,
84
    bootstraping_chain: bool,
85
    pub burnchain_tip: Option<BurnchainTip>,
86
    pub chain_tip: Option<ChainTip>,
87
    keychain: Keychain,
88
    last_sortitioned_block: Option<BurnchainTip>,
89
    event_dispatcher: EventDispatcher,
90
    nonce: u64,
91
    leader_key_registers: HashSet<Txid>,
92
    block_commits: HashSet<Txid>,
93
}
94

95
pub fn get_account_lockups(
8✔
96
    use_test_chainstate_data: bool,
8✔
97
) -> Box<dyn Iterator<Item = ChainstateAccountLockup>> {
8✔
98
    Box::new(
8✔
99
        stx_genesis::GenesisData::new(use_test_chainstate_data)
8✔
100
            .read_lockups()
8✔
101
            .map(|item| ChainstateAccountLockup {
8✔
102
                address: item.address,
160✔
103
                amount: item.amount,
160✔
104
                block_height: item.block_height,
160✔
105
            }),
160✔
106
    )
107
}
8✔
108

109
pub fn get_account_balances(
8✔
110
    use_test_chainstate_data: bool,
8✔
111
) -> Box<dyn Iterator<Item = ChainstateAccountBalance>> {
8✔
112
    Box::new(
8✔
113
        stx_genesis::GenesisData::new(use_test_chainstate_data)
8✔
114
            .read_balances()
8✔
115
            .map(|item| ChainstateAccountBalance {
8✔
116
                address: item.address,
192✔
117
                amount: item.amount,
192✔
118
            }),
192✔
119
    )
120
}
8✔
121

122
pub fn get_namespaces(
8✔
123
    use_test_chainstate_data: bool,
8✔
124
) -> Box<dyn Iterator<Item = ChainstateBNSNamespace>> {
8✔
125
    Box::new(
8✔
126
        stx_genesis::GenesisData::new(use_test_chainstate_data)
8✔
127
            .read_namespaces()
8✔
128
            .map(|item| ChainstateBNSNamespace {
8✔
129
                namespace_id: item.namespace_id,
40✔
130
                importer: item.importer,
40✔
131
                buckets: item.buckets,
40✔
132
                base: item.base as u64,
40✔
133
                coeff: item.coeff as u64,
40✔
134
                nonalpha_discount: item.nonalpha_discount as u64,
40✔
135
                no_vowel_discount: item.no_vowel_discount as u64,
40✔
136
                lifetime: item.lifetime as u64,
40✔
137
            }),
40✔
138
    )
139
}
8✔
140

141
pub fn get_names(use_test_chainstate_data: bool) -> Box<dyn Iterator<Item = ChainstateBNSName>> {
8✔
142
    Box::new(
8✔
143
        stx_genesis::GenesisData::new(use_test_chainstate_data)
8✔
144
            .read_names()
8✔
145
            .map(|item| ChainstateBNSName {
8✔
146
                fully_qualified_name: item.fully_qualified_name,
96✔
147
                owner: item.owner,
96✔
148
                zonefile_hash: item.zonefile_hash,
96✔
149
            }),
96✔
150
    )
151
}
8✔
152

153
// This function is called for helium and mocknet.
154
#[allow(clippy::too_many_arguments)]
155
fn spawn_peer(
8✔
156
    is_mainnet: bool,
8✔
157
    chain_id: u32,
8✔
158
    mut this: PeerNetwork,
8✔
159
    p2p_sock: &SocketAddr,
8✔
160
    rpc_sock: &SocketAddr,
8✔
161
    burn_db_path: String,
8✔
162
    stacks_chainstate_path: String,
8✔
163
    pox_consts: PoxConstants,
8✔
164
    event_dispatcher: EventDispatcher,
8✔
165
    exit_at_block_height: Option<u64>,
8✔
166
    genesis_chainstate_hash: Sha256Sum,
8✔
167
    poll_timeout: u64,
8✔
168
    config: Config,
8✔
169
) -> JoinHandle<()> {
8✔
170
    this.bind(p2p_sock, rpc_sock).unwrap();
8✔
171
    let server_thread = thread::spawn(move || {
8✔
172
        // create estimators, metric instances for RPC handler
173
        let cost_estimator = config
8✔
174
            .make_cost_estimator()
8✔
175
            .unwrap_or_else(|| Box::new(UnitEstimator));
8✔
176
        let metric = config
8✔
177
            .make_cost_metric()
8✔
178
            .unwrap_or_else(|| Box::new(UnitMetric));
8✔
179
        let fee_estimator = config.make_fee_estimator();
8✔
180

181
        let handler_args = RPCHandlerArgs {
8✔
182
            exit_at_block_height,
8✔
183
            cost_estimator: Some(cost_estimator.as_ref()),
8✔
184
            cost_metric: Some(metric.as_ref()),
8✔
185
            fee_estimator: fee_estimator.as_ref().map(|x| x.as_ref()),
8✔
186
            genesis_chainstate_hash,
8✔
187
            ..RPCHandlerArgs::default()
8✔
188
        };
189

190
        loop {
191
            let sortdb = match SortitionDB::open(
166✔
192
                &burn_db_path,
166✔
193
                false,
166✔
194
                pox_consts.clone(),
166✔
195
                Some(config.node.get_marf_opts()),
166✔
196
            ) {
166✔
197
                Ok(x) => x,
166✔
198
                Err(e) => {
×
199
                    warn!("Error while connecting burnchain db in peer loop: {e}");
×
200
                    thread::sleep(time::Duration::from_secs(1));
×
201
                    continue;
×
202
                }
203
            };
204
            let (mut chainstate, _) = match StacksChainState::open(
166✔
205
                is_mainnet,
166✔
206
                chain_id,
166✔
207
                &stacks_chainstate_path,
166✔
208
                Some(config.node.get_marf_opts()),
166✔
209
            ) {
166✔
210
                Ok(x) => x,
166✔
211
                Err(e) => {
×
212
                    warn!("Error while connecting chainstate db in peer loop: {e}");
×
213
                    thread::sleep(time::Duration::from_secs(1));
×
214
                    continue;
×
215
                }
216
            };
217

218
            let estimator = Box::new(UnitEstimator);
166✔
219
            let metric = Box::new(UnitMetric);
166✔
220

221
            let mut mem_pool = match MemPoolDB::open(
166✔
222
                is_mainnet,
166✔
223
                chain_id,
166✔
224
                &stacks_chainstate_path,
166✔
225
                estimator,
166✔
226
                metric,
166✔
227
            ) {
166✔
228
                Ok(x) => x,
166✔
229
                Err(e) => {
×
230
                    warn!("Error while connecting to mempool db in peer loop: {e}");
×
231
                    thread::sleep(time::Duration::from_secs(1));
×
232
                    continue;
×
233
                }
234
            };
235

236
            let indexer = make_bitcoin_indexer(&config, None);
166✔
237

238
            let net_result = this
166✔
239
                .run(
166✔
240
                    &indexer,
166✔
241
                    &sortdb,
166✔
242
                    &mut chainstate,
166✔
243
                    &mut mem_pool,
166✔
244
                    None,
166✔
245
                    false,
246
                    false,
247
                    poll_timeout,
166✔
248
                    &handler_args,
166✔
249
                    config.node.txindex,
166✔
250
                )
251
                .unwrap();
166✔
252
            if net_result.has_transactions() {
166✔
UNCOV
253
                event_dispatcher.process_new_mempool_txs(net_result.transactions())
×
254
            }
158✔
255
            // Dispatch retrieved attachments, if any.
256
            if net_result.has_attachments() {
158✔
257
                event_dispatcher.process_new_attachments(&net_result.attachments);
×
258
            }
158✔
259
        }
260
    });
261
    server_thread
8✔
262
}
8✔
263

264
// Check if the small test genesis chainstate data should be used.
265
// First check env var, then config file, then use default.
266
pub fn use_test_genesis_chainstate(config: &Config) -> bool {
8✔
267
    if env::var("BLOCKSTACK_USE_TEST_GENESIS_CHAINSTATE") == Ok("1".to_string()) {
8✔
268
        true
×
269
    } else if let Some(use_test_genesis_chainstate) = config.node.use_test_genesis_chainstate {
8✔
270
        use_test_genesis_chainstate
×
271
    } else {
272
        USE_TEST_GENESIS_CHAINSTATE
8✔
273
    }
274
}
8✔
275

276
impl Node {
277
    /// Instantiate and initialize a new node, given a config
278
    pub fn new(config: Config, boot_block_exec: Box<dyn FnOnce(&mut ClarityTx)>) -> Self {
8✔
279
        let use_test_genesis_data = if config.burnchain.mode == "mocknet" {
8✔
280
            use_test_genesis_chainstate(&config)
8✔
281
        } else {
282
            USE_TEST_GENESIS_CHAINSTATE
×
283
        };
284

285
        let keychain = Keychain::default(config.node.seed.clone());
8✔
286

287
        let initial_balances = config
8✔
288
            .initial_balances
8✔
289
            .iter()
8✔
290
            .map(|e| (e.address.clone(), e.amount))
522✔
291
            .collect();
8✔
292
        let pox_constants = match config.burnchain.get_bitcoin_network() {
8✔
293
            (_, BitcoinNetworkType::Mainnet) => PoxConstants::mainnet_default(),
×
294
            (_, BitcoinNetworkType::Testnet) => PoxConstants::testnet_default(),
×
295
            (_, BitcoinNetworkType::Regtest) => PoxConstants::regtest_default(),
8✔
296
        };
297

298
        let mut boot_data = ChainStateBootData {
8✔
299
            initial_balances,
8✔
300
            first_burnchain_block_hash: BurnchainHeaderHash::zero(),
8✔
301
            first_burnchain_block_height: 0,
302
            first_burnchain_block_timestamp: 0,
303
            pox_constants,
8✔
304
            post_flight_callback: Some(boot_block_exec),
8✔
305
            get_bulk_initial_lockups: Some(Box::new(move || {
8✔
306
                get_account_lockups(use_test_genesis_data)
8✔
307
            })),
8✔
308
            get_bulk_initial_balances: Some(Box::new(move || {
8✔
309
                get_account_balances(use_test_genesis_data)
8✔
310
            })),
8✔
311
            get_bulk_initial_namespaces: Some(Box::new(move || {
8✔
312
                get_namespaces(use_test_genesis_data)
8✔
313
            })),
8✔
314
            get_bulk_initial_names: Some(Box::new(move || get_names(use_test_genesis_data))),
8✔
315
        };
316

317
        let chain_state_result = StacksChainState::open_and_exec(
8✔
318
            config.is_mainnet(),
8✔
319
            config.burnchain.chain_id,
8✔
320
            &config.get_chainstate_path_str(),
8✔
321
            Some(&mut boot_data),
8✔
322
            Some(config.node.get_marf_opts()),
8✔
323
        );
324

325
        let (chain_state, receipts) = match chain_state_result {
8✔
326
            Ok(res) => res,
8✔
327
            Err(err) => panic!(
×
328
                "Error while opening chain state at path {}: {err:?}",
329
                config.get_chainstate_path_str()
×
330
            ),
331
        };
332

333
        let estimator = Box::new(UnitEstimator);
8✔
334
        let metric = Box::new(UnitMetric);
8✔
335

336
        // avoid race to create condition on mempool db
337
        let _mem_pool = MemPoolDB::open(
8✔
338
            config.is_mainnet(),
8✔
339
            config.burnchain.chain_id,
8✔
340
            &chain_state.root_path,
8✔
341
            estimator,
8✔
342
            metric,
8✔
343
        )
344
        .expect("FATAL: failed to initiate mempool");
8✔
345

346
        let mut event_dispatcher = EventDispatcher::new(config.get_working_dir());
8✔
347

348
        for observer in &config.events_observers {
8✔
349
            event_dispatcher.register_observer(observer);
×
350
        }
×
351
        event_dispatcher.process_pending_payloads();
8✔
352

353
        let burnchain_config = config.get_burnchain();
8✔
354

355
        // instantiate DBs
356
        let _burnchain_db = BurnchainDB::connect(
8✔
357
            &burnchain_config.get_burnchaindb_path(),
8✔
358
            &burnchain_config,
8✔
359
            true,
360
        )
361
        .expect("FATAL: failed to connect to burnchain DB");
8✔
362

363
        run_loop::announce_boot_receipts(
8✔
364
            &mut event_dispatcher,
8✔
365
            &chain_state,
8✔
366
            &burnchain_config.pox_constants,
8✔
367
            &receipts,
8✔
368
        );
369

370
        Self {
8✔
371
            active_registered_key: None,
8✔
372
            bootstraping_chain: false,
8✔
373
            chain_state,
8✔
374
            chain_tip: None,
8✔
375
            keychain,
8✔
376
            last_sortitioned_block: None,
8✔
377
            config,
8✔
378
            burnchain_tip: None,
8✔
379
            nonce: 0,
8✔
380
            event_dispatcher,
8✔
381
            leader_key_registers: HashSet::new(),
8✔
382
            block_commits: HashSet::new(),
8✔
383
        }
8✔
384
    }
8✔
385

386
    fn make_atlas_config() -> AtlasConfig {
78✔
387
        AtlasConfig::new(false)
78✔
388
    }
78✔
389

390
    pub fn make_atlas_db(&self) -> AtlasDB {
43✔
391
        AtlasDB::connect(
43✔
392
            Self::make_atlas_config(),
43✔
393
            &self.config.get_atlas_db_file_path(),
43✔
394
            true,
395
        )
396
        .unwrap()
43✔
397
    }
43✔
398

399
    // This function is used for helium and mocknet.
400
    pub fn spawn_peer_server(&mut self) {
8✔
401
        // we can call _open_ here rather than _connect_, since connect is first called in
402
        //   make_genesis_block
403
        let burnchain = self.config.get_burnchain();
8✔
404
        let sortdb = SortitionDB::open(
8✔
405
            &self.config.get_burn_db_file_path(),
8✔
406
            true,
407
            burnchain.pox_constants.clone(),
8✔
408
            Some(self.config.node.get_marf_opts()),
8✔
409
        )
410
        .expect("Error while instantiating burnchain db");
8✔
411

412
        let epochs_vec = SortitionDB::get_stacks_epochs(sortdb.conn())
8✔
413
            .expect("Error while loading stacks epochs");
8✔
414
        let epochs = EpochList::new(&epochs_vec);
8✔
415

416
        Config::assert_valid_epoch_settings(&burnchain, &epochs);
8✔
417

418
        let view = {
8✔
419
            let sortition_tip = SortitionDB::get_canonical_burn_chain_tip(sortdb.conn())
8✔
420
                .expect("Failed to get sortition tip");
8✔
421
            SortitionDB::get_burnchain_view(&sortdb.index_conn(), &burnchain, &sortition_tip)
8✔
422
                .unwrap()
8✔
423
        };
424

425
        // create a new peerdb
426
        let data_url = UrlString::try_from(self.config.node.data_url.to_string()).unwrap();
8✔
427

428
        let initial_neighbors = self.config.node.bootstrap_node.clone();
8✔
429

430
        println!("BOOTSTRAP WITH {initial_neighbors:?}");
8✔
431

432
        let rpc_sock: SocketAddr =
8✔
433
            self.config.node.rpc_bind.parse().unwrap_or_else(|_| {
8✔
434
                panic!("Failed to parse socket: {}", &self.config.node.rpc_bind)
×
435
            });
436
        let p2p_sock: SocketAddr =
8✔
437
            self.config.node.p2p_bind.parse().unwrap_or_else(|_| {
8✔
438
                panic!("Failed to parse socket: {}", &self.config.node.p2p_bind)
×
439
            });
440
        let p2p_addr: SocketAddr = self.config.node.p2p_address.parse().unwrap_or_else(|_| {
8✔
441
            panic!("Failed to parse socket: {}", &self.config.node.p2p_address)
×
442
        });
443
        let node_privkey = {
8✔
444
            let mut re_hashed_seed = self.config.node.local_peer_seed.clone();
8✔
445
            let my_private_key = loop {
8✔
446
                match Secp256k1PrivateKey::from_slice(&re_hashed_seed[..]) {
8✔
447
                    Ok(sk) => break sk,
8✔
448
                    Err(_) => {
449
                        re_hashed_seed = Sha256Sum::from_data(&re_hashed_seed[..])
×
450
                            .as_bytes()
×
451
                            .to_vec()
×
452
                    }
453
                }
454
            };
455
            my_private_key
8✔
456
        };
457

458
        let mut peerdb = PeerDB::connect(
8✔
459
            &self.config.get_peer_db_file_path(),
8✔
460
            true,
461
            self.config.burnchain.chain_id,
8✔
462
            burnchain.network_id,
8✔
463
            Some(node_privkey),
8✔
464
            self.config.connection_options.private_key_lifetime,
8✔
465
            PeerAddress::from_socketaddr(&p2p_addr),
8✔
466
            p2p_sock.port(),
8✔
467
            data_url,
8✔
468
            &[],
8✔
469
            Some(&initial_neighbors),
8✔
470
            &[],
8✔
471
        )
472
        .unwrap();
8✔
473

474
        println!("DENY NEIGHBORS {:?}", &self.config.node.deny_nodes);
8✔
475
        {
476
            let tx = peerdb.tx_begin().unwrap();
8✔
477
            for denied in self.config.node.deny_nodes.iter() {
8✔
478
                PeerDB::set_deny_peer(
×
479
                    &tx,
×
480
                    denied.addr.network_id,
×
481
                    &denied.addr.addrbytes,
×
482
                    denied.addr.port,
×
483
                    get_epoch_time_secs() + 24 * 365 * 3600,
×
484
                )
×
485
                .unwrap();
×
486
            }
×
487
            tx.commit().unwrap();
8✔
488
        }
489
        let atlasdb = self.make_atlas_db();
8✔
490

491
        let stackerdbs =
8✔
492
            StackerDBs::connect(&self.config.get_stacker_db_file_path(), true).unwrap();
8✔
493

494
        let local_peer = match PeerDB::get_local_peer(peerdb.conn()) {
8✔
495
            Ok(local_peer) => local_peer,
8✔
496
            _ => panic!("Unable to retrieve local peer"),
×
497
        };
498

499
        let event_dispatcher = self.event_dispatcher.clone();
8✔
500
        let exit_at_block_height = self.config.burnchain.process_exit_at_block_height;
8✔
501
        let burnchain_db = burnchain
8✔
502
            .open_burnchain_db(false)
8✔
503
            .expect("Failed to open burnchain DB");
8✔
504

505
        let p2p_net = PeerNetwork::new(
8✔
506
            peerdb,
8✔
507
            atlasdb,
8✔
508
            stackerdbs,
8✔
509
            burnchain_db,
8✔
510
            local_peer,
8✔
511
            self.config.burnchain.peer_version,
8✔
512
            burnchain.clone(),
8✔
513
            view,
8✔
514
            self.config.connection_options.clone(),
8✔
515
            HashMap::new(),
8✔
516
            epochs,
8✔
517
        );
518
        let _join_handle = spawn_peer(
8✔
519
            self.config.is_mainnet(),
8✔
520
            self.config.burnchain.chain_id,
8✔
521
            p2p_net,
8✔
522
            &p2p_sock,
8✔
523
            &rpc_sock,
8✔
524
            self.config.get_burn_db_file_path(),
8✔
525
            self.config.get_chainstate_path_str(),
8✔
526
            burnchain.pox_constants,
8✔
527
            event_dispatcher,
8✔
528
            exit_at_block_height,
8✔
529
            Sha256Sum::from_hex(stx_genesis::GENESIS_CHAINSTATE_HASH).unwrap(),
8✔
530
            1000,
531
            self.config.clone(),
8✔
532
        );
533

534
        info!("Start HTTP server on: {}", &self.config.node.rpc_bind);
8✔
535
        info!("Start P2P server on: {}", &self.config.node.p2p_bind);
8✔
536
    }
8✔
537

538
    pub fn setup(&mut self, burnchain_controller: &mut Box<dyn BurnchainController>) {
8✔
539
        // Register a new key
540
        let burnchain_tip = burnchain_controller.get_chain_tip();
8✔
541
        let (vrf_pk, _) = self
8✔
542
            .keychain
8✔
543
            .make_vrf_keypair(burnchain_tip.block_snapshot.block_height);
8✔
544
        let consensus_hash = burnchain_tip.block_snapshot.consensus_hash;
8✔
545

546
        let burnchain = self.config.get_burnchain();
8✔
547

548
        let sortdb = SortitionDB::open(
8✔
549
            &self.config.get_burn_db_file_path(),
8✔
550
            true,
551
            burnchain.pox_constants.clone(),
8✔
552
            Some(self.config.node.get_marf_opts()),
8✔
553
        )
554
        .expect("Error while opening sortition db");
8✔
555

556
        let epochs = SortitionDB::get_stacks_epochs(sortdb.conn())
8✔
557
            .expect("FATAL: failed to read sortition DB");
8✔
558

559
        Config::assert_valid_epoch_settings(&burnchain, &epochs);
8✔
560

561
        let cur_epoch =
8✔
562
            SortitionDB::get_stacks_epoch(sortdb.conn(), burnchain_tip.block_snapshot.block_height)
8✔
563
                .expect("FATAL: failed to read sortition DB")
8✔
564
                .expect("FATAL: no epoch defined");
8✔
565

566
        let key_reg_op = self.generate_leader_key_register_op(vrf_pk, consensus_hash);
8✔
567
        let mut op_signer = self.keychain.generate_op_signer();
8✔
568
        let key_txid = burnchain_controller
8✔
569
            .submit_operation(cur_epoch.epoch_id, key_reg_op, &mut op_signer)
8✔
570
            .expect("FATAL: failed to submit leader key register operation");
8✔
571

572
        self.leader_key_registers.insert(key_txid);
8✔
573
    }
8✔
574

575
    /// Process an state coming from the burnchain, by extracting the validated KeyRegisterOp
576
    /// and inspecting if a sortition was won.
577
    pub fn process_burnchain_state(
51✔
578
        &mut self,
51✔
579
        burnchain_tip: &BurnchainTip,
51✔
580
    ) -> (Option<BurnchainTip>, bool) {
51✔
581
        let mut new_key = None;
51✔
582
        let mut last_sortitioned_block = None;
51✔
583
        let mut won_sortition = false;
51✔
584
        let ops = &burnchain_tip.state_transition.accepted_ops;
51✔
585

586
        for op in ops.iter() {
51✔
587
            match op {
43✔
588
                BlockstackOperationType::LeaderKeyRegister(ref op) => {
8✔
589
                    if self.leader_key_registers.contains(&op.txid) {
8✔
590
                        // Registered key has been mined
8✔
591
                        new_key = Some(RegisteredKey {
8✔
592
                            vrf_public_key: op.public_key.clone(),
8✔
593
                            block_height: op.block_height,
8✔
594
                            op_vtxindex: op.vtxindex,
8✔
595
                            target_block_height: op.block_height - 1,
8✔
596
                            memo: op.memo.clone(),
8✔
597
                        });
8✔
598
                    }
8✔
599
                }
600
                BlockstackOperationType::LeaderBlockCommit(ref op) => {
35✔
601
                    if op.txid == burnchain_tip.block_snapshot.winning_block_txid {
35✔
602
                        last_sortitioned_block = Some(burnchain_tip.clone());
35✔
603
                        if self.block_commits.contains(&op.txid) {
35✔
604
                            won_sortition = true;
35✔
605
                        }
35✔
606
                    }
×
607
                }
608
                _ => {
×
609
                    // no-op, ops are not supported / produced at this point.
×
610
                }
×
611
            }
612
        }
613

614
        // Update the active key so we use the latest registered key.
615
        if new_key.is_some() {
51✔
616
            self.active_registered_key = new_key;
8✔
617
        }
43✔
618

619
        // Update last_sortitioned_block so we keep a reference to the latest
620
        // block including a sortition.
621
        if last_sortitioned_block.is_some() {
51✔
622
            self.last_sortitioned_block = last_sortitioned_block;
35✔
623
        }
35✔
624

625
        // Keep a pointer of the burnchain's chain tip.
626
        self.burnchain_tip = Some(burnchain_tip.clone());
51✔
627

628
        (self.last_sortitioned_block.clone(), won_sortition)
51✔
629
    }
51✔
630

631
    /// Prepares the node to run a tenure consisting in bootstraping the chain.
632
    ///
633
    /// Will internally call initiate_new_tenure().
634
    pub fn initiate_genesis_tenure(&mut self, burnchain_tip: &BurnchainTip) -> Option<Tenure> {
8✔
635
        // Set the `bootstraping_chain` flag, that will be unset once the
636
        // bootstraping tenure ran successfully (process_tenure).
637
        self.bootstraping_chain = true;
8✔
638

639
        self.last_sortitioned_block = Some(burnchain_tip.clone());
8✔
640

641
        self.initiate_new_tenure()
8✔
642
    }
8✔
643

644
    /// Constructs and returns an instance of Tenure, that can be run
645
    /// on an isolated thread and discarded or canceled without corrupting the
646
    /// chain state of the node.
647
    pub fn initiate_new_tenure(&mut self) -> Option<Tenure> {
43✔
648
        // Get the latest registered key
649
        let registered_key = match &self.active_registered_key {
43✔
650
            None => {
651
                // We're continuously registering new keys, as such, this branch
652
                // should be unreachable.
653
                unreachable!()
×
654
            }
655
            Some(ref key) => key,
43✔
656
        };
657

658
        let burnchain = self.config.get_burnchain();
43✔
659
        let sortdb = SortitionDB::open(
43✔
660
            &self.config.get_burn_db_file_path(),
43✔
661
            true,
662
            burnchain.pox_constants,
43✔
663
            Some(self.config.node.get_marf_opts()),
43✔
664
        )
665
        .expect("Error while opening sortition db");
43✔
666
        let tip = SortitionDB::get_canonical_burn_chain_tip(sortdb.conn())
43✔
667
            .expect("FATAL: failed to query canonical burn chain tip");
43✔
668

669
        // Generates a proof out of the sortition hash provided in the params.
670
        let Some(vrf_proof) = self.keychain.generate_proof(
43✔
671
            registered_key.target_block_height,
43✔
672
            tip.sortition_hash.as_bytes(),
43✔
673
        ) else {
43✔
674
            warn!("Failed to generate VRF proof, will be unable to initiate new tenure");
×
675
            return None;
×
676
        };
677

678
        // Generates a new secret key for signing the trail of microblocks
679
        // of the upcoming tenure.
680
        let microblock_secret_key = self.keychain.get_microblock_key(tip.block_height);
43✔
681

682
        // Get the stack's chain tip
683
        let chain_tip = match self.bootstraping_chain {
43✔
684
            true => ChainTip::genesis(&BurnchainHeaderHash::zero(), 0, 0),
8✔
685
            false => match &self.chain_tip {
35✔
686
                Some(chain_tip) => chain_tip.clone(),
35✔
687
                None => unreachable!(),
×
688
            },
689
        };
690

691
        let estimator = self
43✔
692
            .config
43✔
693
            .make_cost_estimator()
43✔
694
            .unwrap_or_else(|| Box::new(UnitEstimator));
43✔
695
        let metric = self
43✔
696
            .config
43✔
697
            .make_cost_metric()
43✔
698
            .unwrap_or_else(|| Box::new(UnitMetric));
43✔
699

700
        let mem_pool = MemPoolDB::open(
43✔
701
            self.config.is_mainnet(),
43✔
702
            self.config.burnchain.chain_id,
43✔
703
            &self.chain_state.root_path,
43✔
704
            estimator,
43✔
705
            metric,
43✔
706
        )
707
        .expect("FATAL: failed to open mempool");
43✔
708

709
        // Construct the coinbase transaction - 1st txn that should be handled and included in
710
        // the upcoming tenure.
711
        let coinbase_tx = self.generate_coinbase_tx(self.config.is_mainnet());
43✔
712

713
        let burn_fee_cap = self.config.burnchain.burn_fee_cap;
43✔
714

715
        let block_to_build_upon = match &self.last_sortitioned_block {
43✔
716
            None => unreachable!(),
×
717
            Some(block) => block.clone(),
43✔
718
        };
719

720
        // Construct the upcoming tenure
721
        let tenure = Tenure::new(
43✔
722
            chain_tip,
43✔
723
            coinbase_tx,
43✔
724
            self.config.clone(),
43✔
725
            mem_pool,
43✔
726
            microblock_secret_key,
43✔
727
            block_to_build_upon,
43✔
728
            vrf_proof,
43✔
729
            burn_fee_cap,
43✔
730
        );
731

732
        Some(tenure)
43✔
733
    }
43✔
734

735
    pub fn commit_artifacts(
35✔
736
        &mut self,
35✔
737
        anchored_block_from_ongoing_tenure: &StacksBlock,
35✔
738
        burnchain_tip: &BurnchainTip,
35✔
739
        burnchain_controller: &mut Box<dyn BurnchainController>,
35✔
740
        burn_fee: u64,
35✔
741
    ) {
35✔
742
        if self.active_registered_key.is_some() {
35✔
743
            let registered_key = self.active_registered_key.clone().unwrap();
35✔
744

745
            let Some(vrf_proof) = self.keychain.generate_proof(
35✔
746
                registered_key.target_block_height,
35✔
747
                burnchain_tip.block_snapshot.sortition_hash.as_bytes(),
35✔
748
            ) else {
35✔
749
                warn!("Failed to generate VRF proof, will be unable to mine commits");
×
750
                return;
×
751
            };
752

753
            let op = self.generate_block_commit_op(
35✔
754
                anchored_block_from_ongoing_tenure.header.block_hash(),
35✔
755
                burn_fee,
35✔
756
                &registered_key,
35✔
757
                burnchain_tip,
35✔
758
                VRFSeed::from_proof(&vrf_proof),
35✔
759
            );
760

761
            let burnchain = self.config.get_burnchain();
35✔
762
            let sortdb = SortitionDB::open(
35✔
763
                &self.config.get_burn_db_file_path(),
35✔
764
                true,
765
                burnchain.pox_constants,
35✔
766
                Some(self.config.node.get_marf_opts()),
35✔
767
            )
768
            .expect("Error while opening sortition db");
35✔
769

770
            let cur_epoch = SortitionDB::get_stacks_epoch(
35✔
771
                sortdb.conn(),
35✔
772
                burnchain_tip.block_snapshot.block_height,
35✔
773
            )
774
            .expect("FATAL: failed to read sortition DB")
35✔
775
            .expect("FATAL: no epoch defined");
35✔
776

777
            let mut op_signer = self.keychain.generate_op_signer();
35✔
778
            let txid = burnchain_controller
35✔
779
                .submit_operation(cur_epoch.epoch_id, op, &mut op_signer)
35✔
780
                .expect("FATAL: failed to submit block-commit");
35✔
781

782
            self.block_commits.insert(txid);
35✔
783
        } else {
784
            warn!("No leader key active!");
×
785
        }
786
    }
35✔
787

788
    /// Process artifacts from the tenure.
789
    /// At this point, we're modifying the chainstate, and merging the artifacts from the previous tenure.
790
    pub fn process_tenure(
35✔
791
        &mut self,
35✔
792
        anchored_block: &StacksBlock,
35✔
793
        consensus_hash: &ConsensusHash,
35✔
794
        microblocks: Vec<StacksMicroblock>,
35✔
795
        db: &mut SortitionDB,
35✔
796
        atlas_db: &mut AtlasDB,
35✔
797
    ) -> ChainTip {
35✔
798
        let _parent_consensus_hash = {
35✔
799
            // look up parent consensus hash
800
            let ic = db.index_conn();
35✔
801
            let parent_consensus_hash = StacksChainState::get_parent_consensus_hash(
35✔
802
                &ic,
35✔
803
                &anchored_block.header.parent_block,
35✔
804
                consensus_hash,
35✔
805
            )
806
            .unwrap_or_else(|_| {
35✔
807
                panic!(
×
808
                    "BUG: could not query chainstate to find parent consensus hash of {consensus_hash}/{}",
809
                    &anchored_block.block_hash()
×
810
                )
811
            })
812
            .unwrap_or_else(|| {
35✔
813
                panic!(
×
814
                    "BUG: no such parent of block {consensus_hash}/{}",
815
                    &anchored_block.block_hash()
×
816
                )
817
            });
818

819
            // Preprocess the anchored block
820
            self.chain_state
35✔
821
                .preprocess_anchored_block(
35✔
822
                    &ic,
35✔
823
                    consensus_hash,
35✔
824
                    anchored_block,
35✔
825
                    &parent_consensus_hash,
35✔
826
                    0,
827
                )
828
                .unwrap();
35✔
829

830
            // Preprocess the microblocks
831
            for microblock in microblocks.iter() {
35✔
832
                let res = self
×
833
                    .chain_state
×
834
                    .preprocess_streamed_microblock(
×
835
                        consensus_hash,
×
836
                        &anchored_block.block_hash(),
×
837
                        microblock,
×
838
                    )
839
                    .unwrap();
×
840
                if !res {
×
841
                    warn!(
×
842
                        "Unhandled error while pre-processing microblock {}",
843
                        microblock.header.block_hash()
×
844
                    );
845
                }
×
846
            }
847

848
            parent_consensus_hash
35✔
849
        };
850

851
        let atlas_config = Self::make_atlas_config();
35✔
852
        let mut processed_blocks = vec![];
35✔
853
        loop {
854
            let mut process_blocks_at_tip = {
70✔
855
                let tx = db.tx_begin_at_tip();
70✔
856
                self.chain_state
70✔
857
                    .process_blocks(tx, 1, Some(&self.event_dispatcher))
70✔
858
            };
859
            match process_blocks_at_tip {
70✔
860
                Err(e) => panic!("Error while processing block - {e:?}"),
×
861
                Ok(ref mut blocks) => {
70✔
862
                    if blocks.is_empty() {
70✔
863
                        break;
35✔
864
                    } else {
865
                        for block in blocks.iter() {
35✔
866
                            if let (Some(epoch_receipt), _) = block {
35✔
867
                                let attachments_instances =
35✔
868
                                    self.get_attachment_instances(epoch_receipt, &atlas_config);
35✔
869
                                if !attachments_instances.is_empty() {
35✔
870
                                    for new_attachment in attachments_instances.into_iter() {
×
871
                                        if let Err(e) =
×
872
                                            atlas_db.queue_attachment_instance(&new_attachment)
×
873
                                        {
874
                                            warn!(
×
875
                                                "Atlas: Error writing attachment instance to DB";
876
                                                "err" => ?e,
877
                                                "index_block_hash" => %new_attachment.index_block_hash,
878
                                                "contract_id" => %new_attachment.contract_id,
879
                                                "attachment_index" => %new_attachment.attachment_index,
880
                                            );
881
                                        }
×
882
                                    }
883
                                }
35✔
884
                            }
×
885
                        }
886

887
                        processed_blocks.append(blocks);
35✔
888
                    }
889
                }
890
            }
891
        }
892

893
        // todo(ludo): yikes but good enough in the context of helium:
894
        // we only expect 1 block.
895
        let processed_block = processed_blocks[0].clone().0.unwrap();
35✔
896

897
        let mut cost_estimator = self.config.make_cost_estimator();
35✔
898
        let mut fee_estimator = self.config.make_fee_estimator();
35✔
899

900
        let stacks_epoch =
35✔
901
            SortitionDB::get_stacks_epoch_by_epoch_id(db.conn(), &processed_block.evaluated_epoch)
35✔
902
                .expect("FATAL: could not query sortition DB for epochs")
35✔
903
                .expect("Could not find a stacks epoch.");
35✔
904
        if let Some(estimator) = cost_estimator.as_mut() {
35✔
905
            estimator.notify_block(
35✔
906
                &processed_block.tx_receipts,
35✔
907
                &stacks_epoch.block_limit,
35✔
908
                &stacks_epoch.epoch_id,
35✔
909
            );
35✔
910
        }
35✔
911

912
        if let Some(estimator) = fee_estimator.as_mut() {
35✔
913
            if let Err(e) = estimator.notify_block(&processed_block, &stacks_epoch.block_limit) {
35✔
914
                warn!("FeeEstimator failed to process block receipt";
×
915
                      "stacks_block_hash" => %processed_block.header.anchored_header.block_hash(),
×
916
                      "stacks_height" => %processed_block.header.stacks_block_height,
917
                      "error" => %e);
918
            }
35✔
919
        }
×
920

921
        // Handle events
922
        let receipts = processed_block.tx_receipts;
35✔
923
        let metadata = processed_block.header;
35✔
924
        let block: StacksBlock = {
35✔
925
            let block_path = StacksChainState::get_block_path(
35✔
926
                &self.chain_state.blocks_path,
35✔
927
                &metadata.consensus_hash,
35✔
928
                &metadata.anchored_header.block_hash(),
35✔
929
            )
930
            .unwrap();
35✔
931
            StacksChainState::consensus_load(&block_path).unwrap()
35✔
932
        };
933

934
        let chain_tip = ChainTip {
35✔
935
            metadata,
35✔
936
            block,
35✔
937
            receipts,
35✔
938
        };
35✔
939
        self.chain_tip = Some(chain_tip.clone());
35✔
940

941
        // Unset the `bootstraping_chain` flag.
942
        if self.bootstraping_chain {
35✔
943
            self.bootstraping_chain = false;
8✔
944
        }
27✔
945

946
        chain_tip
35✔
947
    }
35✔
948

949
    pub fn get_attachment_instances(
35✔
950
        &self,
35✔
951
        epoch_receipt: &StacksEpochReceipt,
35✔
952
        atlas_config: &AtlasConfig,
35✔
953
    ) -> HashSet<AttachmentInstance> {
35✔
954
        let mut attachments_instances = HashSet::new();
35✔
955
        for receipt in epoch_receipt.tx_receipts.iter() {
119✔
956
            if let TransactionOrigin::Stacks(ref transaction) = receipt.transaction {
119✔
957
                if let TransactionPayload::ContractCall(ref contract_call) = transaction.payload {
119✔
958
                    let contract_id = contract_call.to_clarity_contract_id();
15✔
959
                    if atlas_config.contracts.contains(&contract_id) {
15✔
960
                        for event in receipt.events.iter() {
×
961
                            if let StacksTransactionEvent::SmartContractEvent(ref event_data) =
×
962
                                event
×
963
                            {
964
                                let res = AttachmentInstance::try_new_from_value(
×
965
                                    &event_data.value,
×
966
                                    &contract_id,
×
967
                                    epoch_receipt.header.index_block_hash(),
×
968
                                    epoch_receipt.header.stacks_block_height,
×
969
                                    receipt.transaction.txid(),
×
970
                                    self.chain_tip
×
971
                                        .as_ref()
×
972
                                        .map(|t| t.metadata.stacks_block_height),
×
973
                                );
974
                                if let Some(attachment_instance) = res {
×
975
                                    attachments_instances.insert(attachment_instance);
×
976
                                }
×
977
                            }
×
978
                        }
979
                    }
15✔
980
                }
104✔
981
            }
×
982
        }
983
        attachments_instances
35✔
984
    }
35✔
985

986
    /// Constructs and returns a LeaderKeyRegisterOp out of the provided params
987
    fn generate_leader_key_register_op(
8✔
988
        &mut self,
8✔
989
        vrf_public_key: VRFPublicKey,
8✔
990
        consensus_hash: ConsensusHash,
8✔
991
    ) -> BlockstackOperationType {
8✔
992
        let mut txid_bytes = [0u8; 32];
8✔
993
        let mut rng = rand::thread_rng();
8✔
994
        rng.fill_bytes(&mut txid_bytes);
8✔
995
        let txid = Txid(txid_bytes);
8✔
996

997
        BlockstackOperationType::LeaderKeyRegister(LeaderKeyRegisterOp {
8✔
998
            public_key: vrf_public_key,
8✔
999
            memo: vec![],
8✔
1000
            consensus_hash,
8✔
1001
            vtxindex: 1,
8✔
1002
            txid,
8✔
1003
            block_height: 0,
8✔
1004
            burn_header_hash: BurnchainHeaderHash::zero(),
8✔
1005
        })
8✔
1006
    }
8✔
1007

1008
    /// Constructs and returns a LeaderBlockCommitOp out of the provided params
1009
    fn generate_block_commit_op(
35✔
1010
        &mut self,
35✔
1011
        block_header_hash: BlockHeaderHash,
35✔
1012
        burn_fee: u64,
35✔
1013
        key: &RegisteredKey,
35✔
1014
        burnchain_tip: &BurnchainTip,
35✔
1015
        vrf_seed: VRFSeed,
35✔
1016
    ) -> BlockstackOperationType {
35✔
1017
        let winning_tx_vtindex = burnchain_tip.get_winning_tx_index().unwrap_or(0);
35✔
1018

1019
        let (parent_block_ptr, parent_vtxindex) = match self.bootstraping_chain {
35✔
1020
            true => (0, 0), // parent_block_ptr and parent_vtxindex should both be 0 on block #1
8✔
1021
            false => (
27✔
1022
                burnchain_tip.block_snapshot.block_height as u32,
27✔
1023
                winning_tx_vtindex as u16,
27✔
1024
            ),
27✔
1025
        };
1026

1027
        let burnchain = self.config.get_burnchain();
35✔
1028
        let commit_outs = if burnchain_tip.block_snapshot.block_height + 1
35✔
1029
            < burnchain.pox_constants.sunset_end
35✔
1030
            && !burnchain.is_in_prepare_phase(burnchain_tip.block_snapshot.block_height + 1)
35✔
1031
        {
1032
            RewardSetInfo::into_commit_outs(None, self.config.is_mainnet())
14✔
1033
        } else {
1034
            vec![PoxAddress::standard_burn_address(self.config.is_mainnet())]
21✔
1035
        };
1036

1037
        let burn_parent_modulus =
35✔
1038
            (burnchain_tip.block_snapshot.block_height % BURN_BLOCK_MINED_AT_MODULUS) as u8;
35✔
1039

1040
        let mut txid_bytes = [0u8; 32];
35✔
1041
        let mut rng = rand::thread_rng();
35✔
1042
        rng.fill_bytes(&mut txid_bytes);
35✔
1043
        let txid = Txid(txid_bytes);
35✔
1044

1045
        BlockstackOperationType::LeaderBlockCommit(LeaderBlockCommitOp {
35✔
1046
            treatment: vec![],
35✔
1047
            sunset_burn: 0,
35✔
1048
            block_header_hash,
35✔
1049
            burn_fee,
35✔
1050
            input: (Txid([0; 32]), 0),
35✔
1051
            apparent_sender: self.keychain.get_burnchain_signer(),
35✔
1052
            key_block_ptr: key.block_height as u32,
35✔
1053
            key_vtxindex: key.op_vtxindex as u16,
35✔
1054
            memo: vec![STACKS_EPOCH_2_1_MARKER],
35✔
1055
            new_seed: vrf_seed,
35✔
1056
            parent_block_ptr,
35✔
1057
            parent_vtxindex,
35✔
1058
            vtxindex: 2,
35✔
1059
            txid,
35✔
1060
            commit_outs,
35✔
1061
            block_height: 0,
35✔
1062
            burn_header_hash: BurnchainHeaderHash::zero(),
35✔
1063
            burn_parent_modulus,
35✔
1064
        })
35✔
1065
    }
35✔
1066

1067
    // Constructs a coinbase transaction
1068
    fn generate_coinbase_tx(&mut self, is_mainnet: bool) -> StacksTransaction {
43✔
1069
        let mut tx_auth = self.keychain.get_transaction_auth().unwrap();
43✔
1070
        tx_auth.set_origin_nonce(self.nonce);
43✔
1071

1072
        let version = if is_mainnet {
43✔
1073
            TransactionVersion::Mainnet
×
1074
        } else {
1075
            TransactionVersion::Testnet
43✔
1076
        };
1077
        let mut tx = StacksTransaction::new(
43✔
1078
            version,
43✔
1079
            tx_auth,
43✔
1080
            TransactionPayload::Coinbase(CoinbasePayload([0u8; 32]), None, None),
43✔
1081
        );
1082
        tx.chain_id = self.config.burnchain.chain_id;
43✔
1083
        tx.anchor_mode = TransactionAnchorMode::OnChainOnly;
43✔
1084
        let mut tx_signer = StacksTransactionSigner::new(&tx);
43✔
1085
        self.keychain.sign_as_origin(&mut tx_signer);
43✔
1086

1087
        // Increment nonce
1088
        self.nonce += 1;
43✔
1089

1090
        tx_signer.get_tx().unwrap()
43✔
1091
    }
43✔
1092
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc