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

stacks-network / stacks-core / 25903914664-1

15 May 2026 06:28AM UTC coverage: 47.122% (-38.8%) from 85.959%
25903914664-1

Pull #7199

github

94e391
web-flow
Merge 109f2828c into 1c7b8e6ac
Pull Request #7199: Feat: L1 and L2 early unlocks, updating signer

103343 of 219309 relevant lines covered (47.12%)

12880462.62 hits per line

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

80.7
/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> {
10,926✔
107
        Self::from_u8(value)
10,926✔
108
            .ok_or_else(|| CodecError::DeserializeError(format!("Unknown type prefix: {value}")))
10,926✔
109
    }
10,926✔
110
}
111

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

117
fn hex_deser_block<'de, D: serde::Deserializer<'de>>(d: D) -> Result<NakamotoBlock, D::Error> {
100,588✔
118
    let inst_str = String::deserialize(d)?;
100,588✔
119
    let bytes = hex_bytes(&inst_str).map_err(serde::de::Error::custom)?;
100,588✔
120
    NakamotoBlock::consensus_deserialize(&mut bytes.as_slice()).map_err(serde::de::Error::custom)
100,588✔
121
}
100,588✔
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 {
99✔
160
        let ce: ChainError = value.into();
99✔
161
        let reason_code = match ce {
99✔
162
            ChainError::DBError(db_error::NotFoundError) => ValidateRejectCode::NotFoundError,
81✔
163
            _ => ValidateRejectCode::ChainstateError,
18✔
164
        };
165
        Self {
99✔
166
            reason: format!("Chainstate Error: {ce}"),
99✔
167
            reason_code,
99✔
168
            failed_txid: None,
99✔
169
        }
99✔
170
    }
99✔
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 {
8,068✔
200
        match value {
8,068✔
201
            Ok(o) => BlockValidateResponse::Ok(o),
7,942✔
202
            Err(e) => BlockValidateResponse::Reject(e),
126✔
203
        }
204
    }
8,068✔
205
}
206

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

217
#[cfg(any(test, feature = "testing"))]
218
fn fault_injection_validation_stall(auth_token: Option<String>) {
36,318✔
219
    if TEST_VALIDATE_STALL.get().contains(&auth_token) {
36,318✔
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);
81✔
222
        while TEST_VALIDATE_STALL.get().contains(&auth_token) {
111,258✔
223
            std::thread::sleep(std::time::Duration::from_millis(10));
111,177✔
224
        }
111,177✔
225
        info!(
81✔
226
            "Block validation is no longer stalled due to testing directive. Continuing..."; "auth_token" => ?auth_token
227
        );
228
    }
36,237✔
229
}
36,318✔
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,318✔
236
    let delay = TEST_VALIDATE_DELAY_DURATION_SECS.get();
36,318✔
237
    if delay == 0 {
36,318✔
238
        return;
35,859✔
239
    }
459✔
240
    warn!("Sleeping for {} seconds to simulate slow processing", delay);
459✔
241
    thread::sleep(Duration::from_secs(delay));
459✔
242
}
36,318✔
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 {
90✔
252
            reason_code: ValidateRejectCode::InvalidTransactionReplay,
90✔
253
            reason: "Rejected by test flag".into(),
90✔
254
            failed_txid: None,
90✔
255
        })
90✔
256
    } else {
257
        Ok(())
540✔
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> {
702✔
279
    let Value::Response(ResponseData { committed, data }) = value else {
702✔
280
        return None;
×
281
    };
282
    if !committed {
702✔
283
        return None;
×
284
    }
702✔
285
    Some(data.as_ref())
702✔
286
}
702✔
287

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

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

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

343
    PoxAddress::try_from_pox_tuple(is_mainnet, pox_addr_value).is_some()
648✔
344
}
3,048,016✔
345

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

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

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

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

482
        if !is_tenure_start {
36,075✔
483
            // this is a well-formed block that is not the start of a tenure, so it must build
484
            // atop an existing block in its tenure.
485
            Self::check_block_builds_on_highest_block_in_tenure(
12,864✔
486
                chainstate,
12,864✔
487
                sortdb,
12,864✔
488
                &block.header.consensus_hash,
12,864✔
489
                &block.header.parent_block_id,
12,864✔
490
            )?;
189✔
491
        } else {
492
            // this is a tenure-start block, so it must build atop a parent which has the
493
            // highest height in the *previous* tenure.
494
            let parent_header = NakamotoChainState::get_block_header(
23,211✔
495
                chainstate.db(),
23,211✔
496
                &block.header.parent_block_id,
23,211✔
497
            )?
×
498
            .ok_or_else(|| BlockValidateRejectReason {
23,211✔
499
                reason_code: ValidateRejectCode::UnknownParent,
×
500
                reason: "No parent block".into(),
×
501
                failed_txid: None,
×
502
            })?;
×
503

504
            Self::check_block_builds_on_highest_block_in_tenure(
23,211✔
505
                chainstate,
23,211✔
506
                sortdb,
23,211✔
507
                &parent_header.consensus_hash,
23,211✔
508
                &block.header.parent_block_id,
23,211✔
509
            )?;
9✔
510
        }
511
        Ok(())
35,877✔
512
    }
36,075✔
513

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

539
        fault_injection_validation_delay();
36,318✔
540

541
        let mainnet = self.chain_id == CHAIN_ID_MAINNET;
36,318✔
542
        if self.chain_id != chainstate.chain_id || mainnet != chainstate.mainnet {
36,318✔
543
            warn!(
9✔
544
                "Rejected block proposal";
545
                "reason" => "Wrong network/chain_id",
546
                "expected_chain_id" => chainstate.chain_id,
9✔
547
                "expected_mainnet" => chainstate.mainnet,
9✔
548
                "received_chain_id" => self.chain_id,
9✔
549
                "received_mainnet" => mainnet,
9✔
550
            );
551
            return Err(BlockValidateRejectReason {
9✔
552
                reason_code: ValidateRejectCode::NetworkChainMismatch,
9✔
553
                reason: "Wrong network/chain_id".into(),
9✔
554
                failed_txid: None,
9✔
555
            });
9✔
556
        }
36,309✔
557

558
        // Check block version. If it's less than the compiled-in version, just emit a warning
559
        // because there's a new version of the node / signer binary available that really ought to
560
        // be used (hint, hint)
561
        if self.block.header.version != NAKAMOTO_BLOCK_VERSION {
36,309✔
562
            warn!("Proposed block has unexpected version. Upgrade your node and/or signer ASAP.";
×
563
                  "block.header.version" => %self.block.header.version,
564
                  "expected" => %NAKAMOTO_BLOCK_VERSION);
565
        }
36,309✔
566

567
        // open sortition view to the current burn view.
568
        // If the block has a TenureChange with an Extend cause, then the burn view is whatever is
569
        // indicated in the TenureChange.
570
        // Otherwise, it's the same as the block's parent's burn view.
571
        let parent_stacks_header = NakamotoChainState::get_block_header(
36,309✔
572
            chainstate.db(),
36,309✔
573
            &self.block.header.parent_block_id,
36,309✔
574
        )?
×
575
        .ok_or_else(|| BlockValidateRejectReason {
36,309✔
576
            reason_code: ValidateRejectCode::UnknownParent,
135✔
577
            reason: "Unknown parent block".into(),
135✔
578
            failed_txid: None,
135✔
579
        })?;
135✔
580

581
        let burn_view_consensus_hash =
36,093✔
582
            NakamotoChainState::get_block_burn_view(sortdb, &self.block, &parent_stacks_header)?;
36,174✔
583
        let sort_tip =
36,093✔
584
            SortitionDB::get_block_snapshot_consensus(sortdb.conn(), &burn_view_consensus_hash)?
36,093✔
585
                .ok_or_else(|| BlockValidateRejectReason {
36,093✔
586
                    reason_code: ValidateRejectCode::NoSuchTenure,
×
587
                    reason: "Failed to find sortition for block tenure".to_string(),
×
588
                    failed_txid: None,
×
589
                })?;
×
590

591
        let burn_dbconn: SortitionHandleConn = sortdb.index_handle(&sort_tip.sortition_id);
36,093✔
592
        let db_handle = sortdb.index_handle(&sort_tip.sortition_id);
36,093✔
593

594
        // (For the signer)
595
        // Verify that the block's tenure is on the canonical sortition history
596
        Self::check_block_has_valid_tenure(&db_handle, &self.block.header.consensus_hash)?;
36,093✔
597

598
        // (For the signer)
599
        // Verify that this block's parent is the highest such block we can build off of
600
        Self::check_block_has_valid_parent(chainstate, sortdb, &self.block)?;
36,084✔
601

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

619
        // Static validation checks
620
        NakamotoChainState::validate_normal_nakamoto_block_burnchain(
35,886✔
621
            chainstate.nakamoto_blocks_db(),
35,886✔
622
            &db_handle,
35,886✔
623
            expected_burn_opt,
35,886✔
624
            &self.block,
35,886✔
625
            mainnet,
35,886✔
626
            self.chain_id,
35,886✔
627
        )?;
18✔
628

629
        // Validate txs against chainstate
630

631
        // Validate the block's timestamp. It must be:
632
        // - Greater than the parent block's timestamp
633
        // - At most 15 seconds into the future
634
        if let StacksBlockHeaderTypes::Nakamoto(parent_nakamoto_header) =
31,377✔
635
            &parent_stacks_header.anchored_header
35,868✔
636
        {
637
            if self.block.header.timestamp <= parent_nakamoto_header.timestamp {
31,377✔
638
                warn!(
1✔
639
                    "Rejected block proposal";
640
                    "reason" => "Block timestamp is not greater than parent block",
641
                    "block_timestamp" => self.block.header.timestamp,
1✔
642
                    "parent_block_timestamp" => parent_nakamoto_header.timestamp,
1✔
643
                );
644
                return Err(BlockValidateRejectReason {
1✔
645
                    reason_code: ValidateRejectCode::InvalidTimestamp,
1✔
646
                    reason: "Block timestamp is not greater than parent block".into(),
1✔
647
                    failed_txid: None,
1✔
648
                });
1✔
649
            }
31,376✔
650
        }
4,491✔
651
        if self.block.header.timestamp > get_epoch_time_secs() + 15 {
35,867✔
652
            warn!(
1✔
653
                "Rejected block proposal";
654
                "reason" => "Block timestamp is too far into the future",
655
                "block_timestamp" => self.block.header.timestamp,
1✔
656
                "current_time" => get_epoch_time_secs(),
1✔
657
            );
658
            return Err(BlockValidateRejectReason {
1✔
659
                reason_code: ValidateRejectCode::InvalidTimestamp,
1✔
660
                reason: "Block timestamp is too far into the future".into(),
1✔
661
                failed_txid: None,
1✔
662
            });
1✔
663
        }
35,866✔
664

665
        if self.block.header.chain_length
35,866✔
666
            != parent_stacks_header.stacks_block_height.saturating_add(1)
35,866✔
667
        {
668
            warn!(
×
669
                "Rejected block proposal";
670
                "reason" => "Block height is non-contiguous with parent",
671
                "block_height" => self.block.header.chain_length,
×
672
                "parent_block_height" => parent_stacks_header.stacks_block_height,
×
673
            );
674
            return Err(BlockValidateRejectReason {
×
675
                reason_code: ValidateRejectCode::InvalidBlock,
×
676
                reason: "Block height is non-contiguous with parent".into(),
×
677
                failed_txid: None,
×
678
            });
×
679
        }
35,866✔
680

681
        let tenure_change = self
35,866✔
682
            .block
35,866✔
683
            .txs
35,866✔
684
            .iter()
35,866✔
685
            .find(|tx| matches!(tx.payload, TransactionPayload::TenureChange(..)));
1,244,872✔
686
        let coinbase = self
35,866✔
687
            .block
35,866✔
688
            .txs
35,866✔
689
            .iter()
35,866✔
690
            .find(|tx| matches!(tx.payload, TransactionPayload::Coinbase(..)));
1,269,298✔
691
        let tenure_cause = tenure_change
35,866✔
692
            .and_then(|tx| match &tx.payload {
35,866✔
693
                TransactionPayload::TenureChange(tc) => Some(MinerTenureInfoCause::from(tc)),
25,452✔
694
                _ => None,
×
695
            })
25,452✔
696
            .unwrap_or_else(|| MinerTenureInfoCause::NoTenureChange);
35,866✔
697

698
        let replay_tx_exhausted = self.validate_replay(
35,866✔
699
            &parent_stacks_header,
35,866✔
700
            tenure_change,
35,866✔
701
            coinbase,
35,866✔
702
            tenure_cause,
35,866✔
703
            chainstate,
35,866✔
704
            &burn_dbconn,
35,866✔
705
        )?;
117✔
706

707
        let mut builder = NakamotoBlockBuilder::new(
35,749✔
708
            &parent_stacks_header,
35,749✔
709
            &self.block.header.consensus_hash,
35,749✔
710
            self.block.header.burn_spent,
35,749✔
711
            tenure_change,
35,749✔
712
            coinbase,
35,749✔
713
            self.block.header.pox_treatment.len(),
35,749✔
714
            None,
35,749✔
715
            None,
35,749✔
716
            Some(self.block.header.timestamp),
35,749✔
717
            u64::from(DEFAULT_MAX_TENURE_BYTES),
35,749✔
718
        )?;
×
719

720
        let mut miner_tenure_info =
35,749✔
721
            builder.load_tenure_info(chainstate, &burn_dbconn, tenure_cause)?;
35,749✔
722
        let burn_chain_height = miner_tenure_info.burn_tip_height;
35,749✔
723
        let mut tenure_tx = builder.tenure_begin(&burn_dbconn, &mut miner_tenure_info)?;
35,749✔
724

725
        let block_deadline = Instant::now() + Duration::from_secs(timeout_secs);
35,749✔
726
        let mut receipts_total = 0u64;
35,749✔
727
        for (i, tx) in self.block.txs.iter().enumerate() {
1,269,037✔
728
            let remaining = block_deadline.saturating_duration_since(Instant::now());
1,269,037✔
729

730
            let tx_len = tx.tx_len();
1,269,037✔
731

732
            let tx_result = builder.try_mine_tx_with_len(
1,269,037✔
733
                &mut tenure_tx,
1,269,037✔
734
                tx,
1,269,037✔
735
                tx_len,
1,269,037✔
736
                &BlockLimitFunction::NO_LIMIT_HIT,
1,269,037✔
737
                Some(remaining),
1,269,037✔
738
                &mut receipts_total,
1,269,037✔
739
            );
740
            let reason = match tx_result {
1,269,037✔
741
                TransactionResult::Success(success_result) => {
1,269,037✔
742
                    let all_events_valid = success_result
1,269,037✔
743
                        .receipt
1,269,037✔
744
                        .events
1,269,037✔
745
                        .iter()
1,269,037✔
746
                        .all(|event| is_event_pox_addr_valid(mainnet, event));
1,269,037✔
747
                    if !all_events_valid {
1,269,037✔
748
                        Some((
×
749
                            format!("Problematic tx {i}: contains invalid pox address"),
×
750
                            ValidateRejectCode::ProblematicTransaction,
×
751
                        ))
×
752
                    } else {
753
                        None
1,269,037✔
754
                    }
755
                }
756
                TransactionResult::Skipped(s) => Some((
×
757
                    format!("tx {i} skipped: {}", s.error),
×
758
                    ValidateRejectCode::BadTransaction,
×
759
                )),
×
760
                TransactionResult::ProcessingError(e) => Some((
×
761
                    format!("Error processing tx {i}: {}", e.error),
×
762
                    ValidateRejectCode::BadTransaction,
×
763
                )),
×
764
                TransactionResult::Problematic(p) => Some((
×
765
                    format!("Problematic tx {i}: {}", p.error),
×
766
                    ValidateRejectCode::ProblematicTransaction,
×
767
                )),
×
768
            };
769
            if let Some((reason, reject_code)) = reason {
1,269,037✔
770
                warn!(
9✔
771
                    "Rejected block proposal";
772
                    "reason" => %reason,
773
                    "tx" => ?tx,
774
                );
775
                return Err(BlockValidateRejectReason {
9✔
776
                    reason,
9✔
777
                    reason_code: reject_code,
9✔
778
                    failed_txid: Some(tx.txid()),
9✔
779
                });
9✔
780
            }
1,269,028✔
781
        }
782

783
        let mut block = builder.mine_nakamoto_block(&mut tenure_tx, burn_chain_height);
35,740✔
784
        // Override the block version with the one from the proposal. This must be
785
        // done before computing the block hash, because the block hash includes the
786
        // version in its computation.
787
        block.header.version = self.block.header.version;
35,740✔
788
        let size = builder.get_bytes_so_far();
35,740✔
789
        let cost = builder.tenure_finish(tenure_tx)?;
35,740✔
790

791
        // Clone signatures from block proposal
792
        // These have already been validated by `validate_nakamoto_block_burnchain()``
793
        block.header.miner_signature = self.block.header.miner_signature.clone();
35,740✔
794
        block
35,740✔
795
            .header
35,740✔
796
            .signer_signature
35,740✔
797
            .clone_from(&self.block.header.signer_signature);
35,740✔
798

799
        // Assuming `tx_merkle_root` has been checked we don't need to hash the whole block
800
        let expected_block_header_hash = self.block.header.block_hash();
35,740✔
801
        let computed_block_header_hash = block.header.block_hash();
35,740✔
802

803
        if computed_block_header_hash != expected_block_header_hash {
35,740✔
804
            warn!(
×
805
                "Rejected block proposal";
806
                "reason" => "Block hash is not as expected",
807
                "expected_block_header_hash" => %expected_block_header_hash,
808
                "computed_block_header_hash" => %computed_block_header_hash,
809
                "expected_block" => ?self.block,
810
                "computed_block" => ?block,
811
            );
812
            return Err(BlockValidateRejectReason {
×
813
                reason: "Block hash is not as expected".into(),
×
814
                reason_code: ValidateRejectCode::BadBlockHash,
×
815
                failed_txid: None,
×
816
            });
×
817
        }
35,740✔
818

819
        let validation_time_ms = u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX);
35,740✔
820

821
        info!(
35,740✔
822
            "Participant: validated anchored block";
823
            "block_header_hash" => %computed_block_header_hash,
824
            "height" => block.header.chain_length,
35,740✔
825
            "tx_count" => block.txs.len(),
35,740✔
826
            "parent_stacks_block_id" => %block.header.parent_block_id,
827
            "block_size" => size,
35,740✔
828
            "execution_cost" => %cost,
829
            "validation_time_ms" => validation_time_ms,
35,740✔
830
            "tx_fees_microstacks" => block.txs.iter().fold(0, |agg: u64, tx| {
1,269,037✔
831
                agg.saturating_add(tx.get_tx_fee())
1,269,037✔
832
            })
1,269,037✔
833
        );
834

835
        let replay_tx_hash = Self::tx_replay_hash(&self.replay_txs);
35,740✔
836

837
        Ok(BlockValidateOk {
35,740✔
838
            signer_signature_hash: block.header.signer_signature_hash(),
35,740✔
839
            cost,
35,740✔
840
            size,
35,740✔
841
            validation_time_ms,
35,740✔
842
            replay_tx_hash,
35,740✔
843
            replay_tx_exhausted,
35,740✔
844
        })
35,740✔
845
    }
36,318✔
846

847
    pub fn tx_replay_hash(replay_txs: &Option<Vec<StacksTransaction>>) -> Option<u64> {
82,774✔
848
        replay_txs.as_ref().map(|txs| {
82,774✔
849
            let mut hasher = DefaultHasher::new();
2,241✔
850
            txs.hash(&mut hasher);
2,241✔
851
            hasher.finish()
2,241✔
852
        })
2,241✔
853
    }
82,774✔
854

855
    /// Validate the block against the replay set.
856
    ///
857
    /// Returns a boolean indicating whether this block exhausts the replay set.
858
    ///
859
    /// Returns `false` if there is no replay set.
860
    fn validate_replay(
35,857✔
861
        &self,
35,857✔
862
        parent_stacks_header: &StacksHeaderInfo,
35,857✔
863
        tenure_change: Option<&StacksTransaction>,
35,857✔
864
        coinbase: Option<&StacksTransaction>,
35,857✔
865
        tenure_cause: MinerTenureInfoCause,
35,857✔
866
        // not directly used; used as a handle to open other chainstates
35,857✔
867
        chainstate_handle: &StacksChainState,
35,857✔
868
        burn_dbconn: &SortitionHandleConn,
35,857✔
869
    ) -> Result<bool, BlockValidateRejectReason> {
35,857✔
870
        let mut replay_txs_maybe: Option<VecDeque<StacksTransaction>> =
35,857✔
871
            self.replay_txs.clone().map(|txs| txs.into());
35,857✔
872

873
        let Some(ref mut replay_txs) = replay_txs_maybe else {
35,857✔
874
            return Ok(false);
34,696✔
875
        };
876

877
        let mut replay_builder = NakamotoBlockBuilder::new(
1,161✔
878
            &parent_stacks_header,
1,161✔
879
            &self.block.header.consensus_hash,
1,161✔
880
            self.block.header.burn_spent,
1,161✔
881
            tenure_change,
1,161✔
882
            coinbase,
1,161✔
883
            self.block.header.pox_treatment.len(),
1,161✔
884
            None,
1,161✔
885
            None,
1,161✔
886
            Some(self.block.header.timestamp),
1,161✔
887
            u64::from(DEFAULT_MAX_TENURE_BYTES),
1,161✔
888
        )?;
×
889
        let (mut replay_chainstate, _) = chainstate_handle.reopen()?;
1,161✔
890
        let mut replay_miner_tenure_info =
1,161✔
891
            replay_builder.load_tenure_info(&mut replay_chainstate, &burn_dbconn, tenure_cause)?;
1,161✔
892
        let mut replay_tenure_tx =
1,161✔
893
            replay_builder.tenure_begin(&burn_dbconn, &mut replay_miner_tenure_info)?;
1,161✔
894

895
        let mut total_receipts = 0;
1,161✔
896
        for (i, tx) in self.block.txs.iter().enumerate() {
2,115✔
897
            let tx_len = tx.tx_len();
2,115✔
898

899
            // If a list of replay transactions is set, this transaction must be the next
900
            // mineable transaction from this list.
901
            loop {
902
                if matches!(
630✔
903
                    tx.payload,
2,169✔
904
                    TransactionPayload::TenureChange(..) | TransactionPayload::Coinbase(..)
905
                ) {
906
                    // Allow this to happen, tenure extend checks happen elsewhere.
907
                    break;
1,539✔
908
                }
630✔
909
                fault_injection_reject_replay_txs()?;
630✔
910
                let Some(replay_tx) = replay_txs.pop_front() else {
540✔
911
                    // During transaction replay, we expect that the block only
912
                    // contains transactions from the replay set. Thus, if we're here,
913
                    // the block contains a transaction that is not in the replay set,
914
                    // and we should reject the block.
915
                    warn!("Rejected block proposal. Block contains transactions beyond the replay set.";
×
916
                        "txid" => %tx.txid(),
×
917
                        "tx_index" => i,
×
918
                    );
919
                    return Err(BlockValidateRejectReason {
×
920
                        reason_code: ValidateRejectCode::InvalidTransactionReplay,
×
921
                        reason: "Block contains transactions beyond the replay set".into(),
×
922
                        failed_txid: Some(tx.txid()),
×
923
                    });
×
924
                };
925
                if replay_tx.txid() == tx.txid() {
540✔
926
                    break;
459✔
927
                }
81✔
928

929
                // The included tx doesn't match the next tx in the
930
                // replay set. Check to see if the tx is skipped because
931
                // it was unmineable.
932
                let tx_result = replay_builder.try_mine_tx_with_len(
81✔
933
                    &mut replay_tenure_tx,
81✔
934
                    &replay_tx,
81✔
935
                    replay_tx.tx_len(),
81✔
936
                    &BlockLimitFunction::NO_LIMIT_HIT,
81✔
937
                    None,
81✔
938
                    &mut total_receipts,
81✔
939
                );
940
                match tx_result {
81✔
941
                    TransactionResult::Skipped(TransactionSkipped { error, .. })
×
942
                    | TransactionResult::ProcessingError(TransactionError { error, .. })
54✔
943
                    | TransactionResult::Problematic(TransactionProblematic { error, .. }) => {
×
944
                        // The tx wasn't able to be mined. Check the underlying error, to
945
                        // see if we should reject the block or allow the tx to be
946
                        // dropped from the replay set.
947

948
                        match error {
×
949
                            ChainError::CostOverflowError(..)
950
                            | ChainError::BlockTooBigError
951
                            | ChainError::BlockCostLimitError
952
                            | ChainError::ClarityError(ClarityError::CostError(..)) => {
953
                                // block limit reached; add tx back to replay set.
954
                                // BUT we know that the block should have ended at this point, so
955
                                // return an error.
956
                                let txid = replay_tx.txid();
×
957
                                replay_txs.push_front(replay_tx);
×
958

959
                                warn!("Rejecting block proposal. Next replay tx exceeds cost limits, so should have been in the next block.";
×
960
                                    "error" => %error,
961
                                    "txid" => %txid,
962
                                );
963

964
                                return Err(BlockValidateRejectReason {
×
965
                                    reason_code: ValidateRejectCode::InvalidTransactionReplay,
×
966
                                    reason: "Next replay tx exceeds cost limits, so should have been in the next block.".into(),
×
967
                                    failed_txid: None,
×
968
                                });
×
969
                            }
970
                            _ => {
971
                                info!("During replay block validation, allowing problematic tx to be dropped";
54✔
972
                                    "txid" => %replay_tx.txid(),
54✔
973
                                    "error" => %error,
974
                                );
975
                                // it's ok, drop it
976
                                continue;
54✔
977
                            }
978
                        }
979
                    }
980
                    TransactionResult::Success(_) => {
981
                        // Tx should have been included
982
                        warn!("Rejected block proposal. Block doesn't contain replay transaction that should have been included.";
27✔
983
                            "block_txid" => %tx.txid(),
27✔
984
                            "block_tx_index" => i,
27✔
985
                            "replay_txid" => %replay_tx.txid(),
27✔
986
                        );
987
                        return Err(BlockValidateRejectReason {
27✔
988
                            reason_code: ValidateRejectCode::InvalidTransactionReplay,
27✔
989
                            reason: "Transaction is not in the replay set".into(),
27✔
990
                            failed_txid: Some(tx.txid()),
27✔
991
                        });
27✔
992
                    }
993
                };
994
            }
995

996
            // Apply the block's transaction to our block builder, but we don't
997
            // actually care about the result - that happens in the main
998
            // validation check.
999
            let _tx_result = replay_builder.try_mine_tx_with_len(
1,998✔
1000
                &mut replay_tenure_tx,
1,998✔
1001
                tx,
1,998✔
1002
                tx_len,
1,998✔
1003
                &BlockLimitFunction::NO_LIMIT_HIT,
1,998✔
1004
                None,
1,998✔
1005
                &mut total_receipts,
1,998✔
1006
            );
1007
        }
1008

1009
        let no_replay_txs_remaining = replay_txs.is_empty();
1,044✔
1010

1011
        // Now, we need to check if the remaining replay transactions are unmineable.
1012
        let only_unmineable_remaining = !replay_txs.is_empty()
1,044✔
1013
            && replay_txs.iter().all(|tx| {
990✔
1014
                let tx_result = replay_builder.try_mine_tx_with_len(
990✔
1015
                    &mut replay_tenure_tx,
990✔
1016
                    &tx,
990✔
1017
                    tx.tx_len(),
990✔
1018
                    &BlockLimitFunction::NO_LIMIT_HIT,
990✔
1019
                    None,
990✔
1020
                    &mut total_receipts,
990✔
1021
                );
1022
                match tx_result {
990✔
1023
                    TransactionResult::Skipped(TransactionSkipped { error, .. })
54✔
1024
                    | TransactionResult::ProcessingError(TransactionError { error, .. })
531✔
1025
                    | TransactionResult::Problematic(TransactionProblematic { error, .. }) => {
54✔
1026
                        // If it's just a cost error, it's not unmineable.
1027
                        !matches!(
585✔
1028
                            error,
×
1029
                            ChainError::CostOverflowError(..)
1030
                                | ChainError::BlockTooBigError
1031
                                | ChainError::ClarityError(ClarityError::CostError(..))
1032
                                | ChainError::BlockCostLimitError
1033
                        )
1034
                    }
1035
                    TransactionResult::Success(_) => {
1036
                        // The tx could have been included, but wasn't. This is ok, but we
1037
                        // haven't exhausted the replay set.
1038
                        false
351✔
1039
                    }
1040
                }
1041
            });
990✔
1042

1043
        Ok(no_replay_txs_remaining || only_unmineable_remaining)
1,044✔
1044
    }
35,857✔
1045
}
1046

1047
#[derive(Clone, Default)]
1048
pub struct RPCBlockProposalRequestHandler {
1049
    pub block_proposal: Option<NakamotoBlockProposal>,
1050
    pub auth: Option<String>,
1051
}
1052

1053
impl RPCBlockProposalRequestHandler {
1054
    pub fn new(auth: Option<String>) -> Self {
1,059,005✔
1055
        Self {
1,059,005✔
1056
            block_proposal: None,
1,059,005✔
1057
            auth,
1,059,005✔
1058
        }
1,059,005✔
1059
    }
1,059,005✔
1060

1061
    /// Decode a JSON-encoded block proposal
1062
    fn parse_json(body: &[u8]) -> Result<NakamotoBlockProposal, Error> {
100,588✔
1063
        serde_json::from_slice(body)
100,588✔
1064
            .map_err(|e| Error::DecodeError(format!("Failed to parse body: {e}")))
100,588✔
1065
    }
100,588✔
1066
}
1067

1068
/// Decode the HTTP request
1069
impl HttpRequest for RPCBlockProposalRequestHandler {
1070
    fn verb(&self) -> &'static str {
1,059,005✔
1071
        "POST"
1,059,005✔
1072
    }
1,059,005✔
1073

1074
    fn path_regex(&self) -> Regex {
2,118,010✔
1075
        Regex::new(r#"^/v3/block_proposal$"#).unwrap()
2,118,010✔
1076
    }
2,118,010✔
1077

1078
    fn metrics_identifier(&self) -> &str {
100,588✔
1079
        "/v3/block_proposal"
100,588✔
1080
    }
100,588✔
1081

1082
    /// Try to decode this request.
1083
    /// There's nothing to load here, so just make sure the request is well-formed.
1084
    fn try_parse_request(
100,597✔
1085
        &mut self,
100,597✔
1086
        preamble: &HttpRequestPreamble,
100,597✔
1087
        _captures: &Captures,
100,597✔
1088
        query: Option<&str>,
100,597✔
1089
        body: &[u8],
100,597✔
1090
    ) -> Result<HttpRequestContents, Error> {
100,597✔
1091
        // If no authorization is set, then the block proposal endpoint is not enabled
1092
        let Some(password) = &self.auth else {
100,597✔
1093
            return Err(Error::Http(400, "Bad Request.".into()));
×
1094
        };
1095
        let Some(auth_header) = preamble.headers.get("authorization") else {
100,597✔
1096
            return Err(Error::Http(401, "Unauthorized".into()));
9✔
1097
        };
1098
        if auth_header != password {
100,588✔
1099
            return Err(Error::Http(401, "Unauthorized".into()));
×
1100
        }
100,588✔
1101
        if preamble.get_content_length() == 0 {
100,588✔
1102
            return Err(Error::DecodeError(
×
1103
                "Invalid Http request: expected non-zero-length body for block proposal endpoint"
×
1104
                    .to_string(),
×
1105
            ));
×
1106
        }
100,588✔
1107
        if preamble.get_content_length() > MAX_PAYLOAD_LEN {
100,588✔
1108
            return Err(Error::DecodeError(
×
1109
                "Invalid Http request: BlockProposal body is too big".to_string(),
×
1110
            ));
×
1111
        }
100,588✔
1112

1113
        let block_proposal = match preamble.content_type {
100,588✔
1114
            Some(HttpContentType::JSON) => Self::parse_json(body)?,
100,588✔
1115
            Some(_) => {
1116
                return Err(Error::DecodeError(
×
1117
                    "Wrong Content-Type for block proposal; expected application/json".to_string(),
×
1118
                ))
×
1119
            }
1120
            None => {
1121
                return Err(Error::DecodeError(
×
1122
                    "Missing Content-Type for block proposal".to_string(),
×
1123
                ))
×
1124
            }
1125
        };
1126

1127
        if block_proposal.block.is_shadow_block() {
100,588✔
1128
            return Err(Error::DecodeError(
×
1129
                "Shadow blocks cannot be submitted for validation".to_string(),
×
1130
            ));
×
1131
        }
100,588✔
1132

1133
        self.block_proposal = Some(block_proposal);
100,588✔
1134
        Ok(HttpRequestContents::new().query_string(query))
100,588✔
1135
    }
100,597✔
1136
}
1137

1138
struct ProposalThreadInfo {
1139
    sortdb: SortitionDB,
1140
    chainstate: StacksChainState,
1141
    receiver: Box<dyn ProposalCallbackReceiver>,
1142
}
1143

1144
impl RPCRequestHandler for RPCBlockProposalRequestHandler {
1145
    /// Reset internal state
1146
    fn restart(&mut self) {
100,597✔
1147
        self.block_proposal = None
100,597✔
1148
    }
100,597✔
1149

1150
    /// Make the response
1151
    fn try_handle_request(
100,588✔
1152
        &mut self,
100,588✔
1153
        preamble: HttpRequestPreamble,
100,588✔
1154
        _contents: HttpRequestContents,
100,588✔
1155
        node: &mut StacksNodeState,
100,588✔
1156
    ) -> Result<(HttpResponsePreamble, HttpResponseContents), NetError> {
100,588✔
1157
        let block_proposal = self
100,588✔
1158
            .block_proposal
100,588✔
1159
            .take()
100,588✔
1160
            .ok_or(NetError::SendError("`block_proposal` not set".into()))?;
100,588✔
1161

1162
        info!(
100,588✔
1163
            "Received block proposal request";
1164
            "signer_signature_hash" => %block_proposal.block.header.signer_signature_hash(),
100,588✔
1165
            "block_header_hash" => %block_proposal.block.header.block_hash(),
100,588✔
1166
            "height" => block_proposal.block.header.chain_length,
100,588✔
1167
            "tx_count" => block_proposal.block.txs.len(),
100,588✔
1168
            "parent_stacks_block_id" => %block_proposal.block.header.parent_block_id,
1169
        );
1170

1171
        let res = node.with_node_state(|network, sortdb, chainstate, _mempool, rpc_args| {
100,588✔
1172
            if network.is_proposal_thread_running() {
100,588✔
1173
                return Err((
64,260✔
1174
                    TOO_MANY_REQUESTS_STATUS,
64,260✔
1175
                    NetError::SendError("Proposal currently being evaluated".into()),
64,260✔
1176
                ));
64,260✔
1177
            }
36,328✔
1178

1179
            if block_proposal
36,328✔
1180
                .block
36,328✔
1181
                .header
36,328✔
1182
                .timestamp
36,328✔
1183
                .saturating_add(network.get_connection_opts().block_proposal_max_age_secs)
36,328✔
1184
                < get_epoch_time_secs()
36,328✔
1185
            {
1186
                return Err((
10✔
1187
                    422,
10✔
1188
                    NetError::SendError("Block proposal is too old to process.".into()),
10✔
1189
                ));
10✔
1190
            }
36,318✔
1191

1192
            let (chainstate, _) = chainstate.reopen().map_err(|e| (400, NetError::from(e)))?;
36,318✔
1193
            let sortdb = sortdb.reopen().map_err(|e| (400, NetError::from(e)))?;
36,318✔
1194
            let receiver = rpc_args
36,318✔
1195
                .event_observer
36,318✔
1196
                .and_then(|observer| observer.get_proposal_callback_receiver())
36,318✔
1197
                .ok_or_else(|| {
36,318✔
1198
                    (
×
1199
                        400,
×
1200
                        NetError::SendError(
×
1201
                            "No `observer` registered for receiving proposal callbacks".into(),
×
1202
                        ),
×
1203
                    )
×
1204
                })?;
×
1205
            let thread_info = block_proposal
36,318✔
1206
                .spawn_validation_thread(
36,318✔
1207
                    sortdb,
36,318✔
1208
                    chainstate,
36,318✔
1209
                    receiver,
36,318✔
1210
                    network.get_connection_opts(),
36,318✔
1211
                )
1212
                .map_err(|_e| {
36,318✔
1213
                    (
×
1214
                        TOO_MANY_REQUESTS_STATUS,
×
1215
                        NetError::SendError(
×
1216
                            "IO error while spawning proposal callback thread".into(),
×
1217
                        ),
×
1218
                    )
×
1219
                })?;
×
1220
            network.set_proposal_thread(thread_info);
36,318✔
1221
            Ok(())
36,318✔
1222
        });
100,588✔
1223

1224
        match res {
100,588✔
1225
            Ok(_) => {
1226
                let preamble = HttpResponsePreamble::accepted_json(&preamble);
36,318✔
1227
                let body = HttpResponseContents::try_from_json(&serde_json::json!({
36,318✔
1228
                    "result": "Accepted",
36,318✔
1229
                    "message": "Block proposal is processing, result will be returned via the event observer"
36,318✔
1230
                }))?;
36,318✔
1231
                Ok((preamble, body))
36,318✔
1232
            }
1233
            Err((code, err)) => {
64,270✔
1234
                let preamble = HttpResponsePreamble::error_json(code, http_reason(code));
64,270✔
1235
                let body = HttpResponseContents::try_from_json(&serde_json::json!({
64,270✔
1236
                    "result": "Error",
64,270✔
1237
                    "message": format!("Could not process block proposal request: {err}")
64,270✔
1238
                }))?;
64,270✔
1239
                Ok((preamble, body))
64,270✔
1240
            }
1241
        }
1242
    }
100,588✔
1243
}
1244

1245
/// Decode the HTTP response
1246
impl HttpResponse for RPCBlockProposalRequestHandler {
1247
    fn try_parse_response(
3✔
1248
        &self,
3✔
1249
        preamble: &HttpResponsePreamble,
3✔
1250
        body: &[u8],
3✔
1251
    ) -> Result<HttpResponsePayload, Error> {
3✔
1252
        let response: BlockProposalResponse = parse_json(preamble, body)?;
3✔
1253
        HttpResponsePayload::try_from_json(response)
3✔
1254
    }
3✔
1255
}
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