• 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

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

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

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

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

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

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

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

102
pub static TOO_MANY_REQUESTS_STATUS: u16 = 429;
103

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

112
fn hex_ser_block<S: serde::Serializer>(b: &NakamotoBlock, s: S) -> Result<S::Ok, S::Error> {
31,486✔
113
    let inst = to_hex(&b.serialize_to_vec());
31,486✔
114
    s.serialize_str(inst.as_str())
31,486✔
115
}
31,486✔
116

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

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

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

143
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
144
pub enum BlockProposalResult {
145
    Accepted,
146
    Error,
147
}
148

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

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

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

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

198
impl From<Result<BlockValidateOk, BlockValidateReject>> for BlockValidateResponse {
199
    fn from(value: Result<BlockValidateOk, BlockValidateReject>) -> Self {
7,290✔
200
        match value {
7,290✔
201
            Ok(o) => BlockValidateResponse::Ok(o),
7,154✔
202
            Err(e) => BlockValidateResponse::Reject(e),
136✔
203
        }
204
    }
7,290✔
205
}
206

207
impl BlockValidateResponse {
208
    /// Get the signer signature hash from the response
209
    pub fn signer_signature_hash(&self) -> &Sha512Trunc256Sum {
51,624✔
210
        match self {
51,624✔
211
            BlockValidateResponse::Ok(o) => &o.signer_signature_hash,
50,640✔
212
            BlockValidateResponse::Reject(r) => &r.signer_signature_hash,
984✔
213
        }
214
    }
51,624✔
215
}
216

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

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

234
#[cfg(any(test, feature = "testing"))]
235
fn fault_injection_validation_delay() {
36,443✔
236
    let delay = TEST_VALIDATE_DELAY_DURATION_SECS.get();
36,443✔
237
    if delay == 0 {
36,443✔
238
        return;
35,923✔
239
    }
520✔
240
    warn!("Sleeping for {} seconds to simulate slow processing", delay);
520✔
241
    thread::sleep(Duration::from_secs(delay));
520✔
242
}
36,443✔
243

244
#[cfg(not(any(test, feature = "testing")))]
245
fn fault_injection_validation_delay() {}
246

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

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

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

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

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

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

334
    let pox_addr_value = if let Value::Optional(data) = pox_addr_tuple {
799✔
335
        match data.data {
45✔
336
            None => return true,
31✔
337
            Some(ref inner) => inner.as_ref(),
14✔
338
        }
339
    } else {
340
        pox_addr_tuple
754✔
341
    };
342

343
    PoxAddress::try_from_pox_tuple(is_mainnet, pox_addr_value).is_some()
768✔
344
}
3,403,528✔
345

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

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

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

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

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

511
            Self::check_block_builds_on_highest_block_in_tenure(
23,760✔
512
                chainstate,
23,760✔
513
                sortdb,
23,760✔
514
                &parent_header.consensus_hash,
23,760✔
515
                &block.header.parent_block_id,
23,760✔
UNCOV
516
            )?;
×
517
        }
518
        Ok(())
35,893✔
519
    }
36,113✔
520

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

547
        fault_injection_validation_delay();
36,443✔
548

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

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

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

589
        let burn_view_consensus_hash =
36,123✔
590
            NakamotoChainState::get_block_burn_view(sortdb, &self.block, &parent_stacks_header)?;
36,213✔
591
        let sort_tip =
36,123✔
592
            SortitionDB::get_block_snapshot_consensus(sortdb.conn(), &burn_view_consensus_hash)?
36,123✔
593
                .ok_or_else(|| BlockValidateRejectReason {
36,123✔
UNCOV
594
                    reason_code: ValidateRejectCode::NoSuchTenure,
×
UNCOV
595
                    reason: "Failed to find sortition for block tenure".to_string(),
×
UNCOV
596
                    failed_txid: None,
×
UNCOV
597
                })?;
×
598

599
        let burn_dbconn: SortitionHandleConn = sortdb.index_handle(&sort_tip.sortition_id);
36,123✔
600
        let db_handle = sortdb.index_handle(&sort_tip.sortition_id);
36,123✔
601

602
        // (For the signer)
603
        // Verify that the block's tenure is on the canonical sortition history
604
        Self::check_block_has_valid_tenure(&db_handle, &self.block.header.consensus_hash)?;
36,123✔
605

606
        // (For the signer)
607
        // Verify that this block's parent is the highest such block we can build off of
608
        Self::check_block_has_valid_parent(chainstate, sortdb, &self.block)?;
36,113✔
609

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

627
        // Static validation checks
628
        NakamotoChainState::validate_normal_nakamoto_block_burnchain(
35,893✔
629
            chainstate.nakamoto_blocks_db(),
35,893✔
630
            &db_handle,
35,893✔
631
            expected_burn_opt,
35,893✔
632
            &self.block,
35,893✔
633
            mainnet,
35,893✔
634
            self.chain_id,
35,893✔
635
        )?;
20✔
636

637
        // Validate txs against chainstate
638

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

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

689
        let tenure_change = self
35,871✔
690
            .block
35,871✔
691
            .txs
35,871✔
692
            .iter()
35,871✔
693
            .find(|tx| matches!(tx.payload, TransactionPayload::TenureChange(..)));
1,385,591✔
694
        let coinbase = self
35,871✔
695
            .block
35,871✔
696
            .txs
35,871✔
697
            .iter()
35,871✔
698
            .find(|tx| matches!(tx.payload, TransactionPayload::Coinbase(..)));
1,410,631✔
699
        let tenure_cause = tenure_change
35,871✔
700
            .and_then(|tx| match &tx.payload {
35,871✔
701
                TransactionPayload::TenureChange(tc) => Some(MinerTenureInfoCause::from(tc)),
26,330✔
UNCOV
702
                _ => None,
×
703
            })
26,330✔
704
            .unwrap_or_else(|| MinerTenureInfoCause::NoTenureChange);
35,871✔
705

706
        let replay_tx_exhausted = self.validate_replay(
35,871✔
707
            &parent_stacks_header,
35,871✔
708
            tenure_change,
35,871✔
709
            coinbase,
35,871✔
710
            tenure_cause,
35,871✔
711
            chainstate,
35,871✔
712
            &burn_dbconn,
35,871✔
713
        )?;
110✔
714

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

728
        let mut miner_tenure_info =
35,761✔
729
            builder.load_tenure_info(chainstate, &burn_dbconn, tenure_cause)?;
35,761✔
730
        let burn_chain_height = miner_tenure_info.burn_tip_height;
35,761✔
731
        let mut tenure_tx = builder.tenure_begin(&burn_dbconn, &mut miner_tenure_info)?;
35,761✔
732

733
        let block_deadline = Instant::now() + Duration::from_secs(timeout_secs);
35,761✔
734
        let mut receipts_total = 0u64;
35,761✔
735
        for (i, tx) in self.block.txs.iter().enumerate() {
1,410,381✔
736
            let remaining = block_deadline.saturating_duration_since(Instant::now());
1,410,381✔
737

738
            let tx_len = tx.tx_len();
1,410,381✔
739

740
            if max_tx_mem_bytes > 0 {
1,410,381✔
741
                if let Some(cb) =
1,410,381✔
742
                    crate::chainstate::nakamoto::miner::make_mem_abort_callback(max_tx_mem_bytes)
1,410,381✔
743
                {
1,410,381✔
744
                    tenure_tx.set_abort_callback(cb);
1,410,381✔
745
                }
1,410,381✔
NEW
746
            }
×
747

748
            let tx_result = builder.try_mine_tx_with_len(
1,410,381✔
749
                &mut tenure_tx,
1,410,381✔
750
                tx,
1,410,381✔
751
                tx_len,
1,410,381✔
752
                &BlockLimitFunction::NO_LIMIT_HIT,
1,410,381✔
753
                Some(remaining),
1,410,381✔
754
                &mut receipts_total,
1,410,381✔
755
            );
756
            let reason = match tx_result {
1,410,381✔
757
                TransactionResult::Success(success_result) => {
1,410,381✔
758
                    let all_events_valid = success_result
1,410,381✔
759
                        .receipt
1,410,381✔
760
                        .events
1,410,381✔
761
                        .iter()
1,410,381✔
762
                        .all(|event| is_event_pox_addr_valid(mainnet, event));
1,410,381✔
763
                    if !all_events_valid {
1,410,381✔
UNCOV
764
                        Some((
×
UNCOV
765
                            format!("Problematic tx {i}: contains invalid pox address"),
×
UNCOV
766
                            ValidateRejectCode::ProblematicTransaction,
×
UNCOV
767
                        ))
×
768
                    } else {
769
                        None
1,410,381✔
770
                    }
771
                }
UNCOV
772
                TransactionResult::Skipped(s) => Some((
×
UNCOV
773
                    format!("tx {i} skipped: {}", s.error),
×
UNCOV
774
                    ValidateRejectCode::BadTransaction,
×
UNCOV
775
                )),
×
UNCOV
776
                TransactionResult::ProcessingError(e) => Some((
×
UNCOV
777
                    format!("Error processing tx {i}: {}", e.error),
×
UNCOV
778
                    ValidateRejectCode::BadTransaction,
×
UNCOV
779
                )),
×
UNCOV
780
                TransactionResult::Problematic(p) => Some((
×
UNCOV
781
                    format!("Problematic tx {i}: {}", p.error),
×
UNCOV
782
                    ValidateRejectCode::ProblematicTransaction,
×
UNCOV
783
                )),
×
784
            };
785
            if let Some((reason, reject_code)) = reason {
1,410,381✔
UNCOV
786
                warn!(
×
787
                    "Rejected block proposal";
788
                    "reason" => %reason,
789
                    "tx" => ?tx,
790
                );
791
                return Err(BlockValidateRejectReason {
×
UNCOV
792
                    reason,
×
UNCOV
793
                    reason_code: reject_code,
×
UNCOV
794
                    failed_txid: Some(tx.txid()),
×
UNCOV
795
                });
×
796
            }
1,410,381✔
797
        }
798

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

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

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

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

835
        let validation_time_ms = u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX);
35,761✔
836

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

851
        let replay_tx_hash = Self::tx_replay_hash(&self.replay_txs);
35,761✔
852

853
        Ok(BlockValidateOk {
35,761✔
854
            signer_signature_hash: block.header.signer_signature_hash(),
35,761✔
855
            cost,
35,761✔
856
            size,
35,761✔
857
            validation_time_ms,
35,761✔
858
            replay_tx_hash,
35,761✔
859
            replay_tx_exhausted,
35,761✔
860
        })
35,761✔
861
    }
36,443✔
862

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

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

889
        let Some(ref mut replay_txs) = replay_txs_maybe else {
35,871✔
890
            return Ok(false);
34,761✔
891
        };
892

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

911
        let mut total_receipts = 0;
1,110✔
912
        for (i, tx) in self.block.txs.iter().enumerate() {
2,080✔
913
            let tx_len = tx.tx_len();
2,080✔
914

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

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

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

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

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

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

1025
        let no_replay_txs_remaining = replay_txs.is_empty();
1,000✔
1026

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

1059
        Ok(no_replay_txs_remaining || only_unmineable_remaining)
1,000✔
1060
    }
35,871✔
1061
}
1062

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

1069
impl RPCBlockProposalRequestHandler {
1070
    pub fn new(auth: Option<String>) -> Self {
1,125,750✔
1071
        Self {
1,125,750✔
1072
            block_proposal: None,
1,125,750✔
1073
            auth,
1,125,750✔
1074
        }
1,125,750✔
1075
    }
1,125,750✔
1076

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

1084
/// Decode the HTTP request
1085
impl HttpRequest for RPCBlockProposalRequestHandler {
1086
    fn verb(&self) -> &'static str {
1,125,749✔
1087
        "POST"
1,125,749✔
1088
    }
1,125,749✔
1089

1090
    fn path_regex(&self) -> Regex {
2,251,500✔
1091
        Regex::new(r#"^/v3/block_proposal$"#).unwrap()
2,251,500✔
1092
    }
2,251,500✔
1093

1094
    fn metrics_identifier(&self) -> &str {
104,804✔
1095
        "/v3/block_proposal"
104,804✔
1096
    }
104,804✔
1097

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

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

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

1149
        self.block_proposal = Some(block_proposal);
104,805✔
1150
        Ok(HttpRequestContents::new().query_string(query))
104,805✔
1151
    }
104,816✔
1152
}
1153

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

1160
impl RPCRequestHandler for RPCBlockProposalRequestHandler {
1161
    /// Reset internal state
1162
    fn restart(&mut self) {
104,816✔
1163
        self.block_proposal = None
104,816✔
1164
    }
104,816✔
1165

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

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

1187
        let res = node.with_node_state(|network, sortdb, chainstate, _mempool, rpc_args| {
104,804✔
1188
            if network.is_proposal_thread_running() {
104,804✔
1189
                return Err((
68,350✔
1190
                    TOO_MANY_REQUESTS_STATUS,
68,350✔
1191
                    NetError::SendError("Proposal currently being evaluated".into()),
68,350✔
1192
                ));
68,350✔
1193
            }
36,454✔
1194

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

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

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

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