• 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

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

16
use clarity::util::hash::bytes_to_hex;
17
use clarity::vm::types::PrincipalData;
18
use regex::{Captures, Regex};
19
use stacks_common::codec::{Error as CodecError, StacksMessageCodec, MAX_PAYLOAD_LEN};
20
use stacks_common::types::chainstate::StacksBlockId;
21
use stacks_common::types::net::PeerHost;
22
use stacks_common::util::hash::hex_bytes;
23
use url::form_urlencoded;
24

25
use crate::chainstate::burn::db::sortdb::SortitionDB;
26
use crate::chainstate::stacks::db::StacksChainState;
27
use crate::chainstate::stacks::{Error as ChainError, StacksTransaction};
28
use crate::net::api::blockreplay::{remine_nakamoto_block, RPCReplayedBlock};
29
use crate::net::http::{
30
    parse_json, Error, HttpContentType, HttpNotFound, HttpRequest, HttpRequestContents,
31
    HttpRequestPreamble, HttpResponse, HttpResponseContents, HttpResponsePayload,
32
    HttpResponsePreamble, HttpServerError,
33
};
34
use crate::net::httpcore::{RPCRequestHandler, StacksHttpResponse};
35
use crate::net::{Error as NetError, StacksHttpRequest, StacksNodeState};
36

37
#[derive(Clone, Serialize, Deserialize)]
38
pub struct RPCNakamotoBlockSimulateMint {
39
    pub principal: PrincipalData,
40
    pub amount: u128,
41
}
42

43
#[derive(Clone, Serialize, Deserialize)]
44
pub struct RPCNakamotoBlockSimulateBody {
45
    pub mint: Vec<RPCNakamotoBlockSimulateMint>,
46
    pub transactions_hex: Vec<String>,
47
}
48

49
#[derive(Clone)]
50
pub struct RPCNakamotoBlockSimulateRequestHandler {
51
    pub block_id: Option<StacksBlockId>,
52
    pub auth: Option<String>,
53
    pub profiler: bool,
54
    pub transactions: Vec<StacksTransaction>,
55
    pub mint: Vec<RPCNakamotoBlockSimulateMint>,
56
}
57

58
impl RPCNakamotoBlockSimulateRequestHandler {
59
    pub fn new(auth: Option<String>) -> Self {
1,059,059✔
60
        Self {
1,059,059✔
61
            block_id: None,
1,059,059✔
62
            auth,
1,059,059✔
63
            profiler: false,
1,059,059✔
64
            transactions: vec![],
1,059,059✔
65
            mint: vec![],
1,059,059✔
66
        }
1,059,059✔
67
    }
1,059,059✔
68

69
    fn parse_json(
×
70
        body: &[u8],
×
71
    ) -> Result<(Vec<StacksTransaction>, Vec<RPCNakamotoBlockSimulateMint>), Error> {
×
72
        let block_simulate_body: RPCNakamotoBlockSimulateBody = serde_json::from_slice(body)
×
73
            .map_err(|e| Error::DecodeError(format!("Failed to parse body: {e}")))?;
×
74

75
        let mut transactions = vec![];
×
76

77
        for tx_hex in block_simulate_body.transactions_hex {
×
78
            let tx_bytes =
×
79
                hex_bytes(&tx_hex).map_err(|_e| Error::DecodeError("Failed to parse tx".into()))?;
×
80
            let tx = StacksTransaction::consensus_deserialize(&mut &tx_bytes[..]).map_err(|e| {
×
81
                if let CodecError::DeserializeError(msg) = e {
×
82
                    Error::DecodeError(format!("Failed to deserialize transaction: {}", msg))
×
83
                } else {
84
                    e.into()
×
85
                }
86
            })?;
×
87
            transactions.push(tx);
×
88
        }
89

90
        Ok((transactions, block_simulate_body.mint))
×
91
    }
×
92

93
    pub fn block_simulate(
×
94
        &self,
×
95
        sortdb: &SortitionDB,
×
96
        chainstate: &mut StacksChainState,
×
97
    ) -> Result<RPCReplayedBlock, ChainError> {
×
98
        let Some(block_id) = &self.block_id else {
×
99
            return Err(ChainError::InvalidStacksBlock("block_id is None".into()));
×
100
        };
101

102
        let rpc_simulated_block = remine_nakamoto_block(
×
103
            block_id,
×
104
            sortdb,
×
105
            chainstate,
×
106
            self.profiler,
×
107
            |_| self.transactions.clone(),
×
108
            |tenure_tx| {
×
109
                if !self.mint.is_empty() {
×
110
                    tenure_tx.connection().as_transaction(|tx| {
×
111
                        tx.with_clarity_db(|ref mut db| {
×
112
                            for mint in &self.mint {
×
113
                                let mut balance = db.get_stx_balance_snapshot(&mint.principal)?;
×
114
                                balance.credit(mint.amount)?;
×
115
                                balance.save()?;
×
116
                            }
117
                            Ok(())
×
118
                        })
×
119
                    })?;
×
120
                }
×
121
                Ok(())
×
122
            },
×
123
        )?;
×
124

125
        Ok(rpc_simulated_block)
×
126
    }
×
127
}
128

129
/// Decode the HTTP request
130
impl HttpRequest for RPCNakamotoBlockSimulateRequestHandler {
131
    fn verb(&self) -> &'static str {
1,059,059✔
132
        "POST"
1,059,059✔
133
    }
1,059,059✔
134

135
    fn path_regex(&self) -> Regex {
2,118,118✔
136
        Regex::new(r#"^/v3/blocks/simulate/(?P<block_id>[0-9a-f]{64})$"#).unwrap()
2,118,118✔
137
    }
2,118,118✔
138

139
    fn metrics_identifier(&self) -> &str {
×
140
        "/v3/blocks/simulate/:block_id"
×
141
    }
×
142

143
    /// Try to decode this request.
144
    /// There's nothing to load here, so just make sure the request is well-formed.
145
    fn try_parse_request(
×
146
        &mut self,
×
147
        preamble: &HttpRequestPreamble,
×
148
        captures: &Captures,
×
149
        query: Option<&str>,
×
150
        body: &[u8],
×
151
    ) -> Result<HttpRequestContents, Error> {
×
152
        // If no authorization is set, then the block replay endpoint is not enabled
153
        let Some(password) = &self.auth else {
×
154
            return Err(Error::Http(400, "Bad Request.".into()));
×
155
        };
156
        let Some(auth_header) = preamble.headers.get("authorization") else {
×
157
            return Err(Error::Http(401, "Unauthorized".into()));
×
158
        };
159
        if auth_header != password {
×
160
            return Err(Error::Http(401, "Unauthorized".into()));
×
161
        }
×
162

163
        let block_id_str = captures
×
164
            .name("block_id")
×
165
            .ok_or_else(|| {
×
166
                Error::DecodeError("Failed to match path to block ID group".to_string())
×
167
            })?
×
168
            .as_str();
×
169

170
        let block_id = StacksBlockId::from_hex(block_id_str)
×
171
            .map_err(|_| Error::DecodeError("Invalid path: unparseable block id".to_string()))?;
×
172

173
        self.block_id = Some(block_id);
×
174

175
        if let Some(query_string) = query {
×
176
            for (key, value) in form_urlencoded::parse(query_string.as_bytes()) {
×
177
                if key == "profiler" {
×
178
                    if value == "1" {
×
179
                        self.profiler = true;
×
180
                        break;
×
181
                    }
×
182
                }
×
183
            }
184
        }
×
185

186
        if preamble.get_content_length() == 0 {
×
187
            return Err(Error::DecodeError(
×
188
                "Invalid Http request: expected non-zero-length body for block proposal endpoint"
×
189
                    .to_string(),
×
190
            ));
×
191
        }
×
192
        if preamble.get_content_length() > MAX_PAYLOAD_LEN {
×
193
            return Err(Error::DecodeError(
×
194
                "Invalid Http request: BlockProposal body is too big".to_string(),
×
195
            ));
×
196
        }
×
197

198
        (self.transactions, self.mint) = match preamble.content_type {
×
199
            Some(HttpContentType::JSON) => Self::parse_json(body)?,
×
200
            Some(_) => {
201
                return Err(Error::DecodeError(
×
202
                    "Wrong Content-Type for block proposal; expected application/json".to_string(),
×
203
                ))
×
204
            }
205
            None => {
206
                return Err(Error::DecodeError(
×
207
                    "Missing Content-Type for block simulation".to_string(),
×
208
                ))
×
209
            }
210
        };
211

212
        Ok(HttpRequestContents::new().query_string(query))
×
213
    }
×
214
}
215

216
impl RPCRequestHandler for RPCNakamotoBlockSimulateRequestHandler {
217
    /// Reset internal state
218
    fn restart(&mut self) {
×
219
        self.block_id = None;
×
220
    }
×
221

222
    /// Make the response
223
    fn try_handle_request(
×
224
        &mut self,
×
225
        preamble: HttpRequestPreamble,
×
226
        _contents: HttpRequestContents,
×
227
        node: &mut StacksNodeState,
×
228
    ) -> Result<(HttpResponsePreamble, HttpResponseContents), NetError> {
×
229
        let Some(block_id) = &self.block_id else {
×
230
            return Err(NetError::SendError("Missing `block_id`".into()));
×
231
        };
232

233
        let simulated_block_res =
×
234
            node.with_node_state(|_network, sortdb, chainstate, _mempool, _rpc_args| {
×
235
                self.block_simulate(sortdb, chainstate)
×
236
            });
×
237

238
        // start loading up the block
239
        let simulated_block = match simulated_block_res {
×
240
            Ok(simulated_block) => simulated_block,
×
241
            Err(ChainError::NoSuchBlockError) => {
242
                return StacksHttpResponse::new_error(
×
243
                    &preamble,
×
244
                    &HttpNotFound::new(format!("No such block {block_id}\n")),
×
245
                )
246
                .try_into_contents()
×
247
                .map_err(NetError::from)
×
248
            }
249
            Err(e) => {
×
250
                // nope -- error trying to check
251
                let msg = format!("Failed to simulate block {}: {:?}\n", &block_id, &e);
×
252
                warn!("{}", &msg);
×
253
                return StacksHttpResponse::new_error(&preamble, &HttpServerError::new(msg))
×
254
                    .try_into_contents()
×
255
                    .map_err(NetError::from);
×
256
            }
257
        };
258

259
        let preamble = HttpResponsePreamble::ok_json(&preamble);
×
260
        let body = HttpResponseContents::try_from_json(&simulated_block)?;
×
261
        Ok((preamble, body))
×
262
    }
×
263
}
264

265
impl StacksHttpRequest {
266
    /// Make a new block_replay request to this endpoint
267
    pub fn new_block_simulate(
×
268
        host: PeerHost,
×
269
        block_id: &StacksBlockId,
×
270
        transactions: &Vec<StacksTransaction>,
×
271
        mint: &Vec<RPCNakamotoBlockSimulateMint>,
×
272
    ) -> StacksHttpRequest {
×
273
        let transactions_hex = transactions
×
274
            .iter()
×
275
            .map(|transaction| bytes_to_hex(&transaction.serialize_to_vec()))
×
276
            .collect();
×
277

278
        let block_simulate_body = RPCNakamotoBlockSimulateBody {
×
279
            mint: mint.clone(),
×
280
            transactions_hex,
×
281
        };
×
282

283
        StacksHttpRequest::new_for_peer(
×
284
            host,
×
285
            "POST".into(),
×
286
            format!("/v3/blocks/simulate/{block_id}"),
×
287
            HttpRequestContents::new().payload_json(
×
288
                serde_json::to_value(block_simulate_body)
×
289
                    .expect("FATAL: failed to encode RPCNakamotoBlockSimulateBody"),
×
290
            ),
291
        )
292
        .expect("FATAL: failed to construct request from infallible data")
×
293
    }
×
294

295
    pub fn new_block_simulate_with_profiler(
×
296
        host: PeerHost,
×
297
        block_id: &StacksBlockId,
×
298
        profiler: bool,
×
299
        transactions: &Vec<StacksTransaction>,
×
300
        mint: &Vec<RPCNakamotoBlockSimulateMint>,
×
301
    ) -> StacksHttpRequest {
×
302
        let transactions_hex = transactions
×
303
            .iter()
×
304
            .map(|transaction| bytes_to_hex(&transaction.serialize_to_vec()))
×
305
            .collect();
×
306

307
        let block_simulate_body = RPCNakamotoBlockSimulateBody {
×
308
            mint: mint.clone(),
×
309
            transactions_hex,
×
310
        };
×
311
        StacksHttpRequest::new_for_peer(
×
312
            host,
×
313
            "POST".into(),
×
314
            format!("/v3/blocks/simulate/{block_id}"),
×
315
            HttpRequestContents::new()
×
316
                .query_arg(
×
317
                    "profiler".into(),
×
318
                    if profiler { "1".into() } else { "0".into() },
×
319
                )
320
                .payload_json(
×
321
                    serde_json::to_value(block_simulate_body)
×
322
                        .expect("FATAL: failed to encode RPCNakamotoBlockSimulateBody"),
×
323
                ),
324
        )
325
        .expect("FATAL: failed to construct request from infallible data")
×
326
    }
×
327
}
328

329
/// Decode the HTTP response
330
impl HttpResponse for RPCNakamotoBlockSimulateRequestHandler {
331
    /// Decode this response from a byte stream.  This is called by the client to decode this
332
    /// message
333
    fn try_parse_response(
×
334
        &self,
×
335
        preamble: &HttpResponsePreamble,
×
336
        body: &[u8],
×
337
    ) -> Result<HttpResponsePayload, Error> {
×
338
        let rpc_replayed_block: RPCReplayedBlock = parse_json(preamble, body)?;
×
339
        Ok(HttpResponsePayload::try_from_json(rpc_replayed_block)?)
×
340
    }
×
341
}
342

343
impl StacksHttpResponse {
344
    pub fn decode_simulated_block(self) -> Result<RPCReplayedBlock, NetError> {
×
345
        let contents = self.get_http_payload_ok()?;
×
346
        let response_json: serde_json::Value = contents.try_into()?;
×
347
        let replayed_block: RPCReplayedBlock = serde_json::from_value(response_json)
×
348
            .map_err(|_e| Error::DecodeError("Failed to decode JSON".to_string()))?;
×
349
        Ok(replayed_block)
×
350
    }
×
351
}
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