Skip to content

Commit

Permalink
Add endpoint for raw blocks
Browse files Browse the repository at this point in the history
Available as GET /block/:hash/raw, returned in binary
  • Loading branch information
shesek committed Mar 21, 2020
1 parent cfe9430 commit de1ffb9
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
17 changes: 16 additions & 1 deletion src/new_index/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use bitcoin::blockdata::script::Script;
use bitcoin::hashes::sha256d::Hash as Sha256dHash;
#[cfg(not(feature = "liquid"))]
use bitcoin::util::merkleblock::MerkleBlock;
use bitcoin::{BlockHash, Txid};
use bitcoin::{BlockHash, Txid, VarInt};
use crypto::digest::Digest;
use crypto::sha2::Sha256;
use itertools::Itertools;
Expand Down Expand Up @@ -321,6 +321,21 @@ impl ChainQuery {
.map(|val| bincode::deserialize(&val).expect("failed to parse BlockMeta"))
}

pub fn get_block_raw(&self, hash: &BlockHash) -> Option<Vec<u8>> {
let entry = self.header_by_hash(hash)?;
let txids = self.get_block_txids(hash)?;

let mut raw = serialize(entry.header());

raw.append(&mut serialize(&VarInt(txids.len() as u64)));

for txid in txids {
raw.append(&mut self.lookup_raw_txn(&txid)?);
}

Some(raw)
}

pub fn get_block_with_meta(&self, hash: &BlockHash) -> Option<BlockHeaderMeta> {
let _timer = self.start_timer("get_block_with_meta");
Some(BlockHeaderMeta {
Expand Down
14 changes: 14 additions & 0 deletions src/rest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -609,6 +609,20 @@ fn handle_request(
.ok_or_else(|| HttpError::not_found("Block not found".to_string()))?;
json_response(txids, TTL_LONG)
}
(&Method::GET, Some(&"block"), Some(hash), Some(&"raw"), None, None) => {
let hash = BlockHash::from_hex(hash)?;
let raw = query
.chain()
.get_block_raw(&hash)
.ok_or_else(|| HttpError::not_found("Block not found".to_string()))?;

Ok(Response::builder()
.status(StatusCode::OK)
.header("Content-Type", "application/octet-stream")
.header("Cache-Control", format!("public, max-age={:}", TTL_LONG))
.body(Body::from(raw))
.unwrap())
}
(&Method::GET, Some(&"block"), Some(hash), Some(&"txid"), Some(index), None) => {
let hash = BlockHash::from_hex(hash)?;
let index: usize = index.parse()?;
Expand Down

0 comments on commit de1ffb9

Please sign in to comment.