Skip to content

Commit eb9ef04

Browse files
committed
REST: add "blockhashbyheight" call, fetch blockhash by height
1 parent c932730 commit eb9ef04

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

src/rest.cpp

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -577,6 +577,52 @@ static bool rest_getutxos(HTTPRequest* req, const std::string& strURIPart)
577577
}
578578
}
579579

580+
static bool rest_blockhash_by_height(HTTPRequest* req,
581+
const std::string& str_uri_part)
582+
{
583+
if (!CheckWarmup(req)) return false;
584+
std::string height_str;
585+
const RetFormat rf = ParseDataFormat(height_str, str_uri_part);
586+
587+
int32_t blockheight;
588+
if (!ParseInt32(height_str, &blockheight) || blockheight < 0) {
589+
return RESTERR(req, HTTP_BAD_REQUEST, "Invalid height: " + SanitizeString(height_str));
590+
}
591+
592+
CBlockIndex* pblockindex = nullptr;
593+
{
594+
LOCK(cs_main);
595+
if (blockheight > chainActive.Height()) {
596+
return RESTERR(req, HTTP_NOT_FOUND, "Block height out of range");
597+
}
598+
pblockindex = chainActive[blockheight];
599+
}
600+
switch (rf) {
601+
case RetFormat::BINARY: {
602+
CDataStream ss_blockhash(SER_NETWORK, PROTOCOL_VERSION);
603+
ss_blockhash << pblockindex->GetBlockHash();
604+
req->WriteHeader("Content-Type", "application/octet-stream");
605+
req->WriteReply(HTTP_OK, ss_blockhash.str());
606+
return true;
607+
}
608+
case RetFormat::HEX: {
609+
req->WriteHeader("Content-Type", "text/plain");
610+
req->WriteReply(HTTP_OK, pblockindex->GetBlockHash().GetHex() + "\n");
611+
return true;
612+
}
613+
case RetFormat::JSON: {
614+
req->WriteHeader("Content-Type", "application/json");
615+
UniValue resp = UniValue(UniValue::VOBJ);
616+
resp.pushKV("blockhash", pblockindex->GetBlockHash().GetHex());
617+
req->WriteReply(HTTP_OK, resp.write() + "\n");
618+
return true;
619+
}
620+
default: {
621+
return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
622+
}
623+
}
624+
}
625+
580626
static const struct {
581627
const char* prefix;
582628
bool (*handler)(HTTPRequest* req, const std::string& strReq);
@@ -589,6 +635,7 @@ static const struct {
589635
{"/rest/mempool/contents", rest_mempool_contents},
590636
{"/rest/headers/", rest_headers},
591637
{"/rest/getutxos", rest_getutxos},
638+
{"/rest/blockhashbyheight/", rest_blockhash_by_height},
592639
};
593640

594641
void StartREST()

0 commit comments

Comments
 (0)