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

stacks-network / stacks-core / 25904007932-1

15 May 2026 06:31AM UTC coverage: 47.459% (-38.5%) from 85.959%
25904007932-1

Pull #7210

github

869a54
web-flow
Merge 27877974d into 1c7b8e6ac
Pull Request #7210: [wip] epoch 4 release branch

36 of 53 new or added lines in 1 file covered. (67.92%)

88645 existing lines in 346 files now uncovered.

104136 of 219422 relevant lines covered (47.46%)

12897381.15 hits per line

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

87.36
/stacks-node/src/run_loop/neon.rs
1
#[cfg(test)]
2
use std::sync::atomic::AtomicU64;
3
use std::sync::atomic::{AtomicBool, Ordering};
4
use std::sync::mpsc::sync_channel;
5
use std::sync::{Arc, Mutex};
6
use std::thread;
7
use std::thread::JoinHandle;
8

9
use libc;
10
use stacks::burnchains::bitcoin::address::{BitcoinAddress, LegacyBitcoinAddressType};
11
use stacks::burnchains::{Burnchain, Error as burnchain_error};
12
use stacks::chainstate::burn::db::sortdb::SortitionDB;
13
use stacks::chainstate::burn::{BlockSnapshot, ConsensusHash};
14
use stacks::chainstate::coordinator::comm::{CoordinatorChannels, CoordinatorReceivers};
15
use stacks::chainstate::coordinator::{
16
    migrate_chainstate_dbs, ChainsCoordinator, ChainsCoordinatorConfig, CoordinatorCommunication,
17
    Error as coord_error,
18
};
19
use stacks::chainstate::stacks::db::{ChainStateBootData, StacksChainState};
20
use stacks::chainstate::stacks::miner::{signal_mining_blocked, signal_mining_ready, MinerStatus};
21
use stacks::core::StacksEpochId;
22
use stacks::net::atlas::{AtlasConfig, AtlasDB, Attachment};
23
#[cfg(test)]
24
use stacks::util::tests::TestFlag;
25
use stacks::util_lib::db::Error as db_error;
26
use stacks_common::deps_common::ctrlc as termination;
27
use stacks_common::deps_common::ctrlc::SignalId;
28
use stacks_common::types::PublicKey;
29
use stacks_common::util::hash::Hash160;
30
use stx_genesis::GenesisData;
31

32
use super::RunLoopCallbacks;
33
use crate::burnchains::{make_bitcoin_indexer, Error};
34
use crate::globals::NeonGlobals as Globals;
35
use crate::monitoring::{start_serving_monitoring_metrics, MonitoringError};
36
use crate::neon_node::{
37
    LeaderKeyRegistrationState, StacksNode, BLOCK_PROCESSOR_STACK_SIZE, RELAYER_MAX_BUFFER,
38
};
39
use crate::node::{
40
    get_account_balances, get_account_lockups, get_names, get_namespaces,
41
    use_test_genesis_chainstate,
42
};
43
use crate::run_loop::boot_nakamoto::Neon2NakaData;
44
use crate::syncctl::{PoxSyncWatchdog, PoxSyncWatchdogComms};
45
use crate::{
46
    run_loop, BitcoinRegtestController, BurnchainController, Config, EventDispatcher, Keychain,
47
};
48

49
pub const STDERR: i32 = 2;
50

51
#[cfg(test)]
52
#[derive(Clone, Default)]
53
pub struct RunLoopField<T>(pub Arc<Mutex<T>>);
54

55
#[cfg(not(test))]
56
#[derive(Clone, Default)]
57
pub struct RunLoopField<T>(pub std::marker::PhantomData<T>);
58

59
#[cfg(test)]
60
#[derive(Clone)]
61
pub struct RunLoopCounter(pub Arc<AtomicU64>);
62

63
#[cfg(not(test))]
64
#[derive(Clone)]
65
pub struct RunLoopCounter();
66

67
impl Default for RunLoopCounter {
68
    #[cfg(test)]
69
    fn default() -> Self {
6,006✔
70
        RunLoopCounter(Arc::new(AtomicU64::new(0)))
6,006✔
71
    }
6,006✔
72
    #[cfg(not(test))]
73
    fn default() -> Self {
74
        Self()
75
    }
76
}
77

78
impl<T: Clone> RunLoopField<Option<T>> {
79
    #[cfg(test)]
80
    pub fn get(&self) -> T {
89✔
81
        self.0.lock().unwrap().clone().unwrap()
89✔
82
    }
89✔
83
}
84

85
impl RunLoopCounter {
86
    #[cfg(test)]
87
    pub fn get(&self) -> u64 {
3,289✔
88
        self.0.load(Ordering::SeqCst)
3,289✔
89
    }
3,289✔
90

91
    #[cfg(test)]
92
    pub fn load(&self, ordering: Ordering) -> u64 {
64,010✔
93
        self.0.load(ordering)
64,010✔
94
    }
64,010✔
95
}
96

97
#[cfg(test)]
98
impl std::ops::Deref for RunLoopCounter {
99
    type Target = Arc<AtomicU64>;
100

101
    fn deref(&self) -> &Self::Target {
1,981✔
102
        &self.0
1,981✔
103
    }
1,981✔
104
}
105

106
#[derive(Clone, Default)]
107
pub struct Counters {
108
    pub blocks_processed: RunLoopCounter,
109
    pub microblocks_processed: RunLoopCounter,
110
    pub missed_tenures: RunLoopCounter,
111
    pub missed_microblock_tenures: RunLoopCounter,
112
    pub cancelled_commits: RunLoopCounter,
113

114
    pub sortitions_processed: RunLoopCounter,
115

116
    pub naka_submitted_vrfs: RunLoopCounter,
117
    /// the number of submitted commits
118
    pub neon_submitted_commits: RunLoopCounter,
119
    /// the burn block height when the last commit was submitted
120
    pub neon_submitted_commit_last_burn_height: RunLoopCounter,
121
    pub naka_submitted_commits: RunLoopCounter,
122
    /// the burn block height when the last commit was submitted
123
    pub naka_submitted_commit_last_burn_height: RunLoopCounter,
124
    pub naka_mined_blocks: RunLoopCounter,
125
    pub naka_rejected_blocks: RunLoopCounter,
126
    pub naka_proposed_blocks: RunLoopCounter,
127
    pub naka_mined_tenures: RunLoopCounter,
128
    pub naka_signer_pushed_blocks: RunLoopCounter,
129
    pub naka_miner_directives: RunLoopCounter,
130
    pub naka_submitted_commit_last_stacks_tip: RunLoopCounter,
131
    pub naka_submitted_commit_last_commit_amount: RunLoopCounter,
132
    pub naka_submitted_commit_last_parent_tenure_id: RunLoopField<Option<ConsensusHash>>,
133

134
    pub naka_miner_current_rejections: RunLoopCounter,
135
    pub naka_miner_current_rejections_timeout_secs: RunLoopCounter,
136

137
    #[cfg(test)]
138
    pub skip_commit_op: TestFlag<bool>,
139
}
140

141
impl Counters {
UNCOV
142
    pub fn new() -> Self {
×
UNCOV
143
        Self::default()
×
UNCOV
144
    }
×
145

146
    #[cfg(test)]
147
    fn inc(ctr: &RunLoopCounter) {
34,215✔
148
        ctr.0.fetch_add(1, Ordering::SeqCst);
34,215✔
149
    }
34,215✔
150

151
    #[cfg(not(test))]
152
    fn inc(_ctr: &RunLoopCounter) {}
153

154
    #[cfg(test)]
155
    fn set(ctr: &RunLoopCounter, value: u64) {
12,866✔
156
        ctr.0.store(value, Ordering::SeqCst);
12,866✔
157
    }
12,866✔
158

159
    #[cfg(not(test))]
160
    fn set(_ctr: &RunLoopCounter, _value: u64) {}
161

162
    #[cfg(test)]
163
    fn update<T: Clone>(ctr: &RunLoopField<Option<T>>, value: &T) {
1,925✔
164
        let mut mutex = ctr.0.lock().expect("FATAL: test counter mutext poisoned");
1,925✔
165
        let _ = mutex.replace(value.clone());
1,925✔
166
    }
1,925✔
167

168
    #[cfg(not(test))]
169
    fn update<T: Clone>(_ctr: &RunLoopField<Option<T>>, _value: &T) {}
170

171
    pub fn bump_blocks_processed(&self) {
12,031✔
172
        Counters::inc(&self.blocks_processed);
12,031✔
173
    }
12,031✔
174

175
    pub fn bump_sortitions_processed(&self) {
4,474✔
176
        Counters::inc(&self.sortitions_processed);
4,474✔
177
    }
4,474✔
178

UNCOV
179
    pub fn bump_microblocks_processed(&self) {
×
UNCOV
180
        Counters::inc(&self.microblocks_processed);
×
UNCOV
181
    }
×
182

183
    pub fn bump_missed_tenures(&self) {
1,186✔
184
        Counters::inc(&self.missed_tenures);
1,186✔
185
    }
1,186✔
186

UNCOV
187
    pub fn bump_missed_microblock_tenures(&self) {
×
UNCOV
188
        Counters::inc(&self.missed_microblock_tenures);
×
UNCOV
189
    }
×
190

UNCOV
191
    pub fn bump_cancelled_commits(&self) {
×
UNCOV
192
        Counters::inc(&self.cancelled_commits);
×
UNCOV
193
    }
×
194

195
    pub fn bump_neon_submitted_commits(&self, committed_burn_height: u64) {
6,728✔
196
        Counters::inc(&self.neon_submitted_commits);
6,728✔
197
        Counters::set(
6,728✔
198
            &self.neon_submitted_commit_last_burn_height,
6,728✔
199
            committed_burn_height,
6,728✔
200
        );
201
    }
6,728✔
202

203
    pub fn bump_naka_submitted_vrfs(&self) {
38✔
204
        Counters::inc(&self.naka_submitted_vrfs);
38✔
205
    }
38✔
206

207
    pub fn bump_naka_submitted_commits(
1,925✔
208
        &self,
1,925✔
209
        committed_burn_height: u64,
1,925✔
210
        committed_stacks_height: u64,
1,925✔
211
        committed_sats_amount: u64,
1,925✔
212
        committed_parent_tenure_id: &ConsensusHash,
1,925✔
213
    ) {
1,925✔
214
        Counters::inc(&self.naka_submitted_commits);
1,925✔
215
        Counters::set(
1,925✔
216
            &self.naka_submitted_commit_last_burn_height,
1,925✔
217
            committed_burn_height,
1,925✔
218
        );
219
        Counters::set(
1,925✔
220
            &self.naka_submitted_commit_last_stacks_tip,
1,925✔
221
            committed_stacks_height,
1,925✔
222
        );
223
        Counters::set(
1,925✔
224
            &self.naka_submitted_commit_last_commit_amount,
1,925✔
225
            committed_sats_amount,
1,925✔
226
        );
227
        Counters::update(
1,925✔
228
            &self.naka_submitted_commit_last_parent_tenure_id,
1,925✔
229
            committed_parent_tenure_id,
1,925✔
230
        );
231
    }
1,925✔
232

233
    pub fn bump_naka_mined_blocks(&self) {
2,336✔
234
        Counters::inc(&self.naka_mined_blocks);
2,336✔
235
    }
2,336✔
236

237
    pub fn bump_naka_proposed_blocks(&self) {
2,433✔
238
        Counters::inc(&self.naka_proposed_blocks);
2,433✔
239
    }
2,433✔
240

241
    pub fn bump_naka_rejected_blocks(&self) {
93✔
242
        Counters::inc(&self.naka_rejected_blocks);
93✔
243
    }
93✔
244

245
    pub fn bump_naka_signer_pushed_blocks(&self) {
13✔
246
        Counters::inc(&self.naka_signer_pushed_blocks);
13✔
247
    }
13✔
248

249
    pub fn bump_naka_mined_tenures(&self) {
1,358✔
250
        Counters::inc(&self.naka_mined_tenures);
1,358✔
251
    }
1,358✔
252

253
    pub fn bump_naka_miner_directives(&self) {
1,600✔
254
        Counters::inc(&self.naka_miner_directives);
1,600✔
255
    }
1,600✔
256

257
    pub fn set_microblocks_processed(&self, value: u64) {
105✔
258
        Counters::set(&self.microblocks_processed, value)
105✔
259
    }
105✔
260

261
    pub fn set_miner_current_rejections_timeout_secs(&self, value: u64) {
129✔
262
        Counters::set(&self.naka_miner_current_rejections_timeout_secs, value)
129✔
263
    }
129✔
264

265
    pub fn set_miner_current_rejections(&self, value: u32) {
129✔
266
        Counters::set(&self.naka_miner_current_rejections, u64::from(value))
129✔
267
    }
129✔
268
}
269

270
/// Coordinating a node running in neon mode.
271
pub struct RunLoop {
272
    config: Config,
273
    pub callbacks: RunLoopCallbacks,
274
    globals: Option<Globals>,
275
    counters: Counters,
276
    coordinator_channels: Option<(CoordinatorReceivers, CoordinatorChannels)>,
277
    should_keep_running: Arc<AtomicBool>,
278
    event_dispatcher: EventDispatcher,
279
    pox_watchdog: Option<PoxSyncWatchdog>, // can't be instantiated until .start() is called
280
    is_miner: Option<bool>,                // not known until .start() is called
281
    burnchain: Option<Burnchain>,          // not known until .start() is called
282
    pox_watchdog_comms: PoxSyncWatchdogComms,
283
    /// NOTE: this is duplicated in self.globals, but it needs to be accessible before globals is
284
    /// instantiated (namely, so the test framework can access it).
285
    miner_status: Arc<Mutex<MinerStatus>>,
286
    monitoring_thread: Option<JoinHandle<Result<(), MonitoringError>>>,
287
}
288

289
/// Write to stderr in an async-safe manner.
290
/// See signal-safety(7)
UNCOV
291
fn async_safe_write_stderr(msg: &str) {
×
292
    #[cfg(windows)]
293
    unsafe {
294
        // write(2) inexplicably has a different ABI only on Windows.
295
        libc::write(
296
            STDERR,
297
            msg.as_ptr() as *const libc::c_void,
298
            msg.len() as u32,
299
        );
300
    }
301
    #[cfg(not(windows))]
UNCOV
302
    unsafe {
×
UNCOV
303
        libc::write(STDERR, msg.as_ptr() as *const libc::c_void, msg.len());
×
UNCOV
304
    }
×
UNCOV
305
}
×
306

307
impl RunLoop {
308
    /// Sets up a runloop and node, given a config.
309
    pub fn new(config: Config) -> Self {
284✔
310
        let channels = CoordinatorCommunication::instantiate();
284✔
311
        let should_keep_running = Arc::new(AtomicBool::new(true));
284✔
312
        let pox_watchdog_comms = PoxSyncWatchdogComms::new(should_keep_running.clone());
284✔
313
        let miner_status = Arc::new(Mutex::new(MinerStatus::make_ready(
284✔
314
            config.burnchain.burn_fee_cap,
284✔
315
        )));
316

317
        let mut event_dispatcher = EventDispatcher::new(config.get_working_dir());
284✔
318
        for observer in config.events_observers.iter() {
998✔
319
            event_dispatcher.register_observer(observer);
973✔
320
        }
973✔
321
        event_dispatcher.process_pending_payloads();
284✔
322

323
        Self {
284✔
324
            config,
284✔
325
            globals: None,
284✔
326
            coordinator_channels: Some(channels),
284✔
327
            callbacks: RunLoopCallbacks::new(),
284✔
328
            counters: Counters::default(),
284✔
329
            should_keep_running,
284✔
330
            event_dispatcher,
284✔
331
            pox_watchdog: None,
284✔
332
            is_miner: None,
284✔
333
            burnchain: None,
284✔
334
            pox_watchdog_comms,
284✔
335
            miner_status,
284✔
336
            monitoring_thread: None,
284✔
337
        }
284✔
338
    }
284✔
339

340
    pub fn get_globals(&self) -> Globals {
562✔
341
        self.globals
562✔
342
            .clone()
562✔
343
            .expect("FATAL: globals not instantiated")
562✔
344
    }
562✔
345

346
    fn set_globals(&mut self, globals: Globals) {
281✔
347
        self.globals = Some(globals);
281✔
348
    }
281✔
349

350
    pub fn get_coordinator_channel(&self) -> Option<CoordinatorChannels> {
282✔
351
        self.coordinator_channels.as_ref().map(|x| x.1.clone())
282✔
352
    }
282✔
353

354
    pub fn get_blocks_processed_arc(&self) -> RunLoopCounter {
37✔
355
        self.counters.blocks_processed.clone()
37✔
356
    }
37✔
357

UNCOV
358
    pub fn get_microblocks_processed_arc(&self) -> RunLoopCounter {
×
UNCOV
359
        self.counters.microblocks_processed.clone()
×
UNCOV
360
    }
×
361

362
    pub fn get_missed_tenures_arc(&self) -> RunLoopCounter {
1✔
363
        self.counters.missed_tenures.clone()
1✔
364
    }
1✔
365

UNCOV
366
    pub fn get_missed_microblock_tenures_arc(&self) -> RunLoopCounter {
×
UNCOV
367
        self.counters.missed_microblock_tenures.clone()
×
UNCOV
368
    }
×
369

UNCOV
370
    pub fn get_cancelled_commits_arc(&self) -> RunLoopCounter {
×
UNCOV
371
        self.counters.cancelled_commits.clone()
×
UNCOV
372
    }
×
373

374
    pub fn get_counters(&self) -> Counters {
543✔
375
        self.counters.clone()
543✔
376
    }
543✔
377

378
    pub fn config(&self) -> &Config {
63,727✔
379
        &self.config
63,727✔
380
    }
63,727✔
381

382
    pub fn get_event_dispatcher(&self) -> EventDispatcher {
562✔
383
        self.event_dispatcher.clone()
562✔
384
    }
562✔
385

386
    pub fn is_miner(&self) -> bool {
281✔
387
        self.is_miner.unwrap_or(false)
281✔
388
    }
281✔
389

390
    pub fn get_pox_sync_comms(&self) -> PoxSyncWatchdogComms {
1✔
391
        self.pox_watchdog_comms.clone()
1✔
392
    }
1✔
393

394
    pub fn get_termination_switch(&self) -> Arc<AtomicBool> {
740✔
395
        self.should_keep_running.clone()
740✔
396
    }
740✔
397

398
    pub fn get_burnchain(&self) -> Burnchain {
1,124✔
399
        self.burnchain
1,124✔
400
            .clone()
1,124✔
401
            .expect("FATAL: tried to get runloop burnchain before calling .start()")
1,124✔
402
    }
1,124✔
403

404
    pub fn get_pox_watchdog(&mut self) -> &mut PoxSyncWatchdog {
385,951✔
405
        self.pox_watchdog
385,951✔
406
            .as_mut()
385,951✔
407
            .expect("FATAL: tried to get PoX watchdog before calling .start()")
385,951✔
408
    }
385,951✔
409

410
    pub fn get_miner_status(&self) -> Arc<Mutex<MinerStatus>> {
281✔
411
        self.miner_status.clone()
281✔
412
    }
281✔
413

414
    /// Set up termination handler.  Have a signal set the `should_keep_running` atomic bool to
415
    /// false.  Panics of called more than once.
416
    pub fn setup_termination_handler(keep_running_writer: Arc<AtomicBool>, allow_err: bool) {
526✔
417
        let install = termination::set_handler(move |sig_id| match sig_id {
526✔
418
            SignalId::Bus => {
UNCOV
419
                let msg = "Caught SIGBUS; crashing immediately and dumping core\n";
×
UNCOV
420
                async_safe_write_stderr(msg);
×
421
                unsafe {
UNCOV
422
                    libc::abort();
×
423
                }
424
            }
UNCOV
425
            _ => {
×
UNCOV
426
                let msg = format!("Graceful termination request received (signal `{sig_id}`), will complete the ongoing runloop cycles and terminate\n");
×
UNCOV
427
                async_safe_write_stderr(&msg);
×
UNCOV
428
                keep_running_writer.store(false, Ordering::SeqCst);
×
UNCOV
429
            }
×
UNCOV
430
        });
×
431

432
        if let Err(e) = install {
526✔
433
            // integration tests can do this
434
            if cfg!(test) || allow_err {
295✔
435
                info!("Error setting up signal handler, may have already been set");
295✔
436
            } else {
437
                panic!("FATAL: error setting termination handler - {e}");
×
438
            }
439
        }
231✔
440
    }
526✔
441

442
    /// Seconds to wait before retrying UTXO check during startup
443
    const UTXO_RETRY_INTERVAL: u64 = 10;
444
    /// Number of times to retry UTXO check during startup
445
    const UTXO_RETRY_COUNT: u64 = 6;
446

447
    /// Determine if we're the miner.
448
    /// If there's a network error, then assume that we're not a miner.
449
    fn check_is_miner(&mut self, burnchain: &mut BitcoinRegtestController) -> bool {
282✔
450
        if self.config.node.miner {
282✔
451
            // If we are mock mining, then we don't need to check for UTXOs and
452
            // we can just return true.
453
            if self.config.get_node_config(false).mock_mining {
277✔
454
                return true;
5✔
455
            }
272✔
456
            let keychain = Keychain::default(self.config.node.seed.clone());
272✔
457
            let mut op_signer = keychain.generate_op_signer();
272✔
458
            if let Err(e) = burnchain.create_wallet_if_dne() {
272✔
UNCOV
459
                warn!("Error when creating wallet: {e:?}");
×
460
            }
272✔
461
            let mut btc_addrs = vec![(
272✔
462
                StacksEpochId::Epoch2_05,
272✔
463
                // legacy
272✔
464
                BitcoinAddress::from_bytes_legacy(
272✔
465
                    self.config.burnchain.get_bitcoin_network().1,
272✔
466
                    LegacyBitcoinAddressType::PublicKeyHash,
272✔
467
                    &Hash160::from_data(&op_signer.get_public_key().to_bytes()).0,
272✔
468
                )
272✔
469
                .expect("FATAL: failed to construct legacy bitcoin address"),
272✔
470
            )];
272✔
471
            if self.config.miner.segwit {
272✔
UNCOV
472
                btc_addrs.push((
×
UNCOV
473
                    StacksEpochId::Epoch21,
×
UNCOV
474
                    // segwit p2wpkh
×
UNCOV
475
                    BitcoinAddress::from_bytes_segwit_p2wpkh(
×
UNCOV
476
                        self.config.burnchain.get_bitcoin_network().1,
×
477
                        &Hash160::from_data(&op_signer.get_public_key().to_bytes_compressed()).0,
×
UNCOV
478
                    )
×
UNCOV
479
                    .expect("FATAL: failed to construct segwit p2wpkh address"),
×
UNCOV
480
                ));
×
481
            }
272✔
482

483
            // retry UTXO check a few times, in case bitcoind is still starting up
484
            for _ in 0..Self::UTXO_RETRY_COUNT {
272✔
485
                for (epoch_id, btc_addr) in &btc_addrs {
280✔
486
                    info!("Miner node: checking UTXOs at address: {btc_addr}");
280✔
487
                    let utxos =
280✔
488
                        burnchain.get_utxos(*epoch_id, &op_signer.get_public_key(), 1, None, 0);
280✔
489
                    if utxos.is_none() {
280✔
490
                        warn!("UTXOs not found for {btc_addr}. If this is unexpected, please ensure that your bitcoind instance is indexing transactions for the address {btc_addr} (importaddress)");
9✔
491
                    } else {
492
                        info!("UTXOs found - will run as a Miner node");
271✔
493
                        return true;
271✔
494
                    }
495
                }
496
                thread::sleep(std::time::Duration::from_secs(Self::UTXO_RETRY_INTERVAL));
9✔
497
            }
498
            panic!("No UTXOs found, exiting");
1✔
499
        } else {
500
            info!("Will run as a Follower node");
5✔
501
            false
5✔
502
        }
503
    }
281✔
504

505
    /// Instantiate the burnchain client and databases.
506
    /// Fetches headers and instantiates the burnchain.
507
    /// Panics on failure.
508
    pub fn instantiate_burnchain_state(
526✔
509
        config: &Config,
526✔
510
        should_keep_running: Arc<AtomicBool>,
526✔
511
        burnchain_opt: Option<Burnchain>,
526✔
512
        coordinator_senders: CoordinatorChannels,
526✔
513
    ) -> Result<BitcoinRegtestController, burnchain_error> {
526✔
514
        // Initialize and start the burnchain.
515
        let mut burnchain_controller = BitcoinRegtestController::with_burnchain(
526✔
516
            config.clone(),
526✔
517
            Some(coordinator_senders),
526✔
518
            burnchain_opt,
526✔
519
            Some(should_keep_running.clone()),
526✔
520
        );
521

522
        let burnchain = burnchain_controller.get_burnchain();
526✔
523
        let epochs = burnchain_controller.get_stacks_epochs();
526✔
524

525
        // sanity check -- epoch data must be valid
526
        Config::assert_valid_epoch_settings(&burnchain, &epochs);
526✔
527

528
        // Upgrade chainstate databases if they exist already
529
        // NOTE: this has to be done before the subsequent call to
530
        // `burnchain_controller.connect_dbs()` below!
531
        match migrate_chainstate_dbs(
526✔
532
            &epochs,
526✔
533
            &burnchain,
526✔
534
            &config.get_burn_db_file_path(),
526✔
535
            &config.get_chainstate_path_str(),
526✔
536
            Some(config.node.get_marf_opts()),
526✔
537
        ) {
538
            Ok(_) => {}
526✔
539
            Err(coord_error::DBError(db_error::TooOldForEpoch)) => {
UNCOV
540
                error!(
×
541
                    "FATAL: chainstate database(s) are not compatible with the current system epoch"
542
                );
UNCOV
543
                panic!();
×
544
            }
UNCOV
545
            Err(e) => {
×
UNCOV
546
                panic!("FATAL: unable to query filesystem or databases: {e:?}");
×
547
            }
548
        }
549

550
        info!("Start syncing Bitcoin headers, feel free to grab a cup of coffee, this can take a while");
526✔
551

552
        let burnchain_config = burnchain_controller.get_burnchain();
526✔
553
        let target_burnchain_block_height = match burnchain_config
526✔
554
            .get_highest_burnchain_block()
526✔
555
            .expect("FATAL: failed to access burnchain database")
526✔
556
        {
557
            Some(burnchain_tip) => {
244✔
558
                // database exists already, and has blocks -- just sync to its tip.
559
                let target_height = burnchain_tip.block_height + 1;
244✔
560
                debug!("Burnchain DB exists and has blocks up to {}; synchronizing from where it left off up to {target_height}", burnchain_tip.block_height);
244✔
561
                target_height
244✔
562
            }
563
            None => {
564
                // database does not exist yet
565
                let target_height = 1.max(burnchain_config.first_block_height + 1);
282✔
566
                debug!("Burnchain DB does not exist or does not have blocks; synchronizing to first burnchain block height {target_height}");
282✔
567
                target_height
282✔
568
            }
569
        };
570

571
        burnchain_controller
526✔
572
            .start(Some(target_burnchain_block_height))
526✔
573
            .map_err(|e| {
526✔
574
                if matches!(e, Error::CoordinatorClosed)
1✔
575
                    && !should_keep_running.load(Ordering::SeqCst)
1✔
576
                {
577
                    info!("Shutdown initiated during burnchain initialization: {e}");
1✔
578
                    return burnchain_error::ShutdownInitiated;
1✔
UNCOV
579
                }
×
UNCOV
580
                error!("Burnchain controller stopped: {e}");
×
UNCOV
581
                panic!();
×
582
            })?;
1✔
583

584
        // if the chainstate DBs don't exist, this will instantiate them
585
        if let Err(e) = burnchain_controller.connect_dbs() {
525✔
UNCOV
586
            error!("Failed to connect to burnchain databases: {e}");
×
UNCOV
587
            panic!();
×
588
        };
525✔
589

590
        // TODO (hack) instantiate the sortdb in the burnchain
591
        let _ = burnchain_controller.sortdb_mut();
525✔
592
        Ok(burnchain_controller)
525✔
593
    }
526✔
594

595
    /// Boot up the stacks chainstate.
596
    /// Instantiate the chainstate and push out the boot receipts to observers
597
    /// This is only public so we can test it.
598
    pub fn boot_chainstate(&mut self, burnchain_config: &Burnchain) -> StacksChainState {
282✔
599
        let use_test_genesis_data = use_test_genesis_chainstate(&self.config);
282✔
600

601
        // load up genesis balances
602
        let initial_balances = self
282✔
603
            .config
282✔
604
            .initial_balances
282✔
605
            .iter()
282✔
606
            .map(|e| (e.address.clone(), e.amount))
2,183✔
607
            .collect();
282✔
608

609
        // instantiate chainstate
610
        let mut boot_data = ChainStateBootData {
282✔
611
            initial_balances,
282✔
612
            post_flight_callback: None,
282✔
613
            first_burnchain_block_hash: burnchain_config.first_block_hash.clone(),
282✔
614
            first_burnchain_block_height: burnchain_config.first_block_height as u32,
282✔
615
            first_burnchain_block_timestamp: burnchain_config.first_block_timestamp,
282✔
616
            pox_constants: burnchain_config.pox_constants.clone(),
282✔
617
            get_bulk_initial_lockups: Some(Box::new(move || {
282✔
618
                get_account_lockups(use_test_genesis_data)
282✔
619
            })),
282✔
620
            get_bulk_initial_balances: Some(Box::new(move || {
282✔
621
                get_account_balances(use_test_genesis_data)
282✔
622
            })),
282✔
623
            get_bulk_initial_namespaces: Some(Box::new(move || {
282✔
624
                get_namespaces(use_test_genesis_data)
282✔
625
            })),
282✔
626
            get_bulk_initial_names: Some(Box::new(move || get_names(use_test_genesis_data))),
282✔
627
        };
628

629
        info!("About to call open_and_exec");
282✔
630
        let (chain_state_db, receipts) = StacksChainState::open_and_exec(
282✔
631
            self.config.is_mainnet(),
282✔
632
            self.config.burnchain.chain_id,
282✔
633
            &self.config.get_chainstate_path_str(),
282✔
634
            Some(&mut boot_data),
282✔
635
            Some(self.config.node.get_marf_opts()),
282✔
636
        )
282✔
637
        .unwrap();
282✔
638
        run_loop::announce_boot_receipts(
282✔
639
            &mut self.event_dispatcher,
282✔
640
            &chain_state_db,
282✔
641
            &burnchain_config.pox_constants,
282✔
642
            &receipts,
282✔
643
        );
644
        chain_state_db
282✔
645
    }
282✔
646

647
    /// Instantiate the Stacks chain state and start the chains coordinator thread.
648
    /// Returns the coordinator thread handle, and the receiving end of the coordinator's atlas
649
    /// attachment channel.
650
    fn spawn_chains_coordinator(
281✔
651
        &mut self,
281✔
652
        burnchain_config: &Burnchain,
281✔
653
        coordinator_receivers: CoordinatorReceivers,
281✔
654
        miner_status: Arc<Mutex<MinerStatus>>,
281✔
655
    ) -> JoinHandle<()> {
281✔
656
        let use_test_genesis_data = use_test_genesis_chainstate(&self.config);
281✔
657

658
        // load up genesis Atlas attachments
659
        let mut atlas_config = AtlasConfig::new(self.config.is_mainnet());
281✔
660
        let genesis_attachments = GenesisData::new(use_test_genesis_data)
281✔
661
            .read_name_zonefiles()
281✔
662
            .map(|z| Attachment::new(z.zonefile_content.as_bytes().to_vec()))
3,372✔
663
            .collect();
281✔
664
        atlas_config.genesis_attachments = Some(genesis_attachments);
281✔
665

666
        let chain_state_db = self.boot_chainstate(burnchain_config);
281✔
667

668
        // NOTE: re-instantiate AtlasConfig so we don't have to keep the genesis attachments around
669
        let moved_atlas_config = self.config.atlas.clone();
281✔
670
        let moved_config = self.config.clone();
281✔
671
        let moved_burnchain_config = burnchain_config.clone();
281✔
672
        let coordinator_dispatcher = self.event_dispatcher.clone();
281✔
673
        let atlas_db = AtlasDB::connect(
281✔
674
            moved_atlas_config.clone(),
281✔
675
            &self.config.get_atlas_db_file_path(),
281✔
676
            true,
677
        )
678
        .expect("Failed to connect Atlas DB during startup");
281✔
679
        let coordinator_indexer =
281✔
680
            make_bitcoin_indexer(&self.config, Some(self.should_keep_running.clone()));
281✔
681

682
        let coordinator_thread_handle = thread::Builder::new()
281✔
683
            .name(format!(
281✔
684
                "chains-coordinator-{}",
685
                &moved_config.node.rpc_bind
281✔
686
            ))
687
            .stack_size(BLOCK_PROCESSOR_STACK_SIZE)
281✔
688
            .spawn(move || {
281✔
689
                debug!(
281✔
690
                    "chains-coordinator thread ID is {:?}",
UNCOV
691
                    thread::current().id()
×
692
                );
693
                let mut cost_estimator = moved_config.make_cost_estimator();
281✔
694
                let mut fee_estimator = moved_config.make_fee_estimator();
281✔
695

696
                let coord_config = ChainsCoordinatorConfig {
281✔
697
                    txindex: moved_config.node.txindex,
281✔
698
                };
281✔
699
                ChainsCoordinator::run(
281✔
700
                    coord_config,
281✔
701
                    chain_state_db,
281✔
702
                    moved_burnchain_config,
281✔
703
                    &coordinator_dispatcher,
281✔
704
                    coordinator_receivers,
281✔
705
                    moved_atlas_config,
281✔
706
                    cost_estimator.as_deref_mut(),
281✔
707
                    fee_estimator.as_deref_mut(),
281✔
708
                    miner_status,
281✔
709
                    coordinator_indexer,
281✔
710
                    atlas_db,
281✔
711
                );
712
            })
281✔
713
            .expect("FATAL: failed to start chains coordinator thread");
281✔
714

715
        coordinator_thread_handle
281✔
716
    }
281✔
717

718
    /// Instantiate the PoX watchdog
719
    fn instantiate_pox_watchdog(&mut self) {
281✔
720
        let pox_watchdog = PoxSyncWatchdog::new(&self.config, self.pox_watchdog_comms.clone())
281✔
721
            .expect("FATAL: failed to instantiate PoX sync watchdog");
281✔
722
        self.pox_watchdog = Some(pox_watchdog);
281✔
723
    }
281✔
724

725
    /// Start Prometheus logging
726
    fn start_prometheus(&mut self) {
281✔
727
        let Some(prometheus_bind) = self.config.node.prometheus_bind.clone() else {
281✔
728
            return;
273✔
729
        };
730
        let monitoring_thread = thread::Builder::new()
8✔
731
            .name("prometheus".to_string())
8✔
732
            .spawn(move || {
8✔
733
                debug!("prometheus thread ID is {:?}", thread::current().id());
8✔
734
                start_serving_monitoring_metrics(prometheus_bind)
8✔
735
            })
8✔
736
            .expect("FATAL: failed to start monitoring thread");
8✔
737

738
        self.monitoring_thread.replace(monitoring_thread);
8✔
739
    }
281✔
740

741
    pub fn take_monitoring_thread(&mut self) -> Option<JoinHandle<Result<(), MonitoringError>>> {
242✔
742
        self.monitoring_thread.take()
242✔
743
    }
242✔
744

745
    /// Get the sortition DB's highest block height, aligned to a reward cycle boundary, and the
746
    /// highest sortition.
747
    /// Returns (height at rc start, sortition)
748
    fn get_reward_cycle_sortition_db_height(
281✔
749
        sortdb: &SortitionDB,
281✔
750
        burnchain_config: &Burnchain,
281✔
751
    ) -> (u64, BlockSnapshot) {
281✔
752
        let (stacks_ch, _) = SortitionDB::get_canonical_stacks_chain_tip_hash(sortdb.conn())
281✔
753
            .expect("BUG: failed to load canonical stacks chain tip hash");
281✔
754

755
        let sn = match SortitionDB::get_block_snapshot_consensus(sortdb.conn(), &stacks_ch)
281✔
756
            .expect("BUG: failed to query sortition DB")
281✔
757
        {
758
            Some(sn) => sn,
281✔
759
            None => {
UNCOV
760
                debug!("No canonical stacks chain tip hash present");
×
UNCOV
761
                let sn = SortitionDB::get_first_block_snapshot(sortdb.conn())
×
UNCOV
762
                    .expect("BUG: failed to get first-ever block snapshot");
×
UNCOV
763
                sn
×
764
            }
765
        };
766

767
        (
281✔
768
            burnchain_config.reward_cycle_to_block_height(
281✔
769
                burnchain_config
281✔
770
                    .block_height_to_reward_cycle(sn.block_height)
281✔
771
                    .expect("BUG: snapshot preceeds first reward cycle"),
281✔
772
            ),
281✔
773
            sn,
281✔
774
        )
281✔
775
    }
281✔
776

777
    /// Starts the node runloop.
778
    ///
779
    /// This function will block by looping infinitely.
780
    /// It will start the burnchain (separate thread), set-up a channel in
781
    /// charge of coordinating the new blocks coming from the burnchain and
782
    /// the nodes, taking turns on tenures.
783
    ///
784
    /// Returns `Option<NeonGlobals>` so that data can be passed to `NakamotoNode`
785
    pub fn start(
283✔
786
        &mut self,
283✔
787
        burnchain_opt: Option<Burnchain>,
283✔
788
        mut mine_start: u64,
283✔
789
    ) -> Option<Neon2NakaData> {
283✔
790
        let (coordinator_receivers, coordinator_senders) = self
283✔
791
            .coordinator_channels
283✔
792
            .take()
283✔
793
            .expect("Run loop already started, can only start once after initialization.");
283✔
794

795
        // Apply config-driven process-wide state before any chainstate is opened.
796
        self.config.apply_runtime_state();
283✔
797

798
        Self::setup_termination_handler(self.should_keep_running.clone(), false);
283✔
799

800
        let burnchain_result = Self::instantiate_burnchain_state(
283✔
801
            &self.config,
283✔
802
            self.should_keep_running.clone(),
283✔
803
            burnchain_opt,
283✔
804
            coordinator_senders.clone(),
283✔
805
        );
806

807
        let mut burnchain = match burnchain_result {
282✔
808
            Ok(burnchain_controller) => burnchain_controller,
282✔
809
            Err(burnchain_error::ShutdownInitiated) => {
810
                info!("Exiting stacks-node");
1✔
811
                return None;
1✔
812
            }
UNCOV
813
            Err(e) => {
×
UNCOV
814
                error!("Error initializing burnchain: {e}");
×
UNCOV
815
                info!("Exiting stacks-node");
×
UNCOV
816
                return None;
×
817
            }
818
        };
819

820
        let burnchain_config = burnchain.get_burnchain();
282✔
821
        self.burnchain = Some(burnchain_config.clone());
282✔
822

823
        // can we mine?
824
        let is_miner = self.check_is_miner(&mut burnchain);
282✔
825
        self.is_miner = Some(is_miner);
282✔
826

827
        // relayer linkup
828
        let (relay_send, relay_recv) = sync_channel(RELAYER_MAX_BUFFER);
282✔
829

830
        // set up globals so other subsystems can instantiate off of the runloop state.
831
        let globals = Globals::new(
282✔
832
            coordinator_senders,
282✔
833
            self.get_miner_status(),
282✔
834
            relay_send,
282✔
835
            self.counters.clone(),
282✔
836
            self.pox_watchdog_comms.clone(),
282✔
837
            self.should_keep_running.clone(),
282✔
838
            mine_start,
282✔
839
            LeaderKeyRegistrationState::default(),
282✔
840
        );
841
        self.set_globals(globals.clone());
282✔
842

843
        // have headers; boot up the chains coordinator and instantiate the chain state
844
        let coordinator_thread_handle = self.spawn_chains_coordinator(
282✔
845
            &burnchain_config,
282✔
846
            coordinator_receivers,
282✔
847
            globals.get_miner_status(),
282✔
848
        );
849
        self.instantiate_pox_watchdog();
282✔
850
        self.start_prometheus();
282✔
851

852
        // We announce a new burn block so that the chains coordinator
853
        // can resume prior work and handle eventual unprocessed sortitions
854
        // stored during a previous session.
855
        globals.coord().announce_new_burn_block();
282✔
856

857
        // Make sure at least one sortition has happened, and make sure it's globally available
858
        let sortdb = burnchain.sortdb_mut();
282✔
859
        let (rc_aligned_height, sn) =
282✔
860
            RunLoop::get_reward_cycle_sortition_db_height(sortdb, &burnchain_config);
282✔
861

862
        let burnchain_tip_snapshot = if sn.block_height == burnchain_config.first_block_height {
282✔
863
            // need at least one sortition to happen.
864
            burnchain
281✔
865
                .wait_for_sortitions(globals.coord().clone(), sn.block_height + 1)
281✔
866
                .expect("Unable to get burnchain tip")
281✔
867
                .block_snapshot
281✔
868
        } else {
869
            sn
1✔
870
        };
871

872
        globals.set_last_sortition(burnchain_tip_snapshot);
282✔
873

874
        // Boot up the p2p network and relayer, and figure out how many sortitions we have so far
875
        // (it could be non-zero if the node is resuming from chainstate)
876
        let mut node = StacksNode::spawn(self, globals.clone(), relay_recv);
282✔
877

878
        // Wait for all pending sortitions to process
879
        let burnchain_db = burnchain_config
282✔
880
            .open_burnchain_db(true)
282✔
881
            .expect("FATAL: failed to open burnchain DB");
282✔
882
        let burnchain_db_tip = burnchain_db
282✔
883
            .get_canonical_chain_tip()
282✔
884
            .expect("FATAL: failed to query burnchain DB");
282✔
885
        let mut burnchain_tip = burnchain
282✔
886
            .wait_for_sortitions(globals.coord().clone(), burnchain_db_tip.block_height)
282✔
887
            .expect("Unable to get burnchain tip");
282✔
888

889
        // Start the runloop
890
        debug!("Runloop: Begin run loop");
282✔
891
        self.counters.bump_blocks_processed();
282✔
892

893
        let mut sortition_db_height = rc_aligned_height;
282✔
894
        let mut burnchain_height = sortition_db_height;
282✔
895

896
        // prepare to fetch the first reward cycle!
897
        debug!("Runloop: Begin main runloop starting a burnchain block {sortition_db_height}");
282✔
898

899
        let mut last_tenure_sortition_height = 0;
282✔
900

901
        loop {
902
            if !globals.keep_running() {
386,098✔
903
                // The p2p thread relies on the same atomic_bool, it will
904
                // discontinue its execution after completing its ongoing runloop epoch.
905
                info!("Terminating p2p process");
147✔
906
                info!("Terminating relayer");
147✔
907
                info!("Terminating chains-coordinator");
147✔
908

909
                globals.coord().stop_chains_coordinator();
147✔
910
                coordinator_thread_handle.join().unwrap();
147✔
911
                let peer_network = node.join();
147✔
912

913
                // Data that will be passed to Nakamoto run loop
914
                // Only gets transferred on clean shutdown of neon run loop
915
                let data_to_naka = Neon2NakaData::new(globals, peer_network);
147✔
916

917
                info!("Exiting stacks-node");
147✔
918
                break Some(data_to_naka);
147✔
919
            }
385,951✔
920

921
            let remote_chain_height = burnchain.get_headers_height() - 1;
385,951✔
922

923
            // wait until it's okay to process the next reward cycle's sortitions.
924
            let (ibd, target_burnchain_block_height) = match self.get_pox_watchdog().pox_sync_wait(
385,951✔
925
                &burnchain_config,
385,951✔
926
                &burnchain_tip,
385,951✔
927
                remote_chain_height,
385,951✔
928
            ) {
385,951✔
929
                Ok(x) => x,
385,864✔
930
                Err(e) => {
87✔
931
                    debug!("Runloop: PoX sync wait routine aborted: {e:?}");
87✔
932
                    continue;
87✔
933
                }
934
            };
935

936
            // calculate burnchain sync percentage
937
            let percent: f64 = if remote_chain_height > 0 {
385,864✔
938
                burnchain_tip.block_snapshot.block_height as f64 / remote_chain_height as f64
385,862✔
939
            } else {
940
                0.0
2✔
941
            };
942

943
            // Download each burnchain block and process their sortitions.  This, in turn, will
944
            // cause the node's p2p and relayer threads to go fetch and download Stacks blocks and
945
            // process them.  This loop runs for one reward cycle, so that the next pass of the
946
            // runloop will cause the PoX sync watchdog to wait until it believes that the node has
947
            // obtained all the Stacks blocks it can.
948
            debug!(
385,864✔
949
                "Runloop: Download burnchain blocks up to reward cycle #{} (height {target_burnchain_block_height})",
UNCOV
950
                burnchain_config
×
UNCOV
951
                    .block_height_to_reward_cycle(target_burnchain_block_height)
×
UNCOV
952
                    .expect("FATAL: target burnchain block height does not have a reward cycle");
×
953
                "total_burn_sync_percent" => %percent,
UNCOV
954
                "local_burn_height" => burnchain_tip.block_snapshot.block_height,
×
955
                "remote_tip_height" => remote_chain_height
×
956
            );
957

958
            loop {
959
                if !globals.keep_running() {
385,905✔
960
                    break;
43✔
961
                }
385,862✔
962

963
                let (next_burnchain_tip, tip_burnchain_height) =
385,819✔
964
                    match burnchain.sync(Some(target_burnchain_block_height)) {
385,862✔
965
                        Ok(x) => x,
385,819✔
966
                        Err(e) => {
43✔
967
                            warn!("Runloop: Burnchain controller stopped: {e}");
43✔
968
                            continue;
43✔
969
                        }
970
                    };
971

972
                // *now* we know the burnchain height
973
                burnchain_tip = next_burnchain_tip;
385,819✔
974
                burnchain_height = tip_burnchain_height;
385,819✔
975

976
                let sortition_tip = &burnchain_tip.block_snapshot.sortition_id;
385,819✔
977
                let next_sortition_height = burnchain_tip.block_snapshot.block_height;
385,819✔
978

979
                if next_sortition_height != last_tenure_sortition_height {
385,819✔
980
                    info!(
11,603✔
981
                        "Runloop: Downloaded burnchain blocks up to height {burnchain_height}; target height is {target_burnchain_block_height}; remote_chain_height = {remote_chain_height} next_sortition_height = {next_sortition_height}, sortition_db_height = {sortition_db_height}"
982
                    );
983
                }
374,216✔
984

985
                if next_sortition_height > sortition_db_height {
385,819✔
986
                    debug!(
11,441✔
987
                        "Runloop: New burnchain block height {next_sortition_height} > {sortition_db_height}"
988
                    );
989

990
                    debug!("Runloop: block mining until we process all sortitions");
11,441✔
991
                    signal_mining_blocked(globals.get_miner_status());
11,441✔
992

993
                    // first, let's process all blocks in (sortition_db_height, next_sortition_height]
994
                    for block_to_process in (sortition_db_height + 1)..(next_sortition_height + 1) {
62,884✔
995
                        // stop mining so we can advance the sortition DB and so our
996
                        // ProcessTenure() directive (sent by relayer_sortition_notify() below)
997
                        // will be unblocked.
998

999
                        let block = {
62,884✔
1000
                            let ic = burnchain.sortdb_ref().index_conn();
62,884✔
1001
                            SortitionDB::get_ancestor_snapshot(&ic, block_to_process, sortition_tip)
62,884✔
1002
                                .unwrap()
62,884✔
1003
                                .expect(
62,884✔
1004
                                    "Failed to find block in fork processed by burnchain indexer",
62,884✔
1005
                                )
1006
                        };
1007

1008
                        let sortition_id = &block.sortition_id;
62,884✔
1009

1010
                        // Have the node process the new block, that can include, or not, a sortition.
1011
                        node.process_burnchain_state(
62,884✔
1012
                            self.config(),
62,884✔
1013
                            burnchain.sortdb_mut(),
62,884✔
1014
                            sortition_id,
62,884✔
1015
                            ibd,
62,884✔
1016
                        );
1017

1018
                        // Now, tell the relayer to check if it won a sortition during this block,
1019
                        // and, if so, to process and advertize the block.  This is basically a
1020
                        // no-op during boot-up.
1021
                        //
1022
                        // _this will block if the relayer's buffer is full_
1023
                        if !node.relayer_sortition_notify() {
62,884✔
1024
                            // First check if we were supposed to cleanly exit
1025
                            if !globals.keep_running() {
63✔
1026
                                // The p2p thread relies on the same atomic_bool, it will
1027
                                // discontinue its execution after completing its ongoing runloop epoch.
1028
                                info!("Terminating p2p process");
63✔
1029
                                info!("Terminating relayer");
63✔
1030
                                info!("Terminating chains-coordinator");
63✔
1031

1032
                                globals.coord().stop_chains_coordinator();
63✔
1033
                                coordinator_thread_handle.join().unwrap();
63✔
1034
                                let peer_network = node.join();
63✔
1035

1036
                                // Data that will be passed to Nakamoto run loop
1037
                                // Only gets transferred on clean shutdown of neon run loop
1038
                                let data_to_naka = Neon2NakaData::new(globals, peer_network);
63✔
1039

1040
                                info!("Exiting stacks-node");
63✔
1041
                                return Some(data_to_naka);
63✔
UNCOV
1042
                            }
×
1043
                            // relayer hung up, exit.
UNCOV
1044
                            error!("Runloop: Block relayer and miner hung up, exiting.");
×
UNCOV
1045
                            return None;
×
1046
                        }
62,821✔
1047
                    }
1048

1049
                    debug!("Runloop: enable miner after processing sortitions");
11,378✔
1050
                    signal_mining_ready(globals.get_miner_status());
11,378✔
1051

1052
                    debug!(
11,378✔
1053
                        "Runloop: Synchronized sortitions up to block height {next_sortition_height} from {sortition_db_height} (chain tip height is {burnchain_height})"
1054
                    );
1055

1056
                    sortition_db_height = next_sortition_height;
11,378✔
1057
                } else if ibd {
374,378✔
UNCOV
1058
                    // drive block processing after we reach the burnchain tip.
×
1059
                    // we may have downloaded all the blocks already,
×
1060
                    // so we can't rely on the relayer alone to
×
UNCOV
1061
                    // drive it.
×
UNCOV
1062
                    globals.coord().announce_new_stacks_block();
×
1063
                }
374,378✔
1064

1065
                if burnchain_height >= target_burnchain_block_height
385,756✔
1066
                    || burnchain_height >= remote_chain_height
36✔
1067
                {
1068
                    break;
385,758✔
1069
                }
2,147,483,647✔
1070
            }
1071

1072
            if sortition_db_height >= burnchain_height && !ibd {
385,801✔
1073
                let canonical_stacks_tip_height =
374,344✔
1074
                    SortitionDB::get_canonical_burn_chain_tip(burnchain.sortdb_ref().conn())
374,344✔
1075
                        .map(|snapshot| snapshot.canonical_stacks_tip_height)
374,344✔
1076
                        .unwrap_or(0);
374,344✔
1077
                if canonical_stacks_tip_height < mine_start {
374,344✔
UNCOV
1078
                    info!(
×
1079
                        "Runloop: Synchronized full burnchain, but stacks tip height is {canonical_stacks_tip_height}, and we are trying to boot to {mine_start}, not mining until reaching chain tip"
1080
                    );
1081
                } else {
1082
                    // once we've synced to the chain tip once, don't apply this check again.
1083
                    //  this prevents a possible corner case in the event of a PoX fork.
1084
                    mine_start = 0;
374,344✔
1085
                    globals.set_start_mining_height_if_zero(sortition_db_height);
374,344✔
1086

1087
                    // at tip, and not downloading. proceed to mine.
1088
                    if last_tenure_sortition_height != sortition_db_height {
374,344✔
1089
                        if is_miner {
8,005✔
1090
                            info!(
8,003✔
1091
                                "Runloop: Synchronized full burnchain up to height {sortition_db_height}. Proceeding to mine blocks"
1092
                            );
1093
                        } else {
1094
                            info!(
2✔
1095
                                "Runloop: Synchronized full burnchain up to height {sortition_db_height}."
1096
                            );
1097
                        }
1098
                        last_tenure_sortition_height = sortition_db_height;
8,005✔
1099
                    }
366,339✔
1100

1101
                    if !node.relayer_issue_tenure(ibd) {
374,344✔
1102
                        // First check if we were supposed to cleanly exit
1103
                        if !globals.keep_running() {
72✔
1104
                            // The p2p thread relies on the same atomic_bool, it will
1105
                            // discontinue its execution after completing its ongoing runloop epoch.
1106
                            info!("Terminating p2p process");
72✔
1107
                            info!("Terminating relayer");
72✔
1108
                            info!("Terminating chains-coordinator");
72✔
1109

1110
                            globals.coord().stop_chains_coordinator();
72✔
1111
                            coordinator_thread_handle.join().unwrap();
72✔
1112
                            let peer_network = node.join();
72✔
1113

1114
                            // Data that will be passed to Nakamoto run loop
1115
                            // Only gets transferred on clean shutdown of neon run loop
1116
                            let data_to_naka = Neon2NakaData::new(globals, peer_network);
72✔
1117

1118
                            info!("Exiting stacks-node");
72✔
1119
                            return Some(data_to_naka);
72✔
UNCOV
1120
                        }
×
1121
                        // relayer hung up, exit.
UNCOV
1122
                        error!("Runloop: Block relayer and miner hung up, exiting.");
×
UNCOV
1123
                        break None;
×
1124
                    }
171,405✔
1125
                }
1126
            }
11,457✔
1127
        }
1128
    }
283✔
1129
}
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