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

stacks-network / stacks-core / 26399134379-1

25 May 2026 11:53AM UTC coverage: 85.974% (+0.02%) from 85.959%
26399134379-1

Pull #7233

github

e74aea
web-flow
Merge 32d5ba16e into 30629d416
Pull Request #7233: fix: prevent counting duplicate lockups in pox-5

48 of 57 new or added lines in 2 files covered. (84.21%)

6122 existing lines in 96 files now uncovered.

189662 of 220603 relevant lines covered (85.97%)

17663616.59 hits per line

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

87.31
/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(
461✔
62
        first_burnchain_block_hash: &BurnchainHeaderHash,
461✔
63
        first_burnchain_block_height: u64,
461✔
64
        first_burnchain_block_timestamp: u64,
461✔
65
    ) -> ChainTip {
461✔
66
        ChainTip {
461✔
67
            metadata: StacksHeaderInfo::genesis(
461✔
68
                TrieHash([0u8; 32]),
461✔
69
                first_burnchain_block_hash,
461✔
70
                first_burnchain_block_height as u32,
461✔
71
                first_burnchain_block_timestamp,
461✔
72
            ),
461✔
73
            block: StacksBlock::genesis_block(),
461✔
74
            receipts: vec![],
461✔
75
        }
461✔
76
    }
461✔
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(
298✔
96
    use_test_chainstate_data: bool,
298✔
97
) -> Box<dyn Iterator<Item = ChainstateAccountLockup>> {
298✔
98
    Box::new(
298✔
99
        stx_genesis::GenesisData::new(use_test_chainstate_data)
298✔
100
            .read_lockups()
298✔
101
            .map(|item| ChainstateAccountLockup {
298✔
102
                address: item.address,
5,960✔
103
                amount: item.amount,
5,960✔
104
                block_height: item.block_height,
5,960✔
105
            }),
5,960✔
106
    )
107
}
298✔
108

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

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

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

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

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

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

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

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

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

238
            let net_result = this
252✔
239
                .run(
252✔
240
                    &indexer,
252✔
241
                    &sortdb,
252✔
242
                    &mut chainstate,
252✔
243
                    &mut mem_pool,
252✔
244
                    None,
252✔
245
                    false,
246
                    false,
247
                    poll_timeout,
252✔
248
                    &handler_args,
252✔
249
                    config.node.txindex,
252✔
250
                )
251
                .unwrap();
252✔
252
            if net_result.has_transactions() {
252✔
253
                event_dispatcher.process_new_mempool_txs(net_result.transactions())
1✔
254
            }
241✔
255
            // Dispatch retrieved attachments, if any.
256
            if net_result.has_attachments() {
242✔
UNCOV
257
                event_dispatcher.process_new_attachments(&net_result.attachments);
×
258
            }
242✔
259
        }
260
    });
261
    server_thread
10✔
262
}
10✔
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 {
1,083✔
267
    if env::var("BLOCKSTACK_USE_TEST_GENESIS_CHAINSTATE") == Ok("1".to_string()) {
1,083✔
UNCOV
268
        true
×
269
    } else if let Some(use_test_genesis_chainstate) = config.node.use_test_genesis_chainstate {
1,083✔
UNCOV
270
        use_test_genesis_chainstate
×
271
    } else {
272
        USE_TEST_GENESIS_CHAINSTATE
1,083✔
273
    }
274
}
1,083✔
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 {
10✔
279
        let use_test_genesis_data = if config.burnchain.mode == "mocknet" {
10✔
280
            use_test_genesis_chainstate(&config)
10✔
281
        } else {
UNCOV
282
            USE_TEST_GENESIS_CHAINSTATE
×
283
        };
284

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

399
    // This function is used for helium and mocknet.
400
    pub fn spawn_peer_server(&mut self) {
10✔
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();
10✔
404
        let sortdb = SortitionDB::open(
10✔
405
            &self.config.get_burn_db_file_path(),
10✔
406
            true,
407
            burnchain.pox_constants.clone(),
10✔
408
            Some(self.config.node.get_marf_opts()),
10✔
409
        )
410
        .expect("Error while instantiating burnchain db");
10✔
411

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

572
        self.leader_key_registers.insert(key_txid);
10✔
573
    }
10✔
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(
64✔
578
        &mut self,
64✔
579
        burnchain_tip: &BurnchainTip,
64✔
580
    ) -> (Option<BurnchainTip>, bool) {
64✔
581
        let mut new_key = None;
64✔
582
        let mut last_sortitioned_block = None;
64✔
583
        let mut won_sortition = false;
64✔
584
        let ops = &burnchain_tip.state_transition.accepted_ops;
64✔
585

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

614
        // Update the active key so we use the latest registered key.
615
        if new_key.is_some() {
64✔
616
            self.active_registered_key = new_key;
10✔
617
        }
54✔
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() {
64✔
622
            self.last_sortitioned_block = last_sortitioned_block;
44✔
623
        }
44✔
624

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

628
        (self.last_sortitioned_block.clone(), won_sortition)
64✔
629
    }
64✔
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> {
10✔
635
        // Set the `bootstraping_chain` flag, that will be unset once the
636
        // bootstraping tenure ran successfully (process_tenure).
637
        self.bootstraping_chain = true;
10✔
638

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

641
        self.initiate_new_tenure()
10✔
642
    }
10✔
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> {
54✔
648
        // Get the latest registered key
649
        let registered_key = match &self.active_registered_key {
54✔
650
            None => {
651
                // We're continuously registering new keys, as such, this branch
652
                // should be unreachable.
UNCOV
653
                unreachable!()
×
654
            }
655
            Some(ref key) => key,
54✔
656
        };
657

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

669
        // Generates a proof out of the sortition hash provided in the params.
670
        let Some(vrf_proof) = self.keychain.generate_proof(
54✔
671
            registered_key.target_block_height,
54✔
672
            tip.sortition_hash.as_bytes(),
54✔
673
        ) else {
54✔
UNCOV
674
            warn!("Failed to generate VRF proof, will be unable to initiate new tenure");
×
UNCOV
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);
54✔
681

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

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

700
        let mem_pool = MemPoolDB::open(
54✔
701
            self.config.is_mainnet(),
54✔
702
            self.config.burnchain.chain_id,
54✔
703
            &self.chain_state.root_path,
54✔
704
            estimator,
54✔
705
            metric,
54✔
706
        )
707
        .expect("FATAL: failed to open mempool");
54✔
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());
54✔
712

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

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

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

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

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

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

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

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

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

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

782
            self.block_commits.insert(txid);
44✔
783
        } else {
UNCOV
784
            warn!("No leader key active!");
×
785
        }
786
    }
44✔
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(
44✔
791
        &mut self,
44✔
792
        anchored_block: &StacksBlock,
44✔
793
        consensus_hash: &ConsensusHash,
44✔
794
        microblocks: Vec<StacksMicroblock>,
44✔
795
        db: &mut SortitionDB,
44✔
796
        atlas_db: &mut AtlasDB,
44✔
797
    ) -> ChainTip {
44✔
798
        let _parent_consensus_hash = {
44✔
799
            // look up parent consensus hash
800
            let ic = db.index_conn();
44✔
801
            let parent_consensus_hash = StacksChainState::get_parent_consensus_hash(
44✔
802
                &ic,
44✔
803
                &anchored_block.header.parent_block,
44✔
804
                consensus_hash,
44✔
805
            )
806
            .unwrap_or_else(|_| {
44✔
UNCOV
807
                panic!(
×
808
                    "BUG: could not query chainstate to find parent consensus hash of {consensus_hash}/{}",
UNCOV
809
                    &anchored_block.block_hash()
×
810
                )
811
            })
812
            .unwrap_or_else(|| {
44✔
UNCOV
813
                panic!(
×
814
                    "BUG: no such parent of block {consensus_hash}/{}",
UNCOV
815
                    &anchored_block.block_hash()
×
816
                )
817
            });
818

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

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

848
            parent_consensus_hash
44✔
849
        };
850

851
        let atlas_config = Self::make_atlas_config();
44✔
852
        let mut processed_blocks = vec![];
44✔
853
        loop {
854
            let mut process_blocks_at_tip = {
88✔
855
                let tx = db.tx_begin_at_tip();
88✔
856
                self.chain_state
88✔
857
                    .process_blocks(tx, 1, Some(&self.event_dispatcher))
88✔
858
            };
859
            match process_blocks_at_tip {
88✔
UNCOV
860
                Err(e) => panic!("Error while processing block - {e:?}"),
×
861
                Ok(ref mut blocks) => {
88✔
862
                    if blocks.is_empty() {
88✔
863
                        break;
44✔
864
                    } else {
865
                        for block in blocks.iter() {
44✔
866
                            if let (Some(epoch_receipt), _) = block {
44✔
867
                                let attachments_instances =
44✔
868
                                    self.get_attachment_instances(epoch_receipt, &atlas_config);
44✔
869
                                if !attachments_instances.is_empty() {
44✔
UNCOV
870
                                    for new_attachment in attachments_instances.into_iter() {
×
UNCOV
871
                                        if let Err(e) =
×
UNCOV
872
                                            atlas_db.queue_attachment_instance(&new_attachment)
×
873
                                        {
UNCOV
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
                                            );
UNCOV
881
                                        }
×
882
                                    }
883
                                }
44✔
UNCOV
884
                            }
×
885
                        }
886

887
                        processed_blocks.append(blocks);
44✔
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();
44✔
896

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

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

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

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

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

941
        // Unset the `bootstraping_chain` flag.
942
        if self.bootstraping_chain {
44✔
943
            self.bootstraping_chain = false;
10✔
944
        }
34✔
945

946
        chain_tip
44✔
947
    }
44✔
948

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

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

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

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

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

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

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

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

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

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

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

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

1090
        tx_signer.get_tx().unwrap()
54✔
1091
    }
54✔
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