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

stacks-network / stacks-core / 25404138305-1

05 May 2026 09:47PM UTC coverage: 85.69% (-0.02%) from 85.712%
25404138305-1

Pull #7169

github

497ffd
web-flow
Merge 35db1183d into 53ffba0ab
Pull Request #7169: Feat: add defensive memory allocation for miners/signers

134 of 139 new or added lines in 11 files covered. (96.4%)

4591 existing lines in 96 files now uncovered.

187733 of 219085 relevant lines covered (85.69%)

18687545.45 hits per line

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

87.33
/stacks-node/src/node.rs
1
// Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation
2
// Copyright (C) 2020-2026 Stacks Open Internet Foundation
3
//
4
// This program is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// This program is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
16

17
use std::collections::{HashMap, HashSet};
18
use std::net::SocketAddr;
19
use std::thread::JoinHandle;
20
use std::{env, thread, time};
21

22
use rand::RngCore;
23
use stacks::burnchains::bitcoin::BitcoinNetworkType;
24
use stacks::burnchains::db::BurnchainDB;
25
use stacks::burnchains::{PoxConstants, Txid};
26
use stacks::chainstate::burn::db::sortdb::SortitionDB;
27
use stacks::chainstate::burn::operations::leader_block_commit::{
28
    RewardSetInfo, BURN_BLOCK_MINED_AT_MODULUS,
29
};
30
use stacks::chainstate::burn::operations::{
31
    BlockstackOperationType, LeaderBlockCommitOp, LeaderKeyRegisterOp,
32
};
33
use stacks::chainstate::burn::ConsensusHash;
34
use stacks::chainstate::stacks::address::PoxAddress;
35
use stacks::chainstate::stacks::db::{
36
    ChainStateBootData, ChainstateAccountBalance, ChainstateAccountLockup, ChainstateBNSName,
37
    ChainstateBNSNamespace, ClarityTx, StacksChainState, StacksEpochReceipt, StacksHeaderInfo,
38
};
39
use stacks::chainstate::stacks::events::{
40
    StacksTransactionEvent, StacksTransactionReceipt, TransactionOrigin,
41
};
42
use stacks::chainstate::stacks::{
43
    CoinbasePayload, StacksBlock, StacksMicroblock, StacksTransaction, StacksTransactionSigner,
44
    TransactionAnchorMode, TransactionPayload, TransactionVersion,
45
};
46
use stacks::core::mempool::MemPoolDB;
47
use stacks::core::{EpochList, STACKS_EPOCH_2_1_MARKER};
48
use stacks::cost_estimates::metrics::UnitMetric;
49
use stacks::cost_estimates::UnitEstimator;
50
use stacks::net::atlas::{AtlasConfig, AtlasDB, AttachmentInstance};
51
use stacks::net::db::PeerDB;
52
use stacks::net::p2p::PeerNetwork;
53
use stacks::net::stackerdb::StackerDBs;
54
use stacks::net::RPCHandlerArgs;
55
use stacks::util_lib::strings::UrlString;
56
use stacks_common::types::chainstate::{BlockHeaderHash, BurnchainHeaderHash, TrieHash, VRFSeed};
57
use stacks_common::types::net::PeerAddress;
58
use stacks_common::util::get_epoch_time_secs;
59
use stacks_common::util::hash::Sha256Sum;
60
use stacks_common::util::secp256k1::Secp256k1PrivateKey;
61
use stacks_common::util::vrf::VRFPublicKey;
62

63
use super::{BurnchainController, BurnchainTip, Config, EventDispatcher, Keychain, Tenure};
64
use crate::burnchains::make_bitcoin_indexer;
65
use crate::genesis_data::USE_TEST_GENESIS_CHAINSTATE;
66
use crate::run_loop;
67
use crate::run_loop::RegisteredKey;
68

69
#[derive(Debug, Clone)]
70
pub struct ChainTip {
71
    pub metadata: StacksHeaderInfo,
72
    pub block: StacksBlock,
73
    pub receipts: Vec<StacksTransactionReceipt>,
74
}
75

76
impl ChainTip {
77
    pub fn genesis(
438✔
78
        first_burnchain_block_hash: &BurnchainHeaderHash,
438✔
79
        first_burnchain_block_height: u64,
438✔
80
        first_burnchain_block_timestamp: u64,
438✔
81
    ) -> ChainTip {
438✔
82
        ChainTip {
438✔
83
            metadata: StacksHeaderInfo::genesis(
438✔
84
                TrieHash([0u8; 32]),
438✔
85
                first_burnchain_block_hash,
438✔
86
                first_burnchain_block_height as u32,
438✔
87
                first_burnchain_block_timestamp,
438✔
88
            ),
438✔
89
            block: StacksBlock::genesis_block(),
438✔
90
            receipts: vec![],
438✔
91
        }
438✔
92
    }
438✔
93
}
94

95
/// Node is a structure modelising an active node working on the stacks chain.
96
pub struct Node {
97
    pub chain_state: StacksChainState,
98
    pub config: Config,
99
    active_registered_key: Option<RegisteredKey>,
100
    bootstraping_chain: bool,
101
    pub burnchain_tip: Option<BurnchainTip>,
102
    pub chain_tip: Option<ChainTip>,
103
    keychain: Keychain,
104
    last_sortitioned_block: Option<BurnchainTip>,
105
    event_dispatcher: EventDispatcher,
106
    nonce: u64,
107
    leader_key_registers: HashSet<Txid>,
108
    block_commits: HashSet<Txid>,
109
}
110

111
pub fn get_account_lockups(
290✔
112
    use_test_chainstate_data: bool,
290✔
113
) -> Box<dyn Iterator<Item = ChainstateAccountLockup>> {
290✔
114
    Box::new(
290✔
115
        stx_genesis::GenesisData::new(use_test_chainstate_data)
290✔
116
            .read_lockups()
290✔
117
            .map(|item| ChainstateAccountLockup {
290✔
118
                address: item.address,
5,800✔
119
                amount: item.amount,
5,800✔
120
                block_height: item.block_height,
5,800✔
121
            }),
5,800✔
122
    )
123
}
290✔
124

125
pub fn get_account_balances(
290✔
126
    use_test_chainstate_data: bool,
290✔
127
) -> Box<dyn Iterator<Item = ChainstateAccountBalance>> {
290✔
128
    Box::new(
290✔
129
        stx_genesis::GenesisData::new(use_test_chainstate_data)
290✔
130
            .read_balances()
290✔
131
            .map(|item| ChainstateAccountBalance {
290✔
132
                address: item.address,
6,960✔
133
                amount: item.amount,
6,960✔
134
            }),
6,960✔
135
    )
136
}
290✔
137

138
pub fn get_namespaces(
290✔
139
    use_test_chainstate_data: bool,
290✔
140
) -> Box<dyn Iterator<Item = ChainstateBNSNamespace>> {
290✔
141
    Box::new(
290✔
142
        stx_genesis::GenesisData::new(use_test_chainstate_data)
290✔
143
            .read_namespaces()
290✔
144
            .map(|item| ChainstateBNSNamespace {
290✔
145
                namespace_id: item.namespace_id,
1,450✔
146
                importer: item.importer,
1,450✔
147
                buckets: item.buckets,
1,450✔
148
                base: item.base as u64,
1,450✔
149
                coeff: item.coeff as u64,
1,450✔
150
                nonalpha_discount: item.nonalpha_discount as u64,
1,450✔
151
                no_vowel_discount: item.no_vowel_discount as u64,
1,450✔
152
                lifetime: item.lifetime as u64,
1,450✔
153
            }),
1,450✔
154
    )
155
}
290✔
156

157
pub fn get_names(use_test_chainstate_data: bool) -> Box<dyn Iterator<Item = ChainstateBNSName>> {
290✔
158
    Box::new(
290✔
159
        stx_genesis::GenesisData::new(use_test_chainstate_data)
290✔
160
            .read_names()
290✔
161
            .map(|item| ChainstateBNSName {
290✔
162
                fully_qualified_name: item.fully_qualified_name,
3,480✔
163
                owner: item.owner,
3,480✔
164
                zonefile_hash: item.zonefile_hash,
3,480✔
165
            }),
3,480✔
166
    )
167
}
290✔
168

169
// This function is called for helium and mocknet.
170
#[allow(clippy::too_many_arguments)]
171
fn spawn_peer(
10✔
172
    is_mainnet: bool,
10✔
173
    chain_id: u32,
10✔
174
    mut this: PeerNetwork,
10✔
175
    p2p_sock: &SocketAddr,
10✔
176
    rpc_sock: &SocketAddr,
10✔
177
    burn_db_path: String,
10✔
178
    stacks_chainstate_path: String,
10✔
179
    pox_consts: PoxConstants,
10✔
180
    event_dispatcher: EventDispatcher,
10✔
181
    exit_at_block_height: Option<u64>,
10✔
182
    genesis_chainstate_hash: Sha256Sum,
10✔
183
    poll_timeout: u64,
10✔
184
    config: Config,
10✔
185
) -> JoinHandle<()> {
10✔
186
    this.bind(p2p_sock, rpc_sock).unwrap();
10✔
187
    let server_thread = thread::spawn(move || {
10✔
188
        // create estimators, metric instances for RPC handler
189
        let cost_estimator = config
10✔
190
            .make_cost_estimator()
10✔
191
            .unwrap_or_else(|| Box::new(UnitEstimator));
10✔
192
        let metric = config
10✔
193
            .make_cost_metric()
10✔
194
            .unwrap_or_else(|| Box::new(UnitMetric));
10✔
195
        let fee_estimator = config.make_fee_estimator();
10✔
196

197
        let handler_args = RPCHandlerArgs {
10✔
198
            exit_at_block_height,
10✔
199
            cost_estimator: Some(cost_estimator.as_ref()),
10✔
200
            cost_metric: Some(metric.as_ref()),
10✔
201
            fee_estimator: fee_estimator.as_ref().map(|x| x.as_ref()),
10✔
202
            genesis_chainstate_hash,
10✔
203
            ..RPCHandlerArgs::default()
10✔
204
        };
205

206
        loop {
207
            let sortdb = match SortitionDB::open(
250✔
208
                &burn_db_path,
250✔
209
                false,
250✔
210
                pox_consts.clone(),
250✔
211
                Some(config.node.get_marf_opts()),
250✔
212
            ) {
250✔
213
                Ok(x) => x,
250✔
214
                Err(e) => {
×
UNCOV
215
                    warn!("Error while connecting burnchain db in peer loop: {e}");
×
UNCOV
216
                    thread::sleep(time::Duration::from_secs(1));
×
UNCOV
217
                    continue;
×
218
                }
219
            };
220
            let (mut chainstate, _) = match StacksChainState::open(
250✔
221
                is_mainnet,
250✔
222
                chain_id,
250✔
223
                &stacks_chainstate_path,
250✔
224
                Some(config.node.get_marf_opts()),
250✔
225
            ) {
250✔
226
                Ok(x) => x,
250✔
UNCOV
227
                Err(e) => {
×
UNCOV
228
                    warn!("Error while connecting chainstate db in peer loop: {e}");
×
229
                    thread::sleep(time::Duration::from_secs(1));
×
230
                    continue;
×
231
                }
232
            };
233

234
            let estimator = Box::new(UnitEstimator);
250✔
235
            let metric = Box::new(UnitMetric);
250✔
236

237
            let mut mem_pool = match MemPoolDB::open(
250✔
238
                is_mainnet,
250✔
239
                chain_id,
250✔
240
                &stacks_chainstate_path,
250✔
241
                estimator,
250✔
242
                metric,
250✔
243
            ) {
250✔
244
                Ok(x) => x,
250✔
UNCOV
245
                Err(e) => {
×
UNCOV
246
                    warn!("Error while connecting to mempool db in peer loop: {e}");
×
UNCOV
247
                    thread::sleep(time::Duration::from_secs(1));
×
UNCOV
248
                    continue;
×
249
                }
250
            };
251

252
            let indexer = make_bitcoin_indexer(&config, None);
250✔
253

254
            let net_result = this
250✔
255
                .run(
250✔
256
                    &indexer,
250✔
257
                    &sortdb,
250✔
258
                    &mut chainstate,
250✔
259
                    &mut mem_pool,
250✔
260
                    None,
250✔
261
                    false,
262
                    false,
263
                    poll_timeout,
250✔
264
                    &handler_args,
250✔
265
                    config.node.txindex,
250✔
266
                )
267
                .unwrap();
250✔
268
            if net_result.has_transactions() {
250✔
269
                event_dispatcher.process_new_mempool_txs(net_result.transactions())
1✔
270
            }
239✔
271
            // Dispatch retrieved attachments, if any.
272
            if net_result.has_attachments() {
240✔
UNCOV
273
                event_dispatcher.process_new_attachments(&net_result.attachments);
×
274
            }
240✔
275
        }
276
    });
277
    server_thread
10✔
278
}
10✔
279

280
// Check if the small test genesis chainstate data should be used.
281
// First check env var, then config file, then use default.
282
pub fn use_test_genesis_chainstate(config: &Config) -> bool {
1,051✔
283
    if env::var("BLOCKSTACK_USE_TEST_GENESIS_CHAINSTATE") == Ok("1".to_string()) {
1,051✔
UNCOV
284
        true
×
285
    } else if let Some(use_test_genesis_chainstate) = config.node.use_test_genesis_chainstate {
1,051✔
UNCOV
286
        use_test_genesis_chainstate
×
287
    } else {
288
        USE_TEST_GENESIS_CHAINSTATE
1,051✔
289
    }
290
}
1,051✔
291

292
impl Node {
293
    /// Instantiate and initialize a new node, given a config
294
    pub fn new(config: Config, boot_block_exec: Box<dyn FnOnce(&mut ClarityTx)>) -> Self {
10✔
295
        let use_test_genesis_data = if config.burnchain.mode == "mocknet" {
10✔
296
            use_test_genesis_chainstate(&config)
10✔
297
        } else {
UNCOV
298
            USE_TEST_GENESIS_CHAINSTATE
×
299
        };
300

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

303
        let initial_balances = config
10✔
304
            .initial_balances
10✔
305
            .iter()
10✔
306
            .map(|e| (e.address.clone(), e.amount))
529✔
307
            .collect();
10✔
308
        let pox_constants = match config.burnchain.get_bitcoin_network() {
10✔
UNCOV
309
            (_, BitcoinNetworkType::Mainnet) => PoxConstants::mainnet_default(),
×
UNCOV
310
            (_, BitcoinNetworkType::Testnet) => PoxConstants::testnet_default(),
×
311
            (_, BitcoinNetworkType::Regtest) => PoxConstants::regtest_default(),
10✔
312
        };
313

314
        let mut boot_data = ChainStateBootData {
10✔
315
            initial_balances,
10✔
316
            first_burnchain_block_hash: BurnchainHeaderHash::zero(),
10✔
317
            first_burnchain_block_height: 0,
318
            first_burnchain_block_timestamp: 0,
319
            pox_constants,
10✔
320
            post_flight_callback: Some(boot_block_exec),
10✔
321
            get_bulk_initial_lockups: Some(Box::new(move || {
10✔
322
                get_account_lockups(use_test_genesis_data)
10✔
323
            })),
10✔
324
            get_bulk_initial_balances: Some(Box::new(move || {
10✔
325
                get_account_balances(use_test_genesis_data)
10✔
326
            })),
10✔
327
            get_bulk_initial_namespaces: Some(Box::new(move || {
10✔
328
                get_namespaces(use_test_genesis_data)
10✔
329
            })),
10✔
330
            get_bulk_initial_names: Some(Box::new(move || get_names(use_test_genesis_data))),
10✔
331
        };
332

333
        let chain_state_result = StacksChainState::open_and_exec(
10✔
334
            config.is_mainnet(),
10✔
335
            config.burnchain.chain_id,
10✔
336
            &config.get_chainstate_path_str(),
10✔
337
            Some(&mut boot_data),
10✔
338
            Some(config.node.get_marf_opts()),
10✔
339
        );
340

341
        let (chain_state, receipts) = match chain_state_result {
10✔
342
            Ok(res) => res,
10✔
UNCOV
343
            Err(err) => panic!(
×
344
                "Error while opening chain state at path {}: {err:?}",
UNCOV
345
                config.get_chainstate_path_str()
×
346
            ),
347
        };
348

349
        let estimator = Box::new(UnitEstimator);
10✔
350
        let metric = Box::new(UnitMetric);
10✔
351

352
        // avoid race to create condition on mempool db
353
        let _mem_pool = MemPoolDB::open(
10✔
354
            config.is_mainnet(),
10✔
355
            config.burnchain.chain_id,
10✔
356
            &chain_state.root_path,
10✔
357
            estimator,
10✔
358
            metric,
10✔
359
        )
360
        .expect("FATAL: failed to initiate mempool");
10✔
361

362
        let mut event_dispatcher = EventDispatcher::new_with_custom_queue_size(
10✔
363
            config.get_working_dir(),
10✔
364
            config.node.effective_event_dispatcher_queue_size(),
10✔
365
        );
366

367
        for observer in &config.events_observers {
10✔
UNCOV
368
            event_dispatcher.register_observer(observer);
×
UNCOV
369
        }
×
370

371
        let burnchain_config = config.get_burnchain();
10✔
372

373
        // instantiate DBs
374
        let _burnchain_db = BurnchainDB::connect(
10✔
375
            &burnchain_config.get_burnchaindb_path(),
10✔
376
            &burnchain_config,
10✔
377
            true,
378
        )
379
        .expect("FATAL: failed to connect to burnchain DB");
10✔
380

381
        run_loop::announce_boot_receipts(
10✔
382
            &mut event_dispatcher,
10✔
383
            &chain_state,
10✔
384
            &burnchain_config.pox_constants,
10✔
385
            &receipts,
10✔
386
        );
387

388
        Self {
10✔
389
            active_registered_key: None,
10✔
390
            bootstraping_chain: false,
10✔
391
            chain_state,
10✔
392
            chain_tip: None,
10✔
393
            keychain,
10✔
394
            last_sortitioned_block: None,
10✔
395
            config,
10✔
396
            burnchain_tip: None,
10✔
397
            nonce: 0,
10✔
398
            event_dispatcher,
10✔
399
            leader_key_registers: HashSet::new(),
10✔
400
            block_commits: HashSet::new(),
10✔
401
        }
10✔
402
    }
10✔
403

404
    fn make_atlas_config() -> AtlasConfig {
98✔
405
        AtlasConfig::new(false)
98✔
406
    }
98✔
407

408
    pub fn make_atlas_db(&self) -> AtlasDB {
54✔
409
        AtlasDB::connect(
54✔
410
            Self::make_atlas_config(),
54✔
411
            &self.config.get_atlas_db_file_path(),
54✔
412
            true,
413
        )
414
        .unwrap()
54✔
415
    }
54✔
416

417
    // This function is used for helium and mocknet.
418
    pub fn spawn_peer_server(&mut self) {
10✔
419
        // we can call _open_ here rather than _connect_, since connect is first called in
420
        //   make_genesis_block
421
        let burnchain = self.config.get_burnchain();
10✔
422
        let sortdb = SortitionDB::open(
10✔
423
            &self.config.get_burn_db_file_path(),
10✔
424
            true,
425
            burnchain.pox_constants.clone(),
10✔
426
            Some(self.config.node.get_marf_opts()),
10✔
427
        )
428
        .expect("Error while instantiating burnchain db");
10✔
429

430
        let epochs_vec = SortitionDB::get_stacks_epochs(sortdb.conn())
10✔
431
            .expect("Error while loading stacks epochs");
10✔
432
        let epochs = EpochList::new(&epochs_vec);
10✔
433

434
        Config::assert_valid_epoch_settings(&burnchain, &epochs);
10✔
435

436
        let view = {
10✔
437
            let sortition_tip = SortitionDB::get_canonical_burn_chain_tip(sortdb.conn())
10✔
438
                .expect("Failed to get sortition tip");
10✔
439
            SortitionDB::get_burnchain_view(&sortdb.index_conn(), &burnchain, &sortition_tip)
10✔
440
                .unwrap()
10✔
441
        };
442

443
        // create a new peerdb
444
        let data_url = UrlString::try_from(self.config.node.data_url.to_string()).unwrap();
10✔
445

446
        let initial_neighbors = self.config.node.bootstrap_node.clone();
10✔
447

448
        println!("BOOTSTRAP WITH {initial_neighbors:?}");
10✔
449

450
        let rpc_sock: SocketAddr =
10✔
451
            self.config.node.rpc_bind.parse().unwrap_or_else(|_| {
10✔
UNCOV
452
                panic!("Failed to parse socket: {}", &self.config.node.rpc_bind)
×
453
            });
454
        let p2p_sock: SocketAddr =
10✔
455
            self.config.node.p2p_bind.parse().unwrap_or_else(|_| {
10✔
UNCOV
456
                panic!("Failed to parse socket: {}", &self.config.node.p2p_bind)
×
457
            });
458
        let p2p_addr: SocketAddr = self.config.node.p2p_address.parse().unwrap_or_else(|_| {
10✔
UNCOV
459
            panic!("Failed to parse socket: {}", &self.config.node.p2p_address)
×
460
        });
461
        let node_privkey = {
10✔
462
            let mut re_hashed_seed = self.config.node.local_peer_seed.clone();
10✔
463
            let my_private_key = loop {
10✔
464
                match Secp256k1PrivateKey::from_slice(&re_hashed_seed[..]) {
10✔
465
                    Ok(sk) => break sk,
10✔
466
                    Err(_) => {
UNCOV
467
                        re_hashed_seed = Sha256Sum::from_data(&re_hashed_seed[..])
×
UNCOV
468
                            .as_bytes()
×
UNCOV
469
                            .to_vec()
×
470
                    }
471
                }
472
            };
473
            my_private_key
10✔
474
        };
475

476
        let mut peerdb = PeerDB::connect(
10✔
477
            &self.config.get_peer_db_file_path(),
10✔
478
            true,
479
            self.config.burnchain.chain_id,
10✔
480
            burnchain.network_id,
10✔
481
            Some(node_privkey),
10✔
482
            self.config.connection_options.private_key_lifetime,
10✔
483
            PeerAddress::from_socketaddr(&p2p_addr),
10✔
484
            p2p_sock.port(),
10✔
485
            data_url,
10✔
486
            &[],
10✔
487
            Some(&initial_neighbors),
10✔
488
            &[],
10✔
489
        )
490
        .unwrap();
10✔
491

492
        println!("DENY NEIGHBORS {:?}", &self.config.node.deny_nodes);
10✔
493
        {
494
            let tx = peerdb.tx_begin().unwrap();
10✔
495
            for denied in self.config.node.deny_nodes.iter() {
10✔
496
                PeerDB::set_deny_peer(
×
UNCOV
497
                    &tx,
×
UNCOV
498
                    denied.addr.network_id,
×
UNCOV
499
                    &denied.addr.addrbytes,
×
UNCOV
500
                    denied.addr.port,
×
UNCOV
501
                    get_epoch_time_secs() + 24 * 365 * 3600,
×
UNCOV
502
                )
×
UNCOV
503
                .unwrap();
×
UNCOV
504
            }
×
505
            tx.commit().unwrap();
10✔
506
        }
507
        let atlasdb = self.make_atlas_db();
10✔
508

509
        let stackerdbs =
10✔
510
            StackerDBs::connect(&self.config.get_stacker_db_file_path(), true).unwrap();
10✔
511

512
        let local_peer = match PeerDB::get_local_peer(peerdb.conn()) {
10✔
513
            Ok(local_peer) => local_peer,
10✔
UNCOV
514
            _ => panic!("Unable to retrieve local peer"),
×
515
        };
516

517
        let event_dispatcher = self.event_dispatcher.clone();
10✔
518
        let exit_at_block_height = self.config.burnchain.process_exit_at_block_height;
10✔
519
        let burnchain_db = burnchain
10✔
520
            .open_burnchain_db(false)
10✔
521
            .expect("Failed to open burnchain DB");
10✔
522

523
        let p2p_net = PeerNetwork::new(
10✔
524
            peerdb,
10✔
525
            atlasdb,
10✔
526
            stackerdbs,
10✔
527
            burnchain_db,
10✔
528
            local_peer,
10✔
529
            self.config.burnchain.peer_version,
10✔
530
            burnchain.clone(),
10✔
531
            view,
10✔
532
            self.config.connection_options.clone(),
10✔
533
            HashMap::new(),
10✔
534
            epochs,
10✔
535
        );
536
        let _join_handle = spawn_peer(
10✔
537
            self.config.is_mainnet(),
10✔
538
            self.config.burnchain.chain_id,
10✔
539
            p2p_net,
10✔
540
            &p2p_sock,
10✔
541
            &rpc_sock,
10✔
542
            self.config.get_burn_db_file_path(),
10✔
543
            self.config.get_chainstate_path_str(),
10✔
544
            burnchain.pox_constants,
10✔
545
            event_dispatcher,
10✔
546
            exit_at_block_height,
10✔
547
            Sha256Sum::from_hex(stx_genesis::GENESIS_CHAINSTATE_HASH).unwrap(),
10✔
548
            1000,
549
            self.config.clone(),
10✔
550
        );
551

552
        info!("Start HTTP server on: {}", &self.config.node.rpc_bind);
10✔
553
        info!("Start P2P server on: {}", &self.config.node.p2p_bind);
10✔
554
    }
10✔
555

556
    pub fn setup(&mut self, burnchain_controller: &mut Box<dyn BurnchainController>) {
10✔
557
        // Register a new key
558
        let burnchain_tip = burnchain_controller.get_chain_tip();
10✔
559
        let (vrf_pk, _) = self
10✔
560
            .keychain
10✔
561
            .make_vrf_keypair(burnchain_tip.block_snapshot.block_height);
10✔
562
        let consensus_hash = burnchain_tip.block_snapshot.consensus_hash;
10✔
563

564
        let burnchain = self.config.get_burnchain();
10✔
565

566
        let sortdb = SortitionDB::open(
10✔
567
            &self.config.get_burn_db_file_path(),
10✔
568
            true,
569
            burnchain.pox_constants.clone(),
10✔
570
            Some(self.config.node.get_marf_opts()),
10✔
571
        )
572
        .expect("Error while opening sortition db");
10✔
573

574
        let epochs = SortitionDB::get_stacks_epochs(sortdb.conn())
10✔
575
            .expect("FATAL: failed to read sortition DB");
10✔
576

577
        Config::assert_valid_epoch_settings(&burnchain, &epochs);
10✔
578

579
        let cur_epoch =
10✔
580
            SortitionDB::get_stacks_epoch(sortdb.conn(), burnchain_tip.block_snapshot.block_height)
10✔
581
                .expect("FATAL: failed to read sortition DB")
10✔
582
                .expect("FATAL: no epoch defined");
10✔
583

584
        let key_reg_op = self.generate_leader_key_register_op(vrf_pk, consensus_hash);
10✔
585
        let mut op_signer = self.keychain.generate_op_signer();
10✔
586
        let key_txid = burnchain_controller
10✔
587
            .submit_operation(cur_epoch.epoch_id, key_reg_op, &mut op_signer)
10✔
588
            .expect("FATAL: failed to submit leader key register operation");
10✔
589

590
        self.leader_key_registers.insert(key_txid);
10✔
591
    }
10✔
592

593
    /// Process an state coming from the burnchain, by extracting the validated KeyRegisterOp
594
    /// and inspecting if a sortition was won.
595
    pub fn process_burnchain_state(
64✔
596
        &mut self,
64✔
597
        burnchain_tip: &BurnchainTip,
64✔
598
    ) -> (Option<BurnchainTip>, bool) {
64✔
599
        let mut new_key = None;
64✔
600
        let mut last_sortitioned_block = None;
64✔
601
        let mut won_sortition = false;
64✔
602
        let ops = &burnchain_tip.state_transition.accepted_ops;
64✔
603

604
        for op in ops.iter() {
64✔
605
            match op {
54✔
606
                BlockstackOperationType::LeaderKeyRegister(ref op) => {
10✔
607
                    if self.leader_key_registers.contains(&op.txid) {
10✔
608
                        // Registered key has been mined
10✔
609
                        new_key = Some(RegisteredKey {
10✔
610
                            vrf_public_key: op.public_key.clone(),
10✔
611
                            block_height: op.block_height,
10✔
612
                            op_vtxindex: op.vtxindex,
10✔
613
                            target_block_height: op.block_height - 1,
10✔
614
                            memo: op.memo.clone(),
10✔
615
                        });
10✔
616
                    }
10✔
617
                }
618
                BlockstackOperationType::LeaderBlockCommit(ref op) => {
44✔
619
                    if op.txid == burnchain_tip.block_snapshot.winning_block_txid {
44✔
620
                        last_sortitioned_block = Some(burnchain_tip.clone());
44✔
621
                        if self.block_commits.contains(&op.txid) {
44✔
622
                            won_sortition = true;
44✔
623
                        }
44✔
UNCOV
624
                    }
×
625
                }
UNCOV
626
                _ => {
×
UNCOV
627
                    // no-op, ops are not supported / produced at this point.
×
UNCOV
628
                }
×
629
            }
630
        }
631

632
        // Update the active key so we use the latest registered key.
633
        if new_key.is_some() {
64✔
634
            self.active_registered_key = new_key;
10✔
635
        }
54✔
636

637
        // Update last_sortitioned_block so we keep a reference to the latest
638
        // block including a sortition.
639
        if last_sortitioned_block.is_some() {
64✔
640
            self.last_sortitioned_block = last_sortitioned_block;
44✔
641
        }
44✔
642

643
        // Keep a pointer of the burnchain's chain tip.
644
        self.burnchain_tip = Some(burnchain_tip.clone());
64✔
645

646
        (self.last_sortitioned_block.clone(), won_sortition)
64✔
647
    }
64✔
648

649
    /// Prepares the node to run a tenure consisting in bootstraping the chain.
650
    ///
651
    /// Will internally call initiate_new_tenure().
652
    pub fn initiate_genesis_tenure(&mut self, burnchain_tip: &BurnchainTip) -> Option<Tenure> {
10✔
653
        // Set the `bootstraping_chain` flag, that will be unset once the
654
        // bootstraping tenure ran successfully (process_tenure).
655
        self.bootstraping_chain = true;
10✔
656

657
        self.last_sortitioned_block = Some(burnchain_tip.clone());
10✔
658

659
        self.initiate_new_tenure()
10✔
660
    }
10✔
661

662
    /// Constructs and returns an instance of Tenure, that can be run
663
    /// on an isolated thread and discarded or canceled without corrupting the
664
    /// chain state of the node.
665
    pub fn initiate_new_tenure(&mut self) -> Option<Tenure> {
54✔
666
        // Get the latest registered key
667
        let registered_key = match &self.active_registered_key {
54✔
668
            None => {
669
                // We're continuously registering new keys, as such, this branch
670
                // should be unreachable.
UNCOV
671
                unreachable!()
×
672
            }
673
            Some(ref key) => key,
54✔
674
        };
675

676
        let burnchain = self.config.get_burnchain();
54✔
677
        let sortdb = SortitionDB::open(
54✔
678
            &self.config.get_burn_db_file_path(),
54✔
679
            true,
680
            burnchain.pox_constants,
54✔
681
            Some(self.config.node.get_marf_opts()),
54✔
682
        )
683
        .expect("Error while opening sortition db");
54✔
684
        let tip = SortitionDB::get_canonical_burn_chain_tip(sortdb.conn())
54✔
685
            .expect("FATAL: failed to query canonical burn chain tip");
54✔
686

687
        // Generates a proof out of the sortition hash provided in the params.
688
        let Some(vrf_proof) = self.keychain.generate_proof(
54✔
689
            registered_key.target_block_height,
54✔
690
            tip.sortition_hash.as_bytes(),
54✔
691
        ) else {
54✔
UNCOV
692
            warn!("Failed to generate VRF proof, will be unable to initiate new tenure");
×
UNCOV
693
            return None;
×
694
        };
695

696
        // Generates a new secret key for signing the trail of microblocks
697
        // of the upcoming tenure.
698
        let microblock_secret_key = self.keychain.get_microblock_key(tip.block_height);
54✔
699

700
        // Get the stack's chain tip
701
        let chain_tip = match self.bootstraping_chain {
54✔
702
            true => ChainTip::genesis(&BurnchainHeaderHash::zero(), 0, 0),
10✔
703
            false => match &self.chain_tip {
44✔
704
                Some(chain_tip) => chain_tip.clone(),
44✔
UNCOV
705
                None => unreachable!(),
×
706
            },
707
        };
708

709
        let estimator = self
54✔
710
            .config
54✔
711
            .make_cost_estimator()
54✔
712
            .unwrap_or_else(|| Box::new(UnitEstimator));
54✔
713
        let metric = self
54✔
714
            .config
54✔
715
            .make_cost_metric()
54✔
716
            .unwrap_or_else(|| Box::new(UnitMetric));
54✔
717

718
        let mem_pool = MemPoolDB::open(
54✔
719
            self.config.is_mainnet(),
54✔
720
            self.config.burnchain.chain_id,
54✔
721
            &self.chain_state.root_path,
54✔
722
            estimator,
54✔
723
            metric,
54✔
724
        )
725
        .expect("FATAL: failed to open mempool");
54✔
726

727
        // Construct the coinbase transaction - 1st txn that should be handled and included in
728
        // the upcoming tenure.
729
        let coinbase_tx = self.generate_coinbase_tx(self.config.is_mainnet());
54✔
730

731
        let burn_fee_cap = self.config.burnchain.burn_fee_cap;
54✔
732

733
        let block_to_build_upon = match &self.last_sortitioned_block {
54✔
UNCOV
734
            None => unreachable!(),
×
735
            Some(block) => block.clone(),
54✔
736
        };
737

738
        // Construct the upcoming tenure
739
        let tenure = Tenure::new(
54✔
740
            chain_tip,
54✔
741
            coinbase_tx,
54✔
742
            self.config.clone(),
54✔
743
            mem_pool,
54✔
744
            microblock_secret_key,
54✔
745
            block_to_build_upon,
54✔
746
            vrf_proof,
54✔
747
            burn_fee_cap,
54✔
748
        );
749

750
        Some(tenure)
54✔
751
    }
54✔
752

753
    pub fn commit_artifacts(
44✔
754
        &mut self,
44✔
755
        anchored_block_from_ongoing_tenure: &StacksBlock,
44✔
756
        burnchain_tip: &BurnchainTip,
44✔
757
        burnchain_controller: &mut Box<dyn BurnchainController>,
44✔
758
        burn_fee: u64,
44✔
759
    ) {
44✔
760
        if self.active_registered_key.is_some() {
44✔
761
            let registered_key = self.active_registered_key.clone().unwrap();
44✔
762

763
            let Some(vrf_proof) = self.keychain.generate_proof(
44✔
764
                registered_key.target_block_height,
44✔
765
                burnchain_tip.block_snapshot.sortition_hash.as_bytes(),
44✔
766
            ) else {
44✔
UNCOV
767
                warn!("Failed to generate VRF proof, will be unable to mine commits");
×
UNCOV
768
                return;
×
769
            };
770

771
            let op = self.generate_block_commit_op(
44✔
772
                anchored_block_from_ongoing_tenure.header.block_hash(),
44✔
773
                burn_fee,
44✔
774
                &registered_key,
44✔
775
                burnchain_tip,
44✔
776
                VRFSeed::from_proof(&vrf_proof),
44✔
777
            );
778

779
            let burnchain = self.config.get_burnchain();
44✔
780
            let sortdb = SortitionDB::open(
44✔
781
                &self.config.get_burn_db_file_path(),
44✔
782
                true,
783
                burnchain.pox_constants,
44✔
784
                Some(self.config.node.get_marf_opts()),
44✔
785
            )
786
            .expect("Error while opening sortition db");
44✔
787

788
            let cur_epoch = SortitionDB::get_stacks_epoch(
44✔
789
                sortdb.conn(),
44✔
790
                burnchain_tip.block_snapshot.block_height,
44✔
791
            )
792
            .expect("FATAL: failed to read sortition DB")
44✔
793
            .expect("FATAL: no epoch defined");
44✔
794

795
            let mut op_signer = self.keychain.generate_op_signer();
44✔
796
            let txid = burnchain_controller
44✔
797
                .submit_operation(cur_epoch.epoch_id, op, &mut op_signer)
44✔
798
                .expect("FATAL: failed to submit block-commit");
44✔
799

800
            self.block_commits.insert(txid);
44✔
801
        } else {
UNCOV
802
            warn!("No leader key active!");
×
803
        }
804
    }
44✔
805

806
    /// Process artifacts from the tenure.
807
    /// At this point, we're modifying the chainstate, and merging the artifacts from the previous tenure.
808
    pub fn process_tenure(
44✔
809
        &mut self,
44✔
810
        anchored_block: &StacksBlock,
44✔
811
        consensus_hash: &ConsensusHash,
44✔
812
        microblocks: Vec<StacksMicroblock>,
44✔
813
        db: &mut SortitionDB,
44✔
814
        atlas_db: &mut AtlasDB,
44✔
815
    ) -> ChainTip {
44✔
816
        let _parent_consensus_hash = {
44✔
817
            // look up parent consensus hash
818
            let ic = db.index_conn();
44✔
819
            let parent_consensus_hash = StacksChainState::get_parent_consensus_hash(
44✔
820
                &ic,
44✔
821
                &anchored_block.header.parent_block,
44✔
822
                consensus_hash,
44✔
823
            )
824
            .unwrap_or_else(|_| {
44✔
UNCOV
825
                panic!(
×
826
                    "BUG: could not query chainstate to find parent consensus hash of {consensus_hash}/{}",
UNCOV
827
                    &anchored_block.block_hash()
×
828
                )
829
            })
830
            .unwrap_or_else(|| {
44✔
UNCOV
831
                panic!(
×
832
                    "BUG: no such parent of block {consensus_hash}/{}",
833
                    &anchored_block.block_hash()
×
834
                )
835
            });
836

837
            // Preprocess the anchored block
838
            self.chain_state
44✔
839
                .preprocess_anchored_block(
44✔
840
                    &ic,
44✔
841
                    consensus_hash,
44✔
842
                    anchored_block,
44✔
843
                    &parent_consensus_hash,
44✔
844
                    0,
845
                )
846
                .unwrap();
44✔
847

848
            // Preprocess the microblocks
849
            for microblock in microblocks.iter() {
44✔
UNCOV
850
                let res = self
×
UNCOV
851
                    .chain_state
×
UNCOV
852
                    .preprocess_streamed_microblock(
×
UNCOV
853
                        consensus_hash,
×
UNCOV
854
                        &anchored_block.block_hash(),
×
UNCOV
855
                        microblock,
×
856
                    )
UNCOV
857
                    .unwrap();
×
UNCOV
858
                if !res {
×
UNCOV
859
                    warn!(
×
860
                        "Unhandled error while pre-processing microblock {}",
UNCOV
861
                        microblock.header.block_hash()
×
862
                    );
UNCOV
863
                }
×
864
            }
865

866
            parent_consensus_hash
44✔
867
        };
868

869
        let atlas_config = Self::make_atlas_config();
44✔
870
        let mut processed_blocks = vec![];
44✔
871
        loop {
872
            let mut process_blocks_at_tip = {
88✔
873
                let tx = db.tx_begin_at_tip();
88✔
874
                self.chain_state
88✔
875
                    .process_blocks(tx, 1, Some(&self.event_dispatcher))
88✔
876
            };
877
            match process_blocks_at_tip {
88✔
UNCOV
878
                Err(e) => panic!("Error while processing block - {e:?}"),
×
879
                Ok(ref mut blocks) => {
88✔
880
                    if blocks.is_empty() {
88✔
881
                        break;
44✔
882
                    } else {
883
                        for block in blocks.iter() {
44✔
884
                            if let (Some(epoch_receipt), _) = block {
44✔
885
                                let attachments_instances =
44✔
886
                                    self.get_attachment_instances(epoch_receipt, &atlas_config);
44✔
887
                                if !attachments_instances.is_empty() {
44✔
UNCOV
888
                                    for new_attachment in attachments_instances.into_iter() {
×
UNCOV
889
                                        if let Err(e) =
×
UNCOV
890
                                            atlas_db.queue_attachment_instance(&new_attachment)
×
891
                                        {
UNCOV
892
                                            warn!(
×
893
                                                "Atlas: Error writing attachment instance to DB";
894
                                                "err" => ?e,
895
                                                "index_block_hash" => %new_attachment.index_block_hash,
896
                                                "contract_id" => %new_attachment.contract_id,
897
                                                "attachment_index" => %new_attachment.attachment_index,
898
                                            );
UNCOV
899
                                        }
×
900
                                    }
901
                                }
44✔
UNCOV
902
                            }
×
903
                        }
904

905
                        processed_blocks.append(blocks);
44✔
906
                    }
907
                }
908
            }
909
        }
910

911
        // todo(ludo): yikes but good enough in the context of helium:
912
        // we only expect 1 block.
913
        let processed_block = processed_blocks[0].clone().0.unwrap();
44✔
914

915
        let mut cost_estimator = self.config.make_cost_estimator();
44✔
916
        let mut fee_estimator = self.config.make_fee_estimator();
44✔
917

918
        let stacks_epoch =
44✔
919
            SortitionDB::get_stacks_epoch_by_epoch_id(db.conn(), &processed_block.evaluated_epoch)
44✔
920
                .expect("FATAL: could not query sortition DB for epochs")
44✔
921
                .expect("Could not find a stacks epoch.");
44✔
922
        if let Some(estimator) = cost_estimator.as_mut() {
44✔
923
            estimator.notify_block(
44✔
924
                &processed_block.tx_receipts,
44✔
925
                &stacks_epoch.block_limit,
44✔
926
                &stacks_epoch.epoch_id,
44✔
927
            );
44✔
928
        }
44✔
929

930
        if let Some(estimator) = fee_estimator.as_mut() {
44✔
931
            if let Err(e) = estimator.notify_block(&processed_block, &stacks_epoch.block_limit) {
44✔
UNCOV
932
                warn!("FeeEstimator failed to process block receipt";
×
UNCOV
933
                      "stacks_block_hash" => %processed_block.header.anchored_header.block_hash(),
×
934
                      "stacks_height" => %processed_block.header.stacks_block_height,
935
                      "error" => %e);
936
            }
44✔
UNCOV
937
        }
×
938

939
        // Handle events
940
        let receipts = processed_block.tx_receipts;
44✔
941
        let metadata = processed_block.header;
44✔
942
        let block: StacksBlock = {
44✔
943
            let block_path = StacksChainState::get_block_path(
44✔
944
                &self.chain_state.blocks_path,
44✔
945
                &metadata.consensus_hash,
44✔
946
                &metadata.anchored_header.block_hash(),
44✔
947
            )
948
            .unwrap();
44✔
949
            StacksChainState::consensus_load(&block_path).unwrap()
44✔
950
        };
951

952
        let chain_tip = ChainTip {
44✔
953
            metadata,
44✔
954
            block,
44✔
955
            receipts,
44✔
956
        };
44✔
957
        self.chain_tip = Some(chain_tip.clone());
44✔
958

959
        // Unset the `bootstraping_chain` flag.
960
        if self.bootstraping_chain {
44✔
961
            self.bootstraping_chain = false;
10✔
962
        }
34✔
963

964
        chain_tip
44✔
965
    }
44✔
966

967
    pub fn get_attachment_instances(
44✔
968
        &self,
44✔
969
        epoch_receipt: &StacksEpochReceipt,
44✔
970
        atlas_config: &AtlasConfig,
44✔
971
    ) -> HashSet<AttachmentInstance> {
44✔
972
        let mut attachments_instances = HashSet::new();
44✔
973
        for receipt in epoch_receipt.tx_receipts.iter() {
145✔
974
            if let TransactionOrigin::Stacks(ref transaction) = receipt.transaction {
145✔
975
                if let TransactionPayload::ContractCall(ref contract_call) = transaction.payload {
145✔
976
                    let contract_id = contract_call.to_clarity_contract_id();
17✔
977
                    if atlas_config.contracts.contains(&contract_id) {
17✔
UNCOV
978
                        for event in receipt.events.iter() {
×
UNCOV
979
                            if let StacksTransactionEvent::SmartContractEvent(ref event_data) =
×
UNCOV
980
                                event
×
981
                            {
UNCOV
982
                                let res = AttachmentInstance::try_new_from_value(
×
UNCOV
983
                                    &event_data.value,
×
UNCOV
984
                                    &contract_id,
×
UNCOV
985
                                    epoch_receipt.header.index_block_hash(),
×
UNCOV
986
                                    epoch_receipt.header.stacks_block_height,
×
UNCOV
987
                                    receipt.transaction.txid(),
×
UNCOV
988
                                    self.chain_tip
×
UNCOV
989
                                        .as_ref()
×
UNCOV
990
                                        .map(|t| t.metadata.stacks_block_height),
×
991
                                );
UNCOV
992
                                if let Some(attachment_instance) = res {
×
UNCOV
993
                                    attachments_instances.insert(attachment_instance);
×
UNCOV
994
                                }
×
UNCOV
995
                            }
×
996
                        }
997
                    }
17✔
998
                }
128✔
UNCOV
999
            }
×
1000
        }
1001
        attachments_instances
44✔
1002
    }
44✔
1003

1004
    /// Constructs and returns a LeaderKeyRegisterOp out of the provided params
1005
    fn generate_leader_key_register_op(
10✔
1006
        &mut self,
10✔
1007
        vrf_public_key: VRFPublicKey,
10✔
1008
        consensus_hash: ConsensusHash,
10✔
1009
    ) -> BlockstackOperationType {
10✔
1010
        let mut txid_bytes = [0u8; 32];
10✔
1011
        let mut rng = rand::thread_rng();
10✔
1012
        rng.fill_bytes(&mut txid_bytes);
10✔
1013
        let txid = Txid(txid_bytes);
10✔
1014

1015
        BlockstackOperationType::LeaderKeyRegister(LeaderKeyRegisterOp {
10✔
1016
            public_key: vrf_public_key,
10✔
1017
            memo: vec![],
10✔
1018
            consensus_hash,
10✔
1019
            vtxindex: 1,
10✔
1020
            txid,
10✔
1021
            block_height: 0,
10✔
1022
            burn_header_hash: BurnchainHeaderHash::zero(),
10✔
1023
        })
10✔
1024
    }
10✔
1025

1026
    /// Constructs and returns a LeaderBlockCommitOp out of the provided params
1027
    fn generate_block_commit_op(
44✔
1028
        &mut self,
44✔
1029
        block_header_hash: BlockHeaderHash,
44✔
1030
        burn_fee: u64,
44✔
1031
        key: &RegisteredKey,
44✔
1032
        burnchain_tip: &BurnchainTip,
44✔
1033
        vrf_seed: VRFSeed,
44✔
1034
    ) -> BlockstackOperationType {
44✔
1035
        let winning_tx_vtindex = burnchain_tip.get_winning_tx_index().unwrap_or(0);
44✔
1036

1037
        let (parent_block_ptr, parent_vtxindex) = match self.bootstraping_chain {
44✔
1038
            true => (0, 0), // parent_block_ptr and parent_vtxindex should both be 0 on block #1
10✔
1039
            false => (
34✔
1040
                burnchain_tip.block_snapshot.block_height as u32,
34✔
1041
                winning_tx_vtindex as u16,
34✔
1042
            ),
34✔
1043
        };
1044

1045
        let burnchain = self.config.get_burnchain();
44✔
1046
        let commit_outs = if burnchain_tip.block_snapshot.block_height + 1
44✔
1047
            < burnchain.pox_constants.sunset_end
44✔
1048
            && !burnchain.is_in_prepare_phase(burnchain_tip.block_snapshot.block_height + 1)
44✔
1049
        {
1050
            RewardSetInfo::into_commit_outs(None, self.config.is_mainnet())
17✔
1051
        } else {
1052
            vec![PoxAddress::standard_burn_address(self.config.is_mainnet())]
27✔
1053
        };
1054

1055
        let burn_parent_modulus =
44✔
1056
            (burnchain_tip.block_snapshot.block_height % BURN_BLOCK_MINED_AT_MODULUS) as u8;
44✔
1057

1058
        let mut txid_bytes = [0u8; 32];
44✔
1059
        let mut rng = rand::thread_rng();
44✔
1060
        rng.fill_bytes(&mut txid_bytes);
44✔
1061
        let txid = Txid(txid_bytes);
44✔
1062

1063
        BlockstackOperationType::LeaderBlockCommit(LeaderBlockCommitOp {
44✔
1064
            treatment: vec![],
44✔
1065
            sunset_burn: 0,
44✔
1066
            block_header_hash,
44✔
1067
            burn_fee,
44✔
1068
            input: (Txid([0; 32]), 0),
44✔
1069
            apparent_sender: self.keychain.get_burnchain_signer(),
44✔
1070
            key_block_ptr: key.block_height as u32,
44✔
1071
            key_vtxindex: key.op_vtxindex as u16,
44✔
1072
            memo: vec![STACKS_EPOCH_2_1_MARKER],
44✔
1073
            new_seed: vrf_seed,
44✔
1074
            parent_block_ptr,
44✔
1075
            parent_vtxindex,
44✔
1076
            vtxindex: 2,
44✔
1077
            txid,
44✔
1078
            commit_outs,
44✔
1079
            block_height: 0,
44✔
1080
            burn_header_hash: BurnchainHeaderHash::zero(),
44✔
1081
            burn_parent_modulus,
44✔
1082
        })
44✔
1083
    }
44✔
1084

1085
    // Constructs a coinbase transaction
1086
    fn generate_coinbase_tx(&mut self, is_mainnet: bool) -> StacksTransaction {
54✔
1087
        let mut tx_auth = self.keychain.get_transaction_auth().unwrap();
54✔
1088
        tx_auth.set_origin_nonce(self.nonce);
54✔
1089

1090
        let version = if is_mainnet {
54✔
UNCOV
1091
            TransactionVersion::Mainnet
×
1092
        } else {
1093
            TransactionVersion::Testnet
54✔
1094
        };
1095
        let mut tx = StacksTransaction::new(
54✔
1096
            version,
54✔
1097
            tx_auth,
54✔
1098
            TransactionPayload::Coinbase(CoinbasePayload([0u8; 32]), None, None),
54✔
1099
        );
1100
        tx.chain_id = self.config.burnchain.chain_id;
54✔
1101
        tx.anchor_mode = TransactionAnchorMode::OnChainOnly;
54✔
1102
        let mut tx_signer = StacksTransactionSigner::new(&tx);
54✔
1103
        self.keychain.sign_as_origin(&mut tx_signer);
54✔
1104

1105
        // Increment nonce
1106
        self.nonce += 1;
54✔
1107

1108
        tx_signer.get_tx().unwrap()
54✔
1109
    }
54✔
1110
}
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