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

stacks-network / stacks-core / 25446651601-1

06 May 2026 04:04PM UTC coverage: 85.673% (-0.04%) from 85.712%
25446651601-1

Pull #7169

github

c82af2
web-flow
Merge 1839b925c into 53ffba0ab
Pull Request #7169: Feat: add defensive memory allocation for miners/signers

135 of 139 new or added lines in 11 files covered. (97.12%)

4644 existing lines in 100 files now uncovered.

187695 of 219083 relevant lines covered (85.67%)

18932038.48 hits per line

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

81.28
/stackslib/src/net/api/postblock_proposal.rs
1
// Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation
2
// Copyright (C) 2020-2023 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::VecDeque;
18
use std::hash::{DefaultHasher, Hash, Hasher};
19
#[cfg(any(test, feature = "testing"))]
20
use std::sync::LazyLock;
21
use std::thread::{self, JoinHandle};
22
use std::time::{Duration, Instant};
23

24
use clarity::vm::contexts::AbortCallback;
25
use clarity::vm::costs::ExecutionCost;
26
use clarity::vm::events::StacksTransactionEvent;
27
use clarity::vm::types::{ResponseData, TupleData};
28
use clarity::vm::Value;
29
use regex::{Captures, Regex};
30
use serde::Deserialize;
31
use stacks_common::codec::{Error as CodecError, StacksMessageCodec, MAX_PAYLOAD_LEN};
32
use stacks_common::consts::CHAIN_ID_MAINNET;
33
use stacks_common::types::chainstate::{ConsensusHash, StacksBlockId};
34
use stacks_common::util::get_epoch_time_secs;
35
use stacks_common::util::hash::{hex_bytes, to_hex, Sha512Trunc256Sum};
36
#[cfg(any(test, feature = "testing"))]
37
use stacks_common::util::tests::TestFlag;
38

39
use crate::burnchains::Txid;
40
use crate::chainstate::burn::db::sortdb::{SortitionDB, SortitionHandleConn};
41
use crate::chainstate::nakamoto::miner::{
42
    make_mem_abort_callback, MinerTenureInfoCause, NakamotoBlockBuilder,
43
};
44
use crate::chainstate::nakamoto::{NakamotoBlock, NakamotoChainState, NAKAMOTO_BLOCK_VERSION};
45
use crate::chainstate::stacks::address::PoxAddress;
46
use crate::chainstate::stacks::boot::PoxVersions;
47
use crate::chainstate::stacks::db::{StacksBlockHeaderTypes, StacksChainState, StacksHeaderInfo};
48
use crate::chainstate::stacks::miner::{
49
    BlockBuilder, BlockLimitFunction, TransactionError, TransactionProblematic, TransactionResult,
50
    TransactionSkipped,
51
};
52
use crate::chainstate::stacks::{Error as ChainError, StacksTransaction, TransactionPayload};
53
use crate::clarity_vm::clarity::ClarityError;
54
use crate::config::DEFAULT_MAX_TENURE_BYTES;
55
use crate::core::mempool::ProposalCallbackReceiver;
56
use crate::net::connection::ConnectionOptions;
57
use crate::net::http::{
58
    http_reason, parse_json, Error, HttpContentType, HttpRequest, HttpRequestContents,
59
    HttpRequestPreamble, HttpResponse, HttpResponseContents, HttpResponsePayload,
60
    HttpResponsePreamble,
61
};
62
use crate::net::httpcore::RPCRequestHandler;
63
use crate::net::{Error as NetError, StacksNodeState};
64
use crate::util_lib::db::Error as db_error;
65

66
/// Test flag to stall block validation per endpoint with a matching passphrase
67
#[cfg(any(test, feature = "testing"))]
68
pub static TEST_VALIDATE_STALL: LazyLock<TestFlag<Vec<Option<String>>>> =
69
    LazyLock::new(TestFlag::default);
70

71
#[cfg(any(test, feature = "testing"))]
72
/// Artificial delay to add to block validation.
73
pub static TEST_VALIDATE_DELAY_DURATION_SECS: LazyLock<TestFlag<u64>> =
74
    LazyLock::new(TestFlag::default);
75

76
#[cfg(any(test, feature = "testing"))]
77
/// Mock for the set of transactions that must be replayed
78
pub static TEST_REPLAY_TRANSACTIONS: LazyLock<
79
    TestFlag<std::collections::VecDeque<StacksTransaction>>,
80
> = LazyLock::new(TestFlag::default);
81

82
#[cfg(any(test, feature = "testing"))]
83
/// Whether to reject any transaction while we're in a replay set.
84
pub static TEST_REJECT_REPLAY_TXS: LazyLock<TestFlag<bool>> = LazyLock::new(TestFlag::default);
85

86
// This enum is used to supply a `reason_code` for validation
87
//  rejection responses. This is serialized as an enum with string
88
//  type (in jsonschema terminology).
89
define_u8_enum![ValidateRejectCode {
90
    BadBlockHash = 0,
91
    BadTransaction = 1,
92
    InvalidBlock = 2,
93
    ChainstateError = 3,
94
    UnknownParent = 4,
95
    NonCanonicalTenure = 5,
96
    NoSuchTenure = 6,
97
    InvalidTransactionReplay = 7,
98
    InvalidParentBlock = 8,
99
    InvalidTimestamp = 9,
100
    NetworkChainMismatch = 10,
101
    NotFoundError = 11,
102
    ProblematicTransaction = 12
103
}];
104

105
pub static TOO_MANY_REQUESTS_STATUS: u16 = 429;
106

107
impl TryFrom<u8> for ValidateRejectCode {
108
    type Error = CodecError;
109
    fn try_from(value: u8) -> Result<Self, Self::Error> {
12,320✔
110
        Self::from_u8(value)
12,320✔
111
            .ok_or_else(|| CodecError::DeserializeError(format!("Unknown type prefix: {value}")))
12,320✔
112
    }
12,320✔
113
}
114

115
fn hex_ser_block<S: serde::Serializer>(b: &NakamotoBlock, s: S) -> Result<S::Ok, S::Error> {
32,323✔
116
    let inst = to_hex(&b.serialize_to_vec());
32,323✔
117
    s.serialize_str(inst.as_str())
32,323✔
118
}
32,323✔
119

120
fn hex_deser_block<'de, D: serde::Deserializer<'de>>(d: D) -> Result<NakamotoBlock, D::Error> {
107,635✔
121
    let inst_str = String::deserialize(d)?;
107,635✔
122
    let bytes = hex_bytes(&inst_str).map_err(serde::de::Error::custom)?;
107,635✔
123
    NakamotoBlock::consensus_deserialize(&mut bytes.as_slice()).map_err(serde::de::Error::custom)
107,635✔
124
}
107,635✔
125

126
/// A response for block proposal validation
127
///  that the stacks-node thinks should be rejected.
128
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
129
pub struct BlockValidateReject {
130
    pub signer_signature_hash: Sha512Trunc256Sum,
131
    pub reason: String,
132
    pub reason_code: ValidateRejectCode,
133
    /// The txid of the transaction that caused the block to be rejected, if any
134
    #[serde(default)]
135
    pub failed_txid: Option<Txid>,
136
}
137

138
#[derive(Debug, Clone, PartialEq)]
139
pub struct BlockValidateRejectReason {
140
    pub reason: String,
141
    pub reason_code: ValidateRejectCode,
142
    /// The txid of the transaction that caused the block to be rejected, if any
143
    pub failed_txid: Option<Txid>,
144
}
145

146
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
147
pub enum BlockProposalResult {
148
    Accepted,
149
    Error,
150
}
151

152
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
153
pub struct BlockProposalResponse {
154
    pub result: BlockProposalResult,
155
    pub message: String,
156
}
157

158
impl<T> From<T> for BlockValidateRejectReason
159
where
160
    T: Into<ChainError>,
161
{
162
    fn from(value: T) -> Self {
110✔
163
        let ce: ChainError = value.into();
110✔
164
        let reason_code = match ce {
110✔
165
            ChainError::DBError(db_error::NotFoundError) => ValidateRejectCode::NotFoundError,
90✔
166
            _ => ValidateRejectCode::ChainstateError,
20✔
167
        };
168
        Self {
110✔
169
            reason: format!("Chainstate Error: {ce}"),
110✔
170
            reason_code,
110✔
171
            failed_txid: None,
110✔
172
        }
110✔
173
    }
110✔
174
}
175

176
/// A response for block proposal validation
177
///  that the stacks-node thinks is acceptable.
178
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
179
pub struct BlockValidateOk {
180
    pub signer_signature_hash: Sha512Trunc256Sum,
181
    pub cost: ExecutionCost,
182
    pub size: u64,
183
    pub validation_time_ms: u64,
184
    /// If a block was validated by a transaction replay set,
185
    /// then this returns `Some` with the hash of the replay set.
186
    pub replay_tx_hash: Option<u64>,
187
    /// If a block was validated by a transaction replay set,
188
    /// then this is true if this block exhausted the set of transactions.
189
    pub replay_tx_exhausted: bool,
190
}
191

192
/// This enum is used for serializing the response to block
193
/// proposal validation.
194
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
195
#[serde(tag = "result")]
196
pub enum BlockValidateResponse {
197
    Ok(BlockValidateOk),
198
    Reject(BlockValidateReject),
199
}
200

201
impl From<Result<BlockValidateOk, BlockValidateReject>> for BlockValidateResponse {
202
    fn from(value: Result<BlockValidateOk, BlockValidateReject>) -> Self {
7,644✔
203
        match value {
7,644✔
204
            Ok(o) => BlockValidateResponse::Ok(o),
7,510✔
205
            Err(e) => BlockValidateResponse::Reject(e),
134✔
206
        }
207
    }
7,644✔
208
}
209

210
impl BlockValidateResponse {
211
    /// Get the signer signature hash from the response
212
    pub fn signer_signature_hash(&self) -> &Sha512Trunc256Sum {
52,566✔
213
        match self {
52,566✔
214
            BlockValidateResponse::Ok(o) => &o.signer_signature_hash,
51,576✔
215
            BlockValidateResponse::Reject(r) => &r.signer_signature_hash,
990✔
216
        }
217
    }
52,566✔
218
}
219

220
#[cfg(any(test, feature = "testing"))]
221
fn fault_injection_validation_stall(auth_token: Option<String>) {
38,223✔
222
    if TEST_VALIDATE_STALL.get().contains(&auth_token) {
38,223✔
223
        // Do an extra check just so we don't log EVERY time.
224
        warn!("Block validation is stalled due to testing directive."; "auth_token" => ?auth_token);
90✔
225
        while TEST_VALIDATE_STALL.get().contains(&auth_token) {
123,290✔
226
            std::thread::sleep(std::time::Duration::from_millis(10));
123,200✔
227
        }
123,200✔
228
        info!(
90✔
229
            "Block validation is no longer stalled due to testing directive. Continuing..."; "auth_token" => ?auth_token
230
        );
231
    }
38,133✔
232
}
38,223✔
233

234
#[cfg(not(any(test, feature = "testing")))]
235
fn fault_injection_validation_stall(_auth_token: Option<String>) {}
236

237
#[cfg(any(test, feature = "testing"))]
238
fn fault_injection_validation_delay() {
38,223✔
239
    let delay = TEST_VALIDATE_DELAY_DURATION_SECS.get();
38,223✔
240
    if delay == 0 {
38,223✔
241
        return;
37,703✔
242
    }
520✔
243
    warn!("Sleeping for {} seconds to simulate slow processing", delay);
520✔
244
    thread::sleep(Duration::from_secs(delay));
520✔
245
}
38,223✔
246

247
#[cfg(not(any(test, feature = "testing")))]
248
fn fault_injection_validation_delay() {}
249

250
#[cfg(any(test, feature = "testing"))]
251
fn fault_injection_reject_replay_txs() -> Result<(), BlockValidateRejectReason> {
610✔
252
    let reject = TEST_REJECT_REPLAY_TXS.get();
610✔
253
    if reject {
610✔
254
        Err(BlockValidateRejectReason {
80✔
255
            reason_code: ValidateRejectCode::InvalidTransactionReplay,
80✔
256
            reason: "Rejected by test flag".into(),
80✔
257
            failed_txid: None,
80✔
258
        })
80✔
259
    } else {
260
        Ok(())
530✔
261
    }
262
}
610✔
263

264
#[cfg(not(any(test, feature = "testing")))]
265
fn fault_injection_reject_replay_txs() -> Result<(), BlockValidateRejectReason> {
266
    Ok(())
267
}
268

269
/// Represents a block proposed to the `v3/block_proposal` endpoint for validation
270
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
271
pub struct NakamotoBlockProposal {
272
    /// Proposed block
273
    #[serde(serialize_with = "hex_ser_block", deserialize_with = "hex_deser_block")]
274
    pub block: NakamotoBlock,
275
    /// Identifies which chain block is for (Mainnet, Testnet, etc.)
276
    pub chain_id: u32,
277
    /// Optional transaction replay set
278
    pub replay_txs: Option<Vec<StacksTransaction>>,
279
}
280

281
fn match_result_ok(value: &Value) -> Option<&Value> {
869✔
282
    let Value::Response(ResponseData { committed, data }) = value else {
869✔
UNCOV
283
        return None;
×
284
    };
285
    if !committed {
869✔
UNCOV
286
        return None;
×
287
    }
869✔
288
    Some(data.as_ref())
869✔
289
}
869✔
290

291
fn match_tuple(value: &Value) -> Option<&TupleData> {
1,738✔
292
    if let Value::Tuple(data) = value {
1,738✔
293
        Some(data)
1,738✔
294
    } else {
UNCOV
295
        None
×
296
    }
297
}
1,738✔
298

299
pub fn is_event_pox_addr_valid(is_mainnet: bool, event: &StacksTransactionEvent) -> bool {
3,401,020✔
300
    let StacksTransactionEvent::SmartContractEvent(event) = event else {
3,401,020✔
301
        // only smart contract events are relevant, so everything else is "okay"
302
        return true;
3,399,421✔
303
    };
304
    if !event.key.0.is_boot() {
1,599✔
305
        // only boot code events are relevant, so everything else is "okay"
306
        return true;
712✔
307
    }
887✔
308
    if event.key.0.name.as_str() != PoxVersions::Pox4.get_name_str() {
887✔
309
        // only pox events are relevant
310
        return true;
18✔
311
    }
869✔
312
    if &event.key.1 != "print" {
869✔
313
        // only look at print events
UNCOV
314
        return true;
×
315
    }
869✔
316
    let Some(pox_event_tuple) = match_result_ok(&event.value) else {
869✔
317
        // only care about (okay ...) results
318
        return true;
×
319
    };
320
    let Some(outer_tuple_data) = match_tuple(&pox_event_tuple) else {
869✔
321
        // should be unreachable
UNCOV
322
        return true;
×
323
    };
324
    let Ok(data_tuple) = outer_tuple_data.get("data") else {
869✔
325
        // should be unreachable
326
        return true;
×
327
    };
328
    let Some(data_tuple_data) = match_tuple(&data_tuple) else {
869✔
329
        // should be unreachable
UNCOV
330
        return true;
×
331
    };
332
    let Ok(pox_addr_tuple) = data_tuple_data.get("pox-addr") else {
869✔
333
        // should be unreachable
334
        return true;
30✔
335
    };
336

337
    let pox_addr_value = if let Value::Optional(data) = pox_addr_tuple {
839✔
338
        match data.data {
45✔
339
            None => return true,
31✔
340
            Some(ref inner) => inner.as_ref(),
14✔
341
        }
342
    } else {
343
        pox_addr_tuple
794✔
344
    };
345

346
    PoxAddress::try_from_pox_tuple(is_mainnet, pox_addr_value).is_some()
808✔
347
}
3,401,020✔
348

349
impl NakamotoBlockProposal {
350
    fn spawn_validation_thread(
38,223✔
351
        self,
38,223✔
352
        sortdb: SortitionDB,
38,223✔
353
        mut chainstate: StacksChainState,
38,223✔
354
        receiver: Box<dyn ProposalCallbackReceiver>,
38,223✔
355
        connection_opts: &ConnectionOptions,
38,223✔
356
    ) -> Result<JoinHandle<()>, std::io::Error> {
38,223✔
357
        let timeout_secs = connection_opts.block_proposal_validation_timeout_secs;
38,223✔
358
        let max_tx_mem_bytes = connection_opts.block_proposal_max_tx_mem_bytes;
38,223✔
359
        let auth_token = connection_opts.auth_token.clone();
38,223✔
360
        thread::Builder::new()
38,223✔
361
            .name("block-proposal".into())
38,223✔
362
            .spawn(move || {
38,223✔
363
                let result = self
38,223✔
364
                    .validate(
38,223✔
365
                        &sortdb,
38,223✔
366
                        &mut chainstate,
38,223✔
367
                        timeout_secs,
38,223✔
368
                        max_tx_mem_bytes,
38,223✔
369
                        auth_token,
38,223✔
370
                    )
371
                    .map_err(|reason| BlockValidateReject {
38,223✔
372
                        signer_signature_hash: self.block.header.signer_signature_hash(),
672✔
373
                        reason_code: reason.reason_code,
672✔
374
                        reason: reason.reason,
672✔
375
                        failed_txid: reason.failed_txid,
672✔
376
                    });
672✔
377
                receiver.notify_proposal_result(result);
38,223✔
378
            })
38,223✔
379
    }
38,223✔
380

381
    /// DO NOT CALL FROM CONSENSUS CODE
382
    ///
383
    /// Check to see if a block builds atop the highest block in a given tenure.
384
    /// That is:
385
    /// - its parent must exist, and
386
    /// - its parent must be as high as the highest block in the given tenure.
387
    fn check_block_builds_on_highest_block_in_tenure(
37,893✔
388
        chainstate: &StacksChainState,
37,893✔
389
        sortdb: &SortitionDB,
37,893✔
390
        tenure_id: &ConsensusHash,
37,893✔
391
        parent_block_id: &StacksBlockId,
37,893✔
392
    ) -> Result<(), BlockValidateRejectReason> {
37,893✔
393
        let Some(highest_header) = NakamotoChainState::find_highest_known_block_header_in_tenure(
37,893✔
394
            chainstate, sortdb, tenure_id,
37,893✔
395
        )
396
        .map_err(|e| BlockValidateRejectReason {
37,893✔
397
            reason_code: ValidateRejectCode::ChainstateError,
×
398
            reason: format!("Failed to query highest block in tenure ID: {:?}", &e),
×
399
            failed_txid: None,
×
UNCOV
400
        })?
×
401
        else {
UNCOV
402
            warn!(
×
403
                "Rejected block proposal";
404
                "reason" => "Block is not a tenure-start block, and has an unrecognized tenure consensus hash",
405
                "consensus_hash" => %tenure_id,
406
            );
UNCOV
407
            return Err(BlockValidateRejectReason {
×
UNCOV
408
                reason_code: ValidateRejectCode::NoSuchTenure,
×
UNCOV
409
                reason: "Block is not a tenure-start block, and has an unrecognized tenure consensus hash".into(),
×
UNCOV
410
                failed_txid: None,
×
UNCOV
411
            });
×
412
        };
413
        let Some(parent_header) =
37,893✔
414
            NakamotoChainState::get_block_header(chainstate.db(), parent_block_id).map_err(
37,893✔
415
                |e| BlockValidateRejectReason {
416
                    reason_code: ValidateRejectCode::ChainstateError,
×
UNCOV
417
                    reason: format!("Failed to query block header by block ID: {:?}", &e),
×
418
                    failed_txid: None,
×
419
                },
×
420
            )?
×
421
        else {
UNCOV
422
            warn!(
×
423
                "Rejected block proposal";
424
                "reason" => "Block has no parent",
425
                "parent_block_id" => %parent_block_id
426
            );
427
            return Err(BlockValidateRejectReason {
×
UNCOV
428
                reason_code: ValidateRejectCode::UnknownParent,
×
UNCOV
429
                reason: "Block has no parent".into(),
×
UNCOV
430
                failed_txid: None,
×
UNCOV
431
            });
×
432
        };
433
        if parent_header.anchored_header.height() != highest_header.anchored_header.height() {
37,893✔
434
            warn!(
220✔
435
                "Rejected block proposal";
436
                "reason" => "Block's parent is not the highest block in this tenure",
437
                "consensus_hash" => %tenure_id,
438
                "parent_header.height" => parent_header.anchored_header.height(),
220✔
439
                "highest_header.height" => highest_header.anchored_header.height(),
220✔
440
            );
441
            return Err(BlockValidateRejectReason {
220✔
442
                reason_code: ValidateRejectCode::InvalidParentBlock,
220✔
443
                reason: "Block is not higher than the highest block in its tenure".into(),
220✔
444
                failed_txid: None,
220✔
445
            });
220✔
446
        }
37,673✔
447
        Ok(())
37,673✔
448
    }
37,893✔
449

450
    /// Verify that the block we received builds upon a valid tenure.
451
    /// Implemented as a static function to facilitate testing.
452
    pub(crate) fn check_block_has_valid_tenure(
37,903✔
453
        db_handle: &SortitionHandleConn,
37,903✔
454
        tenure_id: &ConsensusHash,
37,903✔
455
    ) -> Result<(), BlockValidateRejectReason> {
37,903✔
456
        // Verify that the block's tenure is on the canonical sortition history
457
        if !db_handle.has_consensus_hash(tenure_id)? {
37,903✔
458
            warn!(
10✔
459
                "Rejected block proposal";
460
                "reason" => "Block's tenure consensus hash is not on the canonical Bitcoin fork",
461
                "consensus_hash" => %tenure_id,
462
            );
463
            return Err(BlockValidateRejectReason {
10✔
464
                reason_code: ValidateRejectCode::NonCanonicalTenure,
10✔
465
                reason: "Tenure consensus hash is not on the canonical Bitcoin fork".into(),
10✔
466
                failed_txid: None,
10✔
467
            });
10✔
468
        }
37,893✔
469
        Ok(())
37,893✔
470
    }
37,903✔
471

472
    /// Verify that the block we received builds on the highest block in its tenure.
473
    /// * For tenure-start blocks, the parent must be as high as the highest block in the parent
474
    /// block's tenure.
475
    /// * For all other blocks, the parent must be as high as the highest block in the tenure.
476
    ///
477
    /// Implemented as a static function to facilitate testing
478
    pub(crate) fn check_block_has_valid_parent(
37,893✔
479
        chainstate: &StacksChainState,
37,893✔
480
        sortdb: &SortitionDB,
37,893✔
481
        block: &NakamotoBlock,
37,893✔
482
    ) -> Result<(), BlockValidateRejectReason> {
37,893✔
483
        let is_tenure_start =
37,893✔
484
            block
37,893✔
485
                .is_wellformed_tenure_start_block()
37,893✔
486
                .map_err(|_| BlockValidateRejectReason {
37,893✔
UNCOV
487
                    reason_code: ValidateRejectCode::InvalidBlock,
×
UNCOV
488
                    reason: "Block is not well-formed".into(),
×
UNCOV
489
                    failed_txid: None,
×
UNCOV
490
                })?;
×
491

492
        if !is_tenure_start {
37,893✔
493
            // this is a well-formed block that is not the start of a tenure, so it must build
494
            // atop an existing block in its tenure.
495
            Self::check_block_builds_on_highest_block_in_tenure(
13,763✔
496
                chainstate,
13,763✔
497
                sortdb,
13,763✔
498
                &block.header.consensus_hash,
13,763✔
499
                &block.header.parent_block_id,
13,763✔
500
            )?;
210✔
501
        } else {
502
            // this is a tenure-start block, so it must build atop a parent which has the
503
            // highest height in the *previous* tenure.
504
            let parent_header = NakamotoChainState::get_block_header(
24,130✔
505
                chainstate.db(),
24,130✔
506
                &block.header.parent_block_id,
24,130✔
UNCOV
507
            )?
×
508
            .ok_or_else(|| BlockValidateRejectReason {
24,130✔
UNCOV
509
                reason_code: ValidateRejectCode::UnknownParent,
×
UNCOV
510
                reason: "No parent block".into(),
×
UNCOV
511
                failed_txid: None,
×
UNCOV
512
            })?;
×
513

514
            Self::check_block_builds_on_highest_block_in_tenure(
24,130✔
515
                chainstate,
24,130✔
516
                sortdb,
24,130✔
517
                &parent_header.consensus_hash,
24,130✔
518
                &block.header.parent_block_id,
24,130✔
519
            )?;
10✔
520
        }
521
        Ok(())
37,673✔
522
    }
37,893✔
523

524
    /// Test this block proposal against the current chain state and
525
    /// either accept or reject the proposal
526
    ///
527
    /// This is done in 3 stages:
528
    /// - Static validation of the block, which checks the following:
529
    ///   - Block header is well-formed
530
    ///   - Transactions are well-formed
531
    ///   - Miner signature is valid
532
    /// - Validation of transactions by executing them agains current chainstate.
533
    ///   This is resource intensive, and therefore done only if previous checks pass
534
    ///
535
    /// During transaction replay, we also check that the block only contains the unmined
536
    /// transactions that need to be replayed, up until either:
537
    /// - The set of transactions that must be replayed is exhausted
538
    /// - A cost limit is hit
539
    pub fn validate(
38,223✔
540
        &self,
38,223✔
541
        sortdb: &SortitionDB,
38,223✔
542
        chainstate: &mut StacksChainState, // not directly used; used as a handle to open other chainstates
38,223✔
543
        timeout_secs: u64,
38,223✔
544
        max_tx_mem_bytes: u64,
38,223✔
545
        auth_token: Option<String>,
38,223✔
546
    ) -> Result<BlockValidateOk, BlockValidateRejectReason> {
38,223✔
547
        fault_injection_validation_stall(auth_token);
38,223✔
548
        let start = Instant::now();
38,223✔
549

550
        fault_injection_validation_delay();
38,223✔
551

552
        let mainnet = self.chain_id == CHAIN_ID_MAINNET;
38,223✔
553
        if self.chain_id != chainstate.chain_id || mainnet != chainstate.mainnet {
38,223✔
554
            warn!(
10✔
555
                "Rejected block proposal";
556
                "reason" => "Wrong network/chain_id",
557
                "expected_chain_id" => chainstate.chain_id,
10✔
558
                "expected_mainnet" => chainstate.mainnet,
10✔
559
                "received_chain_id" => self.chain_id,
10✔
560
                "received_mainnet" => mainnet,
10✔
561
            );
562
            return Err(BlockValidateRejectReason {
10✔
563
                reason_code: ValidateRejectCode::NetworkChainMismatch,
10✔
564
                reason: "Wrong network/chain_id".into(),
10✔
565
                failed_txid: None,
10✔
566
            });
10✔
567
        }
38,213✔
568

569
        // Check block version. If it's less than the compiled-in version, just emit a warning
570
        // because there's a new version of the node / signer binary available that really ought to
571
        // be used (hint, hint)
572
        if self.block.header.version != NAKAMOTO_BLOCK_VERSION {
38,213✔
UNCOV
573
            warn!("Proposed block has unexpected version. Upgrade your node and/or signer ASAP.";
×
574
                  "block.header.version" => %self.block.header.version,
575
                  "expected" => %NAKAMOTO_BLOCK_VERSION);
576
        }
38,213✔
577

578
        // open sortition view to the current burn view.
579
        // If the block has a TenureChange with an Extend cause, then the burn view is whatever is
580
        // indicated in the TenureChange.
581
        // Otherwise, it's the same as the block's parent's burn view.
582
        let parent_stacks_header = NakamotoChainState::get_block_header(
38,213✔
583
            chainstate.db(),
38,213✔
584
            &self.block.header.parent_block_id,
38,213✔
585
        )?
×
586
        .ok_or_else(|| BlockValidateRejectReason {
38,213✔
587
            reason_code: ValidateRejectCode::UnknownParent,
210✔
588
            reason: "Unknown parent block".into(),
210✔
589
            failed_txid: None,
210✔
590
        })?;
210✔
591

592
        let burn_view_consensus_hash =
37,913✔
593
            NakamotoChainState::get_block_burn_view(sortdb, &self.block, &parent_stacks_header)?;
38,003✔
594
        let sort_tip =
37,913✔
595
            SortitionDB::get_block_snapshot_consensus(sortdb.conn(), &burn_view_consensus_hash)?
37,913✔
596
                .ok_or_else(|| BlockValidateRejectReason {
37,913✔
UNCOV
597
                    reason_code: ValidateRejectCode::NoSuchTenure,
×
UNCOV
598
                    reason: "Failed to find sortition for block tenure".to_string(),
×
UNCOV
599
                    failed_txid: None,
×
UNCOV
600
                })?;
×
601

602
        let burn_dbconn: SortitionHandleConn = sortdb.index_handle(&sort_tip.sortition_id);
37,913✔
603
        let db_handle = sortdb.index_handle(&sort_tip.sortition_id);
37,913✔
604

605
        // (For the signer)
606
        // Verify that the block's tenure is on the canonical sortition history
607
        Self::check_block_has_valid_tenure(&db_handle, &self.block.header.consensus_hash)?;
37,913✔
608

609
        // (For the signer)
610
        // Verify that this block's parent is the highest such block we can build off of
611
        Self::check_block_has_valid_parent(chainstate, sortdb, &self.block)?;
37,903✔
612

613
        // get the burnchain tokens spent for this block. There must be a record of this (i.e.
614
        // there must be a block-commit for this), or otherwise this block doesn't correspond to
615
        // any burnchain chainstate.
616
        let expected_burn_opt =
37,683✔
617
            NakamotoChainState::get_expected_burns(&db_handle, chainstate.db(), &self.block)?;
37,683✔
618
        if expected_burn_opt.is_none() {
37,683✔
UNCOV
619
            warn!(
×
620
                "Rejected block proposal";
621
                "reason" => "Failed to find parent expected burns",
622
            );
UNCOV
623
            return Err(BlockValidateRejectReason {
×
UNCOV
624
                reason_code: ValidateRejectCode::UnknownParent,
×
UNCOV
625
                reason: "Failed to find parent expected burns".into(),
×
UNCOV
626
                failed_txid: None,
×
UNCOV
627
            });
×
628
        };
37,683✔
629

630
        // Static validation checks
631
        NakamotoChainState::validate_normal_nakamoto_block_burnchain(
37,683✔
632
            chainstate.nakamoto_blocks_db(),
37,683✔
633
            &db_handle,
37,683✔
634
            expected_burn_opt,
37,683✔
635
            &self.block,
37,683✔
636
            mainnet,
37,683✔
637
            self.chain_id,
37,683✔
638
        )?;
20✔
639

640
        // Validate txs against chainstate
641

642
        // Validate the block's timestamp. It must be:
643
        // - Greater than the parent block's timestamp
644
        // - At most 15 seconds into the future
645
        if let StacksBlockHeaderTypes::Nakamoto(parent_nakamoto_header) =
32,733✔
646
            &parent_stacks_header.anchored_header
37,663✔
647
        {
648
            if self.block.header.timestamp <= parent_nakamoto_header.timestamp {
32,733✔
649
                warn!(
1✔
650
                    "Rejected block proposal";
651
                    "reason" => "Block timestamp is not greater than parent block",
652
                    "block_timestamp" => self.block.header.timestamp,
1✔
653
                    "parent_block_timestamp" => parent_nakamoto_header.timestamp,
1✔
654
                );
655
                return Err(BlockValidateRejectReason {
1✔
656
                    reason_code: ValidateRejectCode::InvalidTimestamp,
1✔
657
                    reason: "Block timestamp is not greater than parent block".into(),
1✔
658
                    failed_txid: None,
1✔
659
                });
1✔
660
            }
32,732✔
661
        }
4,930✔
662
        if self.block.header.timestamp > get_epoch_time_secs() + 15 {
37,662✔
663
            warn!(
1✔
664
                "Rejected block proposal";
665
                "reason" => "Block timestamp is too far into the future",
666
                "block_timestamp" => self.block.header.timestamp,
1✔
667
                "current_time" => get_epoch_time_secs(),
1✔
668
            );
669
            return Err(BlockValidateRejectReason {
1✔
670
                reason_code: ValidateRejectCode::InvalidTimestamp,
1✔
671
                reason: "Block timestamp is too far into the future".into(),
1✔
672
                failed_txid: None,
1✔
673
            });
1✔
674
        }
37,661✔
675

676
        if self.block.header.chain_length
37,661✔
677
            != parent_stacks_header.stacks_block_height.saturating_add(1)
37,661✔
678
        {
UNCOV
679
            warn!(
×
680
                "Rejected block proposal";
681
                "reason" => "Block height is non-contiguous with parent",
UNCOV
682
                "block_height" => self.block.header.chain_length,
×
UNCOV
683
                "parent_block_height" => parent_stacks_header.stacks_block_height,
×
684
            );
UNCOV
685
            return Err(BlockValidateRejectReason {
×
UNCOV
686
                reason_code: ValidateRejectCode::InvalidBlock,
×
UNCOV
687
                reason: "Block height is non-contiguous with parent".into(),
×
UNCOV
688
                failed_txid: None,
×
UNCOV
689
            });
×
690
        }
37,661✔
691

692
        let tenure_change = self
37,661✔
693
            .block
37,661✔
694
            .txs
37,661✔
695
            .iter()
37,661✔
696
            .find(|tx| matches!(tx.payload, TransactionPayload::TenureChange(..)));
1,383,961✔
697
        let coinbase = self
37,661✔
698
            .block
37,661✔
699
            .txs
37,661✔
700
            .iter()
37,661✔
701
            .find(|tx| matches!(tx.payload, TransactionPayload::Coinbase(..)));
1,409,341✔
702
        let tenure_cause = tenure_change
37,661✔
703
            .and_then(|tx| match &tx.payload {
37,661✔
704
                TransactionPayload::TenureChange(tc) => Some(MinerTenureInfoCause::from(tc)),
26,660✔
UNCOV
705
                _ => None,
×
706
            })
26,660✔
707
            .unwrap_or_else(|| MinerTenureInfoCause::NoTenureChange);
37,661✔
708

709
        let replay_tx_exhausted = self.validate_replay(
37,661✔
710
            &parent_stacks_header,
37,661✔
711
            tenure_change,
37,661✔
712
            coinbase,
37,661✔
713
            tenure_cause,
37,661✔
714
            chainstate,
37,661✔
715
            &burn_dbconn,
37,661✔
716
        )?;
110✔
717

718
        let mut builder = NakamotoBlockBuilder::new(
37,551✔
719
            &parent_stacks_header,
37,551✔
720
            &self.block.header.consensus_hash,
37,551✔
721
            self.block.header.burn_spent,
37,551✔
722
            tenure_change,
37,551✔
723
            coinbase,
37,551✔
724
            self.block.header.pox_treatment.len(),
37,551✔
725
            None,
37,551✔
726
            None,
37,551✔
727
            Some(self.block.header.timestamp),
37,551✔
728
            u64::from(DEFAULT_MAX_TENURE_BYTES),
37,551✔
UNCOV
729
        )?;
×
730

731
        let mut miner_tenure_info =
37,551✔
732
            builder.load_tenure_info(chainstate, &burn_dbconn, tenure_cause)?;
37,551✔
733
        let burn_chain_height = miner_tenure_info.burn_tip_height;
37,551✔
734
        let mut tenure_tx = builder.tenure_begin(&burn_dbconn, &mut miner_tenure_info)?;
37,551✔
735

736
        let block_deadline = Instant::now() + Duration::from_secs(timeout_secs);
37,551✔
737
        let mut receipts_total = 0u64;
37,551✔
738
        for (i, tx) in self.block.txs.iter().enumerate() {
1,409,091✔
739
            let remaining = block_deadline.saturating_duration_since(Instant::now());
1,409,091✔
740

741
            let tx_len = tx.tx_len();
1,409,091✔
742

743
            if max_tx_mem_bytes > 0 {
1,409,091✔
744
                tenure_tx.set_abort_callback(make_mem_abort_callback(max_tx_mem_bytes));
1,409,091✔
745
            }
1,409,091✔
746

747
            let tx_result = builder.try_mine_tx_with_len(
1,409,091✔
748
                &mut tenure_tx,
1,409,091✔
749
                tx,
1,409,091✔
750
                tx_len,
1,409,091✔
751
                &BlockLimitFunction::NO_LIMIT_HIT,
1,409,091✔
752
                Some(remaining),
1,409,091✔
753
                &mut receipts_total,
1,409,091✔
754
            );
755

756
            tenure_tx.set_abort_callback(AbortCallback::None);
1,409,091✔
757

758
            let reason = match tx_result {
1,409,091✔
759
                TransactionResult::Success(success_result) => {
1,409,091✔
760
                    let all_events_valid = success_result
1,409,091✔
761
                        .receipt
1,409,091✔
762
                        .events
1,409,091✔
763
                        .iter()
1,409,091✔
764
                        .all(|event| is_event_pox_addr_valid(mainnet, event));
1,409,091✔
765
                    if !all_events_valid {
1,409,091✔
UNCOV
766
                        Some((
×
UNCOV
767
                            format!("Problematic tx {i}: contains invalid pox address"),
×
UNCOV
768
                            ValidateRejectCode::ProblematicTransaction,
×
UNCOV
769
                        ))
×
770
                    } else {
771
                        None
1,409,091✔
772
                    }
773
                }
UNCOV
774
                TransactionResult::Skipped(s) => Some((
×
UNCOV
775
                    format!("tx {i} skipped: {}", s.error),
×
UNCOV
776
                    ValidateRejectCode::BadTransaction,
×
UNCOV
777
                )),
×
UNCOV
778
                TransactionResult::ProcessingError(e) => Some((
×
UNCOV
779
                    format!("Error processing tx {i}: {}", e.error),
×
UNCOV
780
                    ValidateRejectCode::BadTransaction,
×
UNCOV
781
                )),
×
UNCOV
782
                TransactionResult::Problematic(p) => Some((
×
UNCOV
783
                    format!("Problematic tx {i}: {}", p.error),
×
UNCOV
784
                    ValidateRejectCode::ProblematicTransaction,
×
UNCOV
785
                )),
×
786
            };
787
            if let Some((reason, reject_code)) = reason {
1,409,091✔
788
                warn!(
10✔
789
                    "Rejected block proposal";
790
                    "reason" => %reason,
791
                    "tx" => ?tx,
792
                );
793
                return Err(BlockValidateRejectReason {
10✔
794
                    reason,
10✔
795
                    reason_code: reject_code,
10✔
796
                    failed_txid: Some(tx.txid()),
10✔
797
                });
10✔
798
            }
1,409,081✔
799
        }
800

801
        let mut block = builder.mine_nakamoto_block(&mut tenure_tx, burn_chain_height);
37,541✔
802
        // Override the block version with the one from the proposal. This must be
803
        // done before computing the block hash, because the block hash includes the
804
        // version in its computation.
805
        block.header.version = self.block.header.version;
37,541✔
806
        let size = builder.get_bytes_so_far();
37,541✔
807
        let cost = builder.tenure_finish(tenure_tx)?;
37,541✔
808

809
        // Clone signatures from block proposal
810
        // These have already been validated by `validate_nakamoto_block_burnchain()``
811
        block.header.miner_signature = self.block.header.miner_signature.clone();
37,541✔
812
        block
37,541✔
813
            .header
37,541✔
814
            .signer_signature
37,541✔
815
            .clone_from(&self.block.header.signer_signature);
37,541✔
816

817
        // Assuming `tx_merkle_root` has been checked we don't need to hash the whole block
818
        let expected_block_header_hash = self.block.header.block_hash();
37,541✔
819
        let computed_block_header_hash = block.header.block_hash();
37,541✔
820

821
        if computed_block_header_hash != expected_block_header_hash {
37,541✔
822
            warn!(
×
823
                "Rejected block proposal";
824
                "reason" => "Block hash is not as expected",
825
                "expected_block_header_hash" => %expected_block_header_hash,
826
                "computed_block_header_hash" => %computed_block_header_hash,
827
                "expected_block" => ?self.block,
828
                "computed_block" => ?block,
829
            );
UNCOV
830
            return Err(BlockValidateRejectReason {
×
UNCOV
831
                reason: "Block hash is not as expected".into(),
×
UNCOV
832
                reason_code: ValidateRejectCode::BadBlockHash,
×
UNCOV
833
                failed_txid: None,
×
UNCOV
834
            });
×
835
        }
37,541✔
836

837
        let validation_time_ms = u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX);
37,541✔
838

839
        info!(
37,541✔
840
            "Participant: validated anchored block";
841
            "block_header_hash" => %computed_block_header_hash,
842
            "height" => block.header.chain_length,
37,541✔
843
            "tx_count" => block.txs.len(),
37,541✔
844
            "parent_stacks_block_id" => %block.header.parent_block_id,
845
            "block_size" => size,
37,541✔
846
            "execution_cost" => %cost,
847
            "validation_time_ms" => validation_time_ms,
37,541✔
848
            "tx_fees_microstacks" => block.txs.iter().fold(0, |agg: u64, tx| {
1,409,091✔
849
                agg.saturating_add(tx.get_tx_fee())
1,409,091✔
850
            })
1,409,091✔
851
        );
852

853
        let replay_tx_hash = Self::tx_replay_hash(&self.replay_txs);
37,541✔
854

855
        Ok(BlockValidateOk {
37,541✔
856
            signer_signature_hash: block.header.signer_signature_hash(),
37,541✔
857
            cost,
37,541✔
858
            size,
37,541✔
859
            validation_time_ms,
37,541✔
860
            replay_tx_hash,
37,541✔
861
            replay_tx_exhausted,
37,541✔
862
        })
37,541✔
863
    }
38,223✔
864

865
    pub fn tx_replay_hash(replay_txs: &Option<Vec<StacksTransaction>>) -> Option<u64> {
86,631✔
866
        replay_txs.as_ref().map(|txs| {
86,631✔
867
            let mut hasher = DefaultHasher::new();
2,300✔
868
            txs.hash(&mut hasher);
2,300✔
869
            hasher.finish()
2,300✔
870
        })
2,300✔
871
    }
86,631✔
872

873
    /// Validate the block against the replay set.
874
    ///
875
    /// Returns a boolean indicating whether this block exhausts the replay set.
876
    ///
877
    /// Returns `false` if there is no replay set.
878
    fn validate_replay(
37,651✔
879
        &self,
37,651✔
880
        parent_stacks_header: &StacksHeaderInfo,
37,651✔
881
        tenure_change: Option<&StacksTransaction>,
37,651✔
882
        coinbase: Option<&StacksTransaction>,
37,651✔
883
        tenure_cause: MinerTenureInfoCause,
37,651✔
884
        // not directly used; used as a handle to open other chainstates
37,651✔
885
        chainstate_handle: &StacksChainState,
37,651✔
886
        burn_dbconn: &SortitionHandleConn,
37,651✔
887
    ) -> Result<bool, BlockValidateRejectReason> {
37,651✔
888
        let mut replay_txs_maybe: Option<VecDeque<StacksTransaction>> =
37,651✔
889
            self.replay_txs.clone().map(|txs| txs.into());
37,651✔
890

891
        let Some(ref mut replay_txs) = replay_txs_maybe else {
37,651✔
892
            return Ok(false);
36,571✔
893
        };
894

895
        let mut replay_builder = NakamotoBlockBuilder::new(
1,080✔
896
            &parent_stacks_header,
1,080✔
897
            &self.block.header.consensus_hash,
1,080✔
898
            self.block.header.burn_spent,
1,080✔
899
            tenure_change,
1,080✔
900
            coinbase,
1,080✔
901
            self.block.header.pox_treatment.len(),
1,080✔
902
            None,
1,080✔
903
            None,
1,080✔
904
            Some(self.block.header.timestamp),
1,080✔
905
            u64::from(DEFAULT_MAX_TENURE_BYTES),
1,080✔
UNCOV
906
        )?;
×
907
        let (mut replay_chainstate, _) = chainstate_handle.reopen()?;
1,080✔
908
        let mut replay_miner_tenure_info =
1,080✔
909
            replay_builder.load_tenure_info(&mut replay_chainstate, &burn_dbconn, tenure_cause)?;
1,080✔
910
        let mut replay_tenure_tx =
1,080✔
911
            replay_builder.tenure_begin(&burn_dbconn, &mut replay_miner_tenure_info)?;
1,080✔
912

913
        let mut total_receipts = 0;
1,080✔
914
        for (i, tx) in self.block.txs.iter().enumerate() {
1,990✔
915
            let tx_len = tx.tx_len();
1,990✔
916

917
            // If a list of replay transactions is set, this transaction must be the next
918
            // mineable transaction from this list.
919
            loop {
920
                if matches!(
610✔
921
                    tx.payload,
2,050✔
922
                    TransactionPayload::TenureChange(..) | TransactionPayload::Coinbase(..)
923
                ) {
924
                    // Allow this to happen, tenure extend checks happen elsewhere.
925
                    break;
1,440✔
926
                }
610✔
927
                fault_injection_reject_replay_txs()?;
610✔
928
                let Some(replay_tx) = replay_txs.pop_front() else {
530✔
929
                    // During transaction replay, we expect that the block only
930
                    // contains transactions from the replay set. Thus, if we're here,
931
                    // the block contains a transaction that is not in the replay set,
932
                    // and we should reject the block.
UNCOV
933
                    warn!("Rejected block proposal. Block contains transactions beyond the replay set.";
×
UNCOV
934
                        "txid" => %tx.txid(),
×
UNCOV
935
                        "tx_index" => i,
×
936
                    );
UNCOV
937
                    return Err(BlockValidateRejectReason {
×
UNCOV
938
                        reason_code: ValidateRejectCode::InvalidTransactionReplay,
×
UNCOV
939
                        reason: "Block contains transactions beyond the replay set".into(),
×
UNCOV
940
                        failed_txid: Some(tx.txid()),
×
UNCOV
941
                    });
×
942
                };
943
                if replay_tx.txid() == tx.txid() {
530✔
944
                    break;
440✔
945
                }
90✔
946

947
                // The included tx doesn't match the next tx in the
948
                // replay set. Check to see if the tx is skipped because
949
                // it was unmineable.
950
                let tx_result = replay_builder.try_mine_tx_with_len(
90✔
951
                    &mut replay_tenure_tx,
90✔
952
                    &replay_tx,
90✔
953
                    replay_tx.tx_len(),
90✔
954
                    &BlockLimitFunction::NO_LIMIT_HIT,
90✔
955
                    None,
90✔
956
                    &mut total_receipts,
90✔
957
                );
958
                match tx_result {
90✔
UNCOV
959
                    TransactionResult::Skipped(TransactionSkipped { error, .. })
×
960
                    | TransactionResult::ProcessingError(TransactionError { error, .. })
60✔
UNCOV
961
                    | TransactionResult::Problematic(TransactionProblematic { error, .. }) => {
×
962
                        // The tx wasn't able to be mined. Check the underlying error, to
963
                        // see if we should reject the block or allow the tx to be
964
                        // dropped from the replay set.
965

UNCOV
966
                        match error {
×
967
                            ChainError::CostOverflowError(..)
968
                            | ChainError::BlockTooBigError
969
                            | ChainError::BlockCostLimitError
970
                            | ChainError::ClarityError(ClarityError::CostError(..)) => {
971
                                // block limit reached; add tx back to replay set.
972
                                // BUT we know that the block should have ended at this point, so
973
                                // return an error.
UNCOV
974
                                let txid = replay_tx.txid();
×
UNCOV
975
                                replay_txs.push_front(replay_tx);
×
976

UNCOV
977
                                warn!("Rejecting block proposal. Next replay tx exceeds cost limits, so should have been in the next block.";
×
978
                                    "error" => %error,
979
                                    "txid" => %txid,
980
                                );
981

UNCOV
982
                                return Err(BlockValidateRejectReason {
×
UNCOV
983
                                    reason_code: ValidateRejectCode::InvalidTransactionReplay,
×
UNCOV
984
                                    reason: "Next replay tx exceeds cost limits, so should have been in the next block.".into(),
×
UNCOV
985
                                    failed_txid: None,
×
UNCOV
986
                                });
×
987
                            }
988
                            _ => {
989
                                info!("During replay block validation, allowing problematic tx to be dropped";
60✔
990
                                    "txid" => %replay_tx.txid(),
60✔
991
                                    "error" => %error,
992
                                );
993
                                // it's ok, drop it
994
                                continue;
60✔
995
                            }
996
                        }
997
                    }
998
                    TransactionResult::Success(_) => {
999
                        // Tx should have been included
1000
                        warn!("Rejected block proposal. Block doesn't contain replay transaction that should have been included.";
30✔
1001
                            "block_txid" => %tx.txid(),
30✔
1002
                            "block_tx_index" => i,
30✔
1003
                            "replay_txid" => %replay_tx.txid(),
30✔
1004
                        );
1005
                        return Err(BlockValidateRejectReason {
30✔
1006
                            reason_code: ValidateRejectCode::InvalidTransactionReplay,
30✔
1007
                            reason: "Transaction is not in the replay set".into(),
30✔
1008
                            failed_txid: Some(tx.txid()),
30✔
1009
                        });
30✔
1010
                    }
1011
                };
1012
            }
1013

1014
            // Apply the block's transaction to our block builder, but we don't
1015
            // actually care about the result - that happens in the main
1016
            // validation check.
1017
            let _tx_result = replay_builder.try_mine_tx_with_len(
1,880✔
1018
                &mut replay_tenure_tx,
1,880✔
1019
                tx,
1,880✔
1020
                tx_len,
1,880✔
1021
                &BlockLimitFunction::NO_LIMIT_HIT,
1,880✔
1022
                None,
1,880✔
1023
                &mut total_receipts,
1,880✔
1024
            );
1025
        }
1026

1027
        let no_replay_txs_remaining = replay_txs.is_empty();
970✔
1028

1029
        // Now, we need to check if the remaining replay transactions are unmineable.
1030
        let only_unmineable_remaining = !replay_txs.is_empty()
970✔
1031
            && replay_txs.iter().all(|tx| {
900✔
1032
                let tx_result = replay_builder.try_mine_tx_with_len(
900✔
1033
                    &mut replay_tenure_tx,
900✔
1034
                    &tx,
900✔
1035
                    tx.tx_len(),
900✔
1036
                    &BlockLimitFunction::NO_LIMIT_HIT,
900✔
1037
                    None,
900✔
1038
                    &mut total_receipts,
900✔
1039
                );
1040
                match tx_result {
900✔
1041
                    TransactionResult::Skipped(TransactionSkipped { error, .. })
60✔
1042
                    | TransactionResult::ProcessingError(TransactionError { error, .. })
460✔
1043
                    | TransactionResult::Problematic(TransactionProblematic { error, .. }) => {
40✔
1044
                        // If it's just a cost error, it's not unmineable.
1045
                        !matches!(
500✔
UNCOV
1046
                            error,
×
1047
                            ChainError::CostOverflowError(..)
1048
                                | ChainError::BlockTooBigError
1049
                                | ChainError::ClarityError(ClarityError::CostError(..))
1050
                                | ChainError::BlockCostLimitError
1051
                        )
1052
                    }
1053
                    TransactionResult::Success(_) => {
1054
                        // The tx could have been included, but wasn't. This is ok, but we
1055
                        // haven't exhausted the replay set.
1056
                        false
340✔
1057
                    }
1058
                }
1059
            });
900✔
1060

1061
        Ok(no_replay_txs_remaining || only_unmineable_remaining)
970✔
1062
    }
37,651✔
1063
}
1064

1065
#[derive(Clone, Default)]
1066
pub struct RPCBlockProposalRequestHandler {
1067
    pub block_proposal: Option<NakamotoBlockProposal>,
1068
    pub auth: Option<String>,
1069
}
1070

1071
impl RPCBlockProposalRequestHandler {
1072
    pub fn new(auth: Option<String>) -> Self {
1,132,839✔
1073
        Self {
1,132,839✔
1074
            block_proposal: None,
1,132,839✔
1075
            auth,
1,132,839✔
1076
        }
1,132,839✔
1077
    }
1,132,839✔
1078

1079
    /// Decode a JSON-encoded block proposal
1080
    fn parse_json(body: &[u8]) -> Result<NakamotoBlockProposal, Error> {
107,635✔
1081
        serde_json::from_slice(body)
107,635✔
1082
            .map_err(|e| Error::DecodeError(format!("Failed to parse body: {e}")))
107,635✔
1083
    }
107,635✔
1084
}
1085

1086
/// Decode the HTTP request
1087
impl HttpRequest for RPCBlockProposalRequestHandler {
1088
    fn verb(&self) -> &'static str {
1,132,838✔
1089
        "POST"
1,132,838✔
1090
    }
1,132,838✔
1091

1092
    fn path_regex(&self) -> Regex {
2,265,678✔
1093
        Regex::new(r#"^/v3/block_proposal$"#).unwrap()
2,265,678✔
1094
    }
2,265,678✔
1095

1096
    fn metrics_identifier(&self) -> &str {
107,634✔
1097
        "/v3/block_proposal"
107,634✔
1098
    }
107,634✔
1099

1100
    /// Try to decode this request.
1101
    /// There's nothing to load here, so just make sure the request is well-formed.
1102
    fn try_parse_request(
107,646✔
1103
        &mut self,
107,646✔
1104
        preamble: &HttpRequestPreamble,
107,646✔
1105
        _captures: &Captures,
107,646✔
1106
        query: Option<&str>,
107,646✔
1107
        body: &[u8],
107,646✔
1108
    ) -> Result<HttpRequestContents, Error> {
107,646✔
1109
        // If no authorization is set, then the block proposal endpoint is not enabled
1110
        let Some(password) = &self.auth else {
107,646✔
UNCOV
1111
            return Err(Error::Http(400, "Bad Request.".into()));
×
1112
        };
1113
        let Some(auth_header) = preamble.headers.get("authorization") else {
107,646✔
1114
            return Err(Error::Http(401, "Unauthorized".into()));
11✔
1115
        };
1116
        if auth_header != password {
107,635✔
1117
            return Err(Error::Http(401, "Unauthorized".into()));
×
1118
        }
107,635✔
1119
        if preamble.get_content_length() == 0 {
107,635✔
1120
            return Err(Error::DecodeError(
×
1121
                "Invalid Http request: expected non-zero-length body for block proposal endpoint"
×
UNCOV
1122
                    .to_string(),
×
UNCOV
1123
            ));
×
1124
        }
107,635✔
1125
        if preamble.get_content_length() > MAX_PAYLOAD_LEN {
107,635✔
UNCOV
1126
            return Err(Error::DecodeError(
×
UNCOV
1127
                "Invalid Http request: BlockProposal body is too big".to_string(),
×
UNCOV
1128
            ));
×
1129
        }
107,635✔
1130

1131
        let block_proposal = match preamble.content_type {
107,635✔
1132
            Some(HttpContentType::JSON) => Self::parse_json(body)?,
107,635✔
1133
            Some(_) => {
UNCOV
1134
                return Err(Error::DecodeError(
×
UNCOV
1135
                    "Wrong Content-Type for block proposal; expected application/json".to_string(),
×
UNCOV
1136
                ))
×
1137
            }
1138
            None => {
UNCOV
1139
                return Err(Error::DecodeError(
×
UNCOV
1140
                    "Missing Content-Type for block proposal".to_string(),
×
UNCOV
1141
                ))
×
1142
            }
1143
        };
1144

1145
        if block_proposal.block.is_shadow_block() {
107,635✔
UNCOV
1146
            return Err(Error::DecodeError(
×
UNCOV
1147
                "Shadow blocks cannot be submitted for validation".to_string(),
×
UNCOV
1148
            ));
×
1149
        }
107,635✔
1150

1151
        self.block_proposal = Some(block_proposal);
107,635✔
1152
        Ok(HttpRequestContents::new().query_string(query))
107,635✔
1153
    }
107,646✔
1154
}
1155

1156
struct ProposalThreadInfo {
1157
    sortdb: SortitionDB,
1158
    chainstate: StacksChainState,
1159
    receiver: Box<dyn ProposalCallbackReceiver>,
1160
}
1161

1162
impl RPCRequestHandler for RPCBlockProposalRequestHandler {
1163
    /// Reset internal state
1164
    fn restart(&mut self) {
107,646✔
1165
        self.block_proposal = None
107,646✔
1166
    }
107,646✔
1167

1168
    /// Make the response
1169
    fn try_handle_request(
107,634✔
1170
        &mut self,
107,634✔
1171
        preamble: HttpRequestPreamble,
107,634✔
1172
        _contents: HttpRequestContents,
107,634✔
1173
        node: &mut StacksNodeState,
107,634✔
1174
    ) -> Result<(HttpResponsePreamble, HttpResponseContents), NetError> {
107,634✔
1175
        let block_proposal = self
107,634✔
1176
            .block_proposal
107,634✔
1177
            .take()
107,634✔
1178
            .ok_or(NetError::SendError("`block_proposal` not set".into()))?;
107,634✔
1179

1180
        info!(
107,634✔
1181
            "Received block proposal request";
1182
            "signer_signature_hash" => %block_proposal.block.header.signer_signature_hash(),
107,634✔
1183
            "block_header_hash" => %block_proposal.block.header.block_hash(),
107,634✔
1184
            "height" => block_proposal.block.header.chain_length,
107,634✔
1185
            "tx_count" => block_proposal.block.txs.len(),
107,634✔
1186
            "parent_stacks_block_id" => %block_proposal.block.header.parent_block_id,
1187
        );
1188

1189
        let res = node.with_node_state(|network, sortdb, chainstate, _mempool, rpc_args| {
107,634✔
1190
            if network.is_proposal_thread_running() {
107,634✔
1191
                return Err((
69,400✔
1192
                    TOO_MANY_REQUESTS_STATUS,
69,400✔
1193
                    NetError::SendError("Proposal currently being evaluated".into()),
69,400✔
1194
                ));
69,400✔
1195
            }
38,234✔
1196

1197
            if block_proposal
38,234✔
1198
                .block
38,234✔
1199
                .header
38,234✔
1200
                .timestamp
38,234✔
1201
                .saturating_add(network.get_connection_opts().block_proposal_max_age_secs)
38,234✔
1202
                < get_epoch_time_secs()
38,234✔
1203
            {
1204
                return Err((
11✔
1205
                    422,
11✔
1206
                    NetError::SendError("Block proposal is too old to process.".into()),
11✔
1207
                ));
11✔
1208
            }
38,223✔
1209

1210
            let (chainstate, _) = chainstate.reopen().map_err(|e| (400, NetError::from(e)))?;
38,223✔
1211
            let sortdb = sortdb.reopen().map_err(|e| (400, NetError::from(e)))?;
38,223✔
1212
            let receiver = rpc_args
38,223✔
1213
                .event_observer
38,223✔
1214
                .and_then(|observer| observer.get_proposal_callback_receiver())
38,223✔
1215
                .ok_or_else(|| {
38,223✔
UNCOV
1216
                    (
×
UNCOV
1217
                        400,
×
UNCOV
1218
                        NetError::SendError(
×
UNCOV
1219
                            "No `observer` registered for receiving proposal callbacks".into(),
×
UNCOV
1220
                        ),
×
UNCOV
1221
                    )
×
UNCOV
1222
                })?;
×
1223
            let thread_info = block_proposal
38,223✔
1224
                .spawn_validation_thread(
38,223✔
1225
                    sortdb,
38,223✔
1226
                    chainstate,
38,223✔
1227
                    receiver,
38,223✔
1228
                    network.get_connection_opts(),
38,223✔
1229
                )
1230
                .map_err(|_e| {
38,223✔
UNCOV
1231
                    (
×
UNCOV
1232
                        TOO_MANY_REQUESTS_STATUS,
×
UNCOV
1233
                        NetError::SendError(
×
UNCOV
1234
                            "IO error while spawning proposal callback thread".into(),
×
UNCOV
1235
                        ),
×
UNCOV
1236
                    )
×
UNCOV
1237
                })?;
×
1238
            network.set_proposal_thread(thread_info);
38,223✔
1239
            Ok(())
38,223✔
1240
        });
107,634✔
1241

1242
        match res {
107,634✔
1243
            Ok(_) => {
1244
                let preamble = HttpResponsePreamble::accepted_json(&preamble);
38,223✔
1245
                let body = HttpResponseContents::try_from_json(&serde_json::json!({
38,223✔
1246
                    "result": "Accepted",
38,223✔
1247
                    "message": "Block proposal is processing, result will be returned via the event observer"
38,223✔
1248
                }))?;
38,223✔
1249
                Ok((preamble, body))
38,223✔
1250
            }
1251
            Err((code, err)) => {
69,411✔
1252
                let preamble = HttpResponsePreamble::error_json(code, http_reason(code));
69,411✔
1253
                let body = HttpResponseContents::try_from_json(&serde_json::json!({
69,411✔
1254
                    "result": "Error",
69,411✔
1255
                    "message": format!("Could not process block proposal request: {err}")
69,411✔
1256
                }))?;
69,411✔
1257
                Ok((preamble, body))
69,411✔
1258
            }
1259
        }
1260
    }
107,634✔
1261
}
1262

1263
/// Decode the HTTP response
1264
impl HttpResponse for RPCBlockProposalRequestHandler {
1265
    fn try_parse_response(
3✔
1266
        &self,
3✔
1267
        preamble: &HttpResponsePreamble,
3✔
1268
        body: &[u8],
3✔
1269
    ) -> Result<HttpResponsePayload, Error> {
3✔
1270
        let response: BlockProposalResponse = parse_json(preamble, body)?;
3✔
1271
        HttpResponsePayload::try_from_json(response)
3✔
1272
    }
3✔
1273
}
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