|
| 1 | +// Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation |
| 2 | +// Copyright (C) 2020-2024 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::io::{Read, Seek, SeekFrom, Write}; |
| 18 | +use std::{fs, io}; |
| 19 | + |
| 20 | +use regex::{Captures, Regex}; |
| 21 | +use rusqlite::Connection; |
| 22 | +use serde::de::Error as de_Error; |
| 23 | +use stacks_common::codec::{StacksMessageCodec, MAX_MESSAGE_LEN}; |
| 24 | +use stacks_common::types::chainstate::{ConsensusHash, StacksBlockId}; |
| 25 | +use stacks_common::types::net::PeerHost; |
| 26 | +use {serde, serde_json}; |
| 27 | + |
| 28 | +use crate::chainstate::nakamoto::{ |
| 29 | + NakamotoBlock, NakamotoChainState, NakamotoStagingBlocksConn, StacksDBIndexed, |
| 30 | +}; |
| 31 | +use crate::chainstate::stacks::db::StacksChainState; |
| 32 | +use crate::chainstate::stacks::Error as ChainError; |
| 33 | +use crate::net::api::getblock_v3::{NakamotoBlockStream, RPCNakamotoBlockRequestHandler}; |
| 34 | +use crate::net::http::{ |
| 35 | + parse_bytes, Error, HttpBadRequest, HttpChunkGenerator, HttpContentType, HttpNotFound, |
| 36 | + HttpRequest, HttpRequestContents, HttpRequestPreamble, HttpResponse, HttpResponseContents, |
| 37 | + HttpResponsePayload, HttpResponsePreamble, HttpServerError, HttpVersion, |
| 38 | +}; |
| 39 | +use crate::net::httpcore::{ |
| 40 | + HttpRequestContentsExtensions, RPCRequestHandler, StacksHttp, StacksHttpRequest, |
| 41 | + StacksHttpResponse, |
| 42 | +}; |
| 43 | +use crate::net::{Error as NetError, StacksNodeState, TipRequest, MAX_HEADERS}; |
| 44 | +use crate::util_lib::db::{DBConn, Error as DBError}; |
| 45 | + |
| 46 | +#[derive(Clone)] |
| 47 | +pub struct RPCNakamotoBlockByHeightRequestHandler { |
| 48 | + pub block_height: Option<u64>, |
| 49 | +} |
| 50 | + |
| 51 | +impl RPCNakamotoBlockByHeightRequestHandler { |
| 52 | + pub fn new() -> Self { |
| 53 | + Self { block_height: None } |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +/// Decode the HTTP request |
| 58 | +impl HttpRequest for RPCNakamotoBlockByHeightRequestHandler { |
| 59 | + fn verb(&self) -> &'static str { |
| 60 | + "GET" |
| 61 | + } |
| 62 | + |
| 63 | + fn path_regex(&self) -> Regex { |
| 64 | + Regex::new(r#"^/v3/blocks/height/(?P<block_height>[0-9]{1,20})$"#).unwrap() |
| 65 | + } |
| 66 | + |
| 67 | + fn metrics_identifier(&self) -> &str { |
| 68 | + "/v3/blocks/height/:block_height" |
| 69 | + } |
| 70 | + |
| 71 | + /// Try to decode this request. |
| 72 | + /// There's nothing to load here, so just make sure the request is well-formed. |
| 73 | + fn try_parse_request( |
| 74 | + &mut self, |
| 75 | + preamble: &HttpRequestPreamble, |
| 76 | + captures: &Captures, |
| 77 | + query: Option<&str>, |
| 78 | + _body: &[u8], |
| 79 | + ) -> Result<HttpRequestContents, Error> { |
| 80 | + if preamble.get_content_length() != 0 { |
| 81 | + return Err(Error::DecodeError( |
| 82 | + "Invalid Http request: expected 0-length body".to_string(), |
| 83 | + )); |
| 84 | + } |
| 85 | + |
| 86 | + let block_height_str = captures |
| 87 | + .name("block_height") |
| 88 | + .ok_or_else(|| { |
| 89 | + Error::DecodeError("Failed to match path to block height group".to_string()) |
| 90 | + })? |
| 91 | + .as_str(); |
| 92 | + |
| 93 | + let block_height = block_height_str.parse::<u64>().map_err(|_| { |
| 94 | + Error::DecodeError("Invalid path: unparseable block height".to_string()) |
| 95 | + })?; |
| 96 | + self.block_height = Some(block_height); |
| 97 | + |
| 98 | + Ok(HttpRequestContents::new().query_string(query)) |
| 99 | + } |
| 100 | +} |
| 101 | + |
| 102 | +impl RPCRequestHandler for RPCNakamotoBlockByHeightRequestHandler { |
| 103 | + /// Reset internal state |
| 104 | + fn restart(&mut self) { |
| 105 | + self.block_height = None; |
| 106 | + } |
| 107 | + |
| 108 | + /// Make the response |
| 109 | + fn try_handle_request( |
| 110 | + &mut self, |
| 111 | + preamble: HttpRequestPreamble, |
| 112 | + contents: HttpRequestContents, |
| 113 | + node: &mut StacksNodeState, |
| 114 | + ) -> Result<(HttpResponsePreamble, HttpResponseContents), NetError> { |
| 115 | + let block_height = self |
| 116 | + .block_height |
| 117 | + .take() |
| 118 | + .ok_or(NetError::SendError("Missing `block_height`".into()))?; |
| 119 | + |
| 120 | + let tip = match node.load_stacks_chain_tip(&preamble, &contents) { |
| 121 | + Ok(tip) => tip, |
| 122 | + Err(error_resp) => { |
| 123 | + return error_resp.try_into_contents().map_err(NetError::from); |
| 124 | + } |
| 125 | + }; |
| 126 | + |
| 127 | + let index_block_hash_res = |
| 128 | + node.with_node_state(|_network, _sortdb, chainstate, _mempool, _rpc_args| { |
| 129 | + chainstate |
| 130 | + .index_conn() |
| 131 | + .get_ancestor_block_hash(block_height, &tip) |
| 132 | + }); |
| 133 | + |
| 134 | + let block_id = match index_block_hash_res { |
| 135 | + Ok(index_block_hash_opt) => match index_block_hash_opt { |
| 136 | + Some(index_block_hash) => index_block_hash, |
| 137 | + None => { |
| 138 | + // block hash not found |
| 139 | + let msg = format!("No such block #{:?}\n", block_height); |
| 140 | + warn!("{}", &msg); |
| 141 | + return StacksHttpResponse::new_error(&preamble, &HttpNotFound::new(msg)) |
| 142 | + .try_into_contents() |
| 143 | + .map_err(NetError::from); |
| 144 | + } |
| 145 | + }, |
| 146 | + Err(e) => { |
| 147 | + // error querying the db |
| 148 | + let msg = format!("Failed to load block #{}: {:?}\n", block_height, &e); |
| 149 | + warn!("{}", &msg); |
| 150 | + return StacksHttpResponse::new_error(&preamble, &HttpServerError::new(msg)) |
| 151 | + .try_into_contents() |
| 152 | + .map_err(NetError::from); |
| 153 | + } |
| 154 | + }; |
| 155 | + |
| 156 | + let stream_res = |
| 157 | + node.with_node_state(|_network, _sortdb, chainstate, _mempool, _rpc_args| { |
| 158 | + let Some((tenure_id, parent_block_id)) = chainstate |
| 159 | + .nakamoto_blocks_db() |
| 160 | + .get_tenure_and_parent_block_id(&block_id)? |
| 161 | + else { |
| 162 | + return Err(ChainError::NoSuchBlockError); |
| 163 | + }; |
| 164 | + NakamotoBlockStream::new(chainstate, block_id, tenure_id, parent_block_id) |
| 165 | + }); |
| 166 | + |
| 167 | + // start loading up the block |
| 168 | + let stream = match stream_res { |
| 169 | + Ok(stream) => stream, |
| 170 | + Err(ChainError::NoSuchBlockError) => { |
| 171 | + return StacksHttpResponse::new_error( |
| 172 | + &preamble, |
| 173 | + &HttpNotFound::new(format!("No such block #{:?}\n", &block_height)), |
| 174 | + ) |
| 175 | + .try_into_contents() |
| 176 | + .map_err(NetError::from) |
| 177 | + } |
| 178 | + Err(e) => { |
| 179 | + // nope -- error trying to check |
| 180 | + let msg = format!("Failed to load block #{}: {:?}\n", block_height, &e); |
| 181 | + warn!("{}", &msg); |
| 182 | + return StacksHttpResponse::new_error(&preamble, &HttpServerError::new(msg)) |
| 183 | + .try_into_contents() |
| 184 | + .map_err(NetError::from); |
| 185 | + } |
| 186 | + }; |
| 187 | + |
| 188 | + let resp_preamble = HttpResponsePreamble::from_http_request_preamble( |
| 189 | + &preamble, |
| 190 | + 200, |
| 191 | + "OK", |
| 192 | + None, |
| 193 | + HttpContentType::Bytes, |
| 194 | + ); |
| 195 | + |
| 196 | + Ok(( |
| 197 | + resp_preamble, |
| 198 | + HttpResponseContents::from_stream(Box::new(stream)), |
| 199 | + )) |
| 200 | + } |
| 201 | +} |
| 202 | + |
| 203 | +/// Decode the HTTP response |
| 204 | +impl HttpResponse for RPCNakamotoBlockByHeightRequestHandler { |
| 205 | + /// Decode this response from a byte stream. This is called by the client to decode this |
| 206 | + /// message |
| 207 | + fn try_parse_response( |
| 208 | + &self, |
| 209 | + preamble: &HttpResponsePreamble, |
| 210 | + body: &[u8], |
| 211 | + ) -> Result<HttpResponsePayload, Error> { |
| 212 | + let bytes = parse_bytes(preamble, body, MAX_MESSAGE_LEN.into())?; |
| 213 | + Ok(HttpResponsePayload::Bytes(bytes)) |
| 214 | + } |
| 215 | +} |
| 216 | + |
| 217 | +impl StacksHttpRequest { |
| 218 | + pub fn new_get_nakamoto_block_by_height( |
| 219 | + host: PeerHost, |
| 220 | + block_height: u64, |
| 221 | + tip: TipRequest, |
| 222 | + ) -> StacksHttpRequest { |
| 223 | + StacksHttpRequest::new_for_peer( |
| 224 | + host, |
| 225 | + "GET".into(), |
| 226 | + format!("/v3/blocks/height/{}", block_height), |
| 227 | + HttpRequestContents::new().for_tip(tip), |
| 228 | + ) |
| 229 | + .expect("FATAL: failed to construct request from infallible data") |
| 230 | + } |
| 231 | +} |
0 commit comments