Bitcoin Core  21.99.0
P2P Digital Currency
rest.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2020 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #include <chain.h>
7 #include <chainparams.h>
8 #include <core_io.h>
9 #include <httpserver.h>
10 #include <index/txindex.h>
11 #include <node/blockstorage.h>
12 #include <node/context.h>
13 #include <primitives/block.h>
14 #include <primitives/transaction.h>
15 #include <rpc/blockchain.h>
16 #include <rpc/protocol.h>
17 #include <rpc/server.h>
18 #include <streams.h>
19 #include <sync.h>
20 #include <txmempool.h>
21 #include <util/check.h>
22 #include <util/system.h>
23 #include <validation.h>
24 #include <version.h>
25 
26 #include <any>
27 
28 #include <boost/algorithm/string.hpp>
29 
30 #include <univalue.h>
31 
32 static const size_t MAX_GETUTXOS_OUTPOINTS = 15; //allow a max of 15 outpoints to be queried at once
33 
34 enum class RetFormat {
35  UNDEF,
36  BINARY,
37  HEX,
38  JSON,
39 };
40 
41 static const struct {
43  const char* name;
44 } rf_names[] = {
45  {RetFormat::UNDEF, ""},
46  {RetFormat::BINARY, "bin"},
47  {RetFormat::HEX, "hex"},
48  {RetFormat::JSON, "json"},
49 };
50 
51 struct CCoin {
52  uint32_t nHeight;
54 
55  CCoin() : nHeight(0) {}
56  explicit CCoin(Coin&& in) : nHeight(in.nHeight), out(std::move(in.out)) {}
57 
59  {
60  uint32_t nTxVerDummy = 0;
61  READWRITE(nTxVerDummy, obj.nHeight, obj.out);
62  }
63 };
64 
65 static bool RESTERR(HTTPRequest* req, enum HTTPStatusCode status, std::string message)
66 {
67  req->WriteHeader("Content-Type", "text/plain");
68  req->WriteReply(status, message + "\r\n");
69  return false;
70 }
71 
79 static NodeContext* GetNodeContext(const std::any& context, HTTPRequest* req)
80 {
81  auto node_context = util::AnyPtr<NodeContext>(context);
82  if (!node_context) {
84  strprintf("%s:%d (%s)\n"
85  "Internal bug detected: Node context not found!\n"
86  "You may report this issue here: %s\n",
87  __FILE__, __LINE__, __func__, PACKAGE_BUGREPORT));
88  return nullptr;
89  }
90  return node_context;
91 }
92 
100 static CTxMemPool* GetMemPool(const std::any& context, HTTPRequest* req)
101 {
102  auto node_context = util::AnyPtr<NodeContext>(context);
103  if (!node_context || !node_context->mempool) {
104  RESTERR(req, HTTP_NOT_FOUND, "Mempool disabled or instance not found");
105  return nullptr;
106  }
107  return node_context->mempool.get();
108 }
109 
110 static RetFormat ParseDataFormat(std::string& param, const std::string& strReq)
111 {
112  const std::string::size_type pos = strReq.rfind('.');
113  if (pos == std::string::npos)
114  {
115  param = strReq;
116  return rf_names[0].rf;
117  }
118 
119  param = strReq.substr(0, pos);
120  const std::string suff(strReq, pos + 1);
121 
122  for (const auto& rf_name : rf_names) {
123  if (suff == rf_name.name)
124  return rf_name.rf;
125  }
126 
127  /* If no suffix is found, return original string. */
128  param = strReq;
129  return rf_names[0].rf;
130 }
131 
132 static std::string AvailableDataFormatsString()
133 {
134  std::string formats;
135  for (const auto& rf_name : rf_names) {
136  if (strlen(rf_name.name) > 0) {
137  formats.append(".");
138  formats.append(rf_name.name);
139  formats.append(", ");
140  }
141  }
142 
143  if (formats.length() > 0)
144  return formats.substr(0, formats.length() - 2);
145 
146  return formats;
147 }
148 
149 static bool CheckWarmup(HTTPRequest* req)
150 {
151  std::string statusmessage;
152  if (RPCIsInWarmup(&statusmessage))
153  return RESTERR(req, HTTP_SERVICE_UNAVAILABLE, "Service temporarily unavailable: " + statusmessage);
154  return true;
155 }
156 
157 static bool rest_headers(const std::any& context,
158  HTTPRequest* req,
159  const std::string& strURIPart)
160 {
161  if (!CheckWarmup(req))
162  return false;
163  std::string param;
164  const RetFormat rf = ParseDataFormat(param, strURIPart);
165  std::vector<std::string> path;
166  boost::split(path, param, boost::is_any_of("/"));
167 
168  if (path.size() != 2)
169  return RESTERR(req, HTTP_BAD_REQUEST, "No header count specified. Use /rest/headers/<count>/<hash>.<ext>.");
170 
171  long count = strtol(path[0].c_str(), nullptr, 10);
172  if (count < 1 || count > 2000)
173  return RESTERR(req, HTTP_BAD_REQUEST, "Header count out of range: " + path[0]);
174 
175  std::string hashStr = path[1];
176  uint256 hash;
177  if (!ParseHashStr(hashStr, hash))
178  return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);
179 
180  const CBlockIndex* tip = nullptr;
181  std::vector<const CBlockIndex *> headers;
182  headers.reserve(count);
183  {
184  ChainstateManager& chainman = EnsureAnyChainman(context);
185  LOCK(cs_main);
186  CChain& active_chain = chainman.ActiveChain();
187  tip = active_chain.Tip();
188  const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(hash);
189  while (pindex != nullptr && active_chain.Contains(pindex)) {
190  headers.push_back(pindex);
191  if (headers.size() == (unsigned long)count)
192  break;
193  pindex = active_chain.Next(pindex);
194  }
195  }
196 
197  switch (rf) {
198  case RetFormat::BINARY: {
200  for (const CBlockIndex *pindex : headers) {
201  ssHeader << pindex->GetBlockHeader();
202  }
203 
204  std::string binaryHeader = ssHeader.str();
205  req->WriteHeader("Content-Type", "application/octet-stream");
206  req->WriteReply(HTTP_OK, binaryHeader);
207  return true;
208  }
209 
210  case RetFormat::HEX: {
212  for (const CBlockIndex *pindex : headers) {
213  ssHeader << pindex->GetBlockHeader();
214  }
215 
216  std::string strHex = HexStr(ssHeader) + "\n";
217  req->WriteHeader("Content-Type", "text/plain");
218  req->WriteReply(HTTP_OK, strHex);
219  return true;
220  }
221  case RetFormat::JSON: {
222  UniValue jsonHeaders(UniValue::VARR);
223  for (const CBlockIndex *pindex : headers) {
224  jsonHeaders.push_back(blockheaderToJSON(tip, pindex));
225  }
226  std::string strJSON = jsonHeaders.write() + "\n";
227  req->WriteHeader("Content-Type", "application/json");
228  req->WriteReply(HTTP_OK, strJSON);
229  return true;
230  }
231  default: {
232  return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: .bin, .hex, .json)");
233  }
234  }
235 }
236 
237 static bool rest_block(const std::any& context,
238  HTTPRequest* req,
239  const std::string& strURIPart,
240  bool showTxDetails)
241 {
242  if (!CheckWarmup(req))
243  return false;
244  std::string hashStr;
245  const RetFormat rf = ParseDataFormat(hashStr, strURIPart);
246 
247  uint256 hash;
248  if (!ParseHashStr(hashStr, hash))
249  return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);
250 
251  CBlock block;
252  CBlockIndex* pblockindex = nullptr;
253  CBlockIndex* tip = nullptr;
254  {
255  ChainstateManager& chainman = EnsureAnyChainman(context);
256  LOCK(cs_main);
257  tip = chainman.ActiveChain().Tip();
258  pblockindex = chainman.m_blockman.LookupBlockIndex(hash);
259  if (!pblockindex) {
260  return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found");
261  }
262 
263  if (IsBlockPruned(pblockindex))
264  return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not available (pruned data)");
265 
266  if (!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus()))
267  return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found");
268  }
269 
270  switch (rf) {
271  case RetFormat::BINARY: {
273  ssBlock << block;
274  std::string binaryBlock = ssBlock.str();
275  req->WriteHeader("Content-Type", "application/octet-stream");
276  req->WriteReply(HTTP_OK, binaryBlock);
277  return true;
278  }
279 
280  case RetFormat::HEX: {
282  ssBlock << block;
283  std::string strHex = HexStr(ssBlock) + "\n";
284  req->WriteHeader("Content-Type", "text/plain");
285  req->WriteReply(HTTP_OK, strHex);
286  return true;
287  }
288 
289  case RetFormat::JSON: {
290  UniValue objBlock = blockToJSON(block, tip, pblockindex, showTxDetails);
291  std::string strJSON = objBlock.write() + "\n";
292  req->WriteHeader("Content-Type", "application/json");
293  req->WriteReply(HTTP_OK, strJSON);
294  return true;
295  }
296 
297  default: {
298  return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
299  }
300  }
301 }
302 
303 static bool rest_block_extended(const std::any& context, HTTPRequest* req, const std::string& strURIPart)
304 {
305  return rest_block(context, req, strURIPart, true);
306 }
307 
308 static bool rest_block_notxdetails(const std::any& context, HTTPRequest* req, const std::string& strURIPart)
309 {
310  return rest_block(context, req, strURIPart, false);
311 }
312 
313 // A bit of a hack - dependency on a function defined in rpc/blockchain.cpp
315 
316 static bool rest_chaininfo(const std::any& context, HTTPRequest* req, const std::string& strURIPart)
317 {
318  if (!CheckWarmup(req))
319  return false;
320  std::string param;
321  const RetFormat rf = ParseDataFormat(param, strURIPart);
322 
323  switch (rf) {
324  case RetFormat::JSON: {
325  JSONRPCRequest jsonRequest;
326  jsonRequest.context = context;
327  jsonRequest.params = UniValue(UniValue::VARR);
328  UniValue chainInfoObject = getblockchaininfo().HandleRequest(jsonRequest);
329  std::string strJSON = chainInfoObject.write() + "\n";
330  req->WriteHeader("Content-Type", "application/json");
331  req->WriteReply(HTTP_OK, strJSON);
332  return true;
333  }
334  default: {
335  return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: json)");
336  }
337  }
338 }
339 
340 static bool rest_mempool_info(const std::any& context, HTTPRequest* req, const std::string& strURIPart)
341 {
342  if (!CheckWarmup(req))
343  return false;
344  const CTxMemPool* mempool = GetMemPool(context, req);
345  if (!mempool) return false;
346  std::string param;
347  const RetFormat rf = ParseDataFormat(param, strURIPart);
348 
349  switch (rf) {
350  case RetFormat::JSON: {
351  UniValue mempoolInfoObject = MempoolInfoToJSON(*mempool);
352 
353  std::string strJSON = mempoolInfoObject.write() + "\n";
354  req->WriteHeader("Content-Type", "application/json");
355  req->WriteReply(HTTP_OK, strJSON);
356  return true;
357  }
358  default: {
359  return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: json)");
360  }
361  }
362 }
363 
364 static bool rest_mempool_contents(const std::any& context, HTTPRequest* req, const std::string& strURIPart)
365 {
366  if (!CheckWarmup(req)) return false;
367  const CTxMemPool* mempool = GetMemPool(context, req);
368  if (!mempool) return false;
369  std::string param;
370  const RetFormat rf = ParseDataFormat(param, strURIPart);
371 
372  switch (rf) {
373  case RetFormat::JSON: {
374  UniValue mempoolObject = MempoolToJSON(*mempool, true);
375 
376  std::string strJSON = mempoolObject.write() + "\n";
377  req->WriteHeader("Content-Type", "application/json");
378  req->WriteReply(HTTP_OK, strJSON);
379  return true;
380  }
381  default: {
382  return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: json)");
383  }
384  }
385 }
386 
387 static bool rest_tx(const std::any& context, HTTPRequest* req, const std::string& strURIPart)
388 {
389  if (!CheckWarmup(req))
390  return false;
391  std::string hashStr;
392  const RetFormat rf = ParseDataFormat(hashStr, strURIPart);
393 
394  uint256 hash;
395  if (!ParseHashStr(hashStr, hash))
396  return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);
397 
398  if (g_txindex) {
399  g_txindex->BlockUntilSyncedToCurrentChain();
400  }
401 
402  const NodeContext* const node = GetNodeContext(context, req);
403  if (!node) return false;
404  uint256 hashBlock = uint256();
405  const CTransactionRef tx = GetTransaction(/* block_index */ nullptr, node->mempool.get(), hash, Params().GetConsensus(), hashBlock);
406  if (!tx) {
407  return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found");
408  }
409 
410  switch (rf) {
411  case RetFormat::BINARY: {
413  ssTx << tx;
414 
415  std::string binaryTx = ssTx.str();
416  req->WriteHeader("Content-Type", "application/octet-stream");
417  req->WriteReply(HTTP_OK, binaryTx);
418  return true;
419  }
420 
421  case RetFormat::HEX: {
423  ssTx << tx;
424 
425  std::string strHex = HexStr(ssTx) + "\n";
426  req->WriteHeader("Content-Type", "text/plain");
427  req->WriteReply(HTTP_OK, strHex);
428  return true;
429  }
430 
431  case RetFormat::JSON: {
432  UniValue objTx(UniValue::VOBJ);
433  TxToUniv(*tx, hashBlock, objTx);
434  std::string strJSON = objTx.write() + "\n";
435  req->WriteHeader("Content-Type", "application/json");
436  req->WriteReply(HTTP_OK, strJSON);
437  return true;
438  }
439 
440  default: {
441  return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
442  }
443  }
444 }
445 
446 static bool rest_getutxos(const std::any& context, HTTPRequest* req, const std::string& strURIPart)
447 {
448  if (!CheckWarmup(req))
449  return false;
450  std::string param;
451  const RetFormat rf = ParseDataFormat(param, strURIPart);
452 
453  std::vector<std::string> uriParts;
454  if (param.length() > 1)
455  {
456  std::string strUriParams = param.substr(1);
457  boost::split(uriParts, strUriParams, boost::is_any_of("/"));
458  }
459 
460  // throw exception in case of an empty request
461  std::string strRequestMutable = req->ReadBody();
462  if (strRequestMutable.length() == 0 && uriParts.size() == 0)
463  return RESTERR(req, HTTP_BAD_REQUEST, "Error: empty request");
464 
465  bool fInputParsed = false;
466  bool fCheckMemPool = false;
467  std::vector<COutPoint> vOutPoints;
468 
469  // parse/deserialize input
470  // input-format = output-format, rest/getutxos/bin requires binary input, gives binary output, ...
471 
472  if (uriParts.size() > 0)
473  {
474  //inputs is sent over URI scheme (/rest/getutxos/checkmempool/txid1-n/txid2-n/...)
475  if (uriParts[0] == "checkmempool") fCheckMemPool = true;
476 
477  for (size_t i = (fCheckMemPool) ? 1 : 0; i < uriParts.size(); i++)
478  {
479  uint256 txid;
480  int32_t nOutput;
481  std::string strTxid = uriParts[i].substr(0, uriParts[i].find('-'));
482  std::string strOutput = uriParts[i].substr(uriParts[i].find('-')+1);
483 
484  if (!ParseInt32(strOutput, &nOutput) || !IsHex(strTxid))
485  return RESTERR(req, HTTP_BAD_REQUEST, "Parse error");
486 
487  txid.SetHex(strTxid);
488  vOutPoints.push_back(COutPoint(txid, (uint32_t)nOutput));
489  }
490 
491  if (vOutPoints.size() > 0)
492  fInputParsed = true;
493  else
494  return RESTERR(req, HTTP_BAD_REQUEST, "Error: empty request");
495  }
496 
497  switch (rf) {
498  case RetFormat::HEX: {
499  // convert hex to bin, continue then with bin part
500  std::vector<unsigned char> strRequestV = ParseHex(strRequestMutable);
501  strRequestMutable.assign(strRequestV.begin(), strRequestV.end());
502  }
503 
504  case RetFormat::BINARY: {
505  try {
506  //deserialize only if user sent a request
507  if (strRequestMutable.size() > 0)
508  {
509  if (fInputParsed) //don't allow sending input over URI and HTTP RAW DATA
510  return RESTERR(req, HTTP_BAD_REQUEST, "Combination of URI scheme inputs and raw post data is not allowed");
511 
513  oss << strRequestMutable;
514  oss >> fCheckMemPool;
515  oss >> vOutPoints;
516  }
517  } catch (const std::ios_base::failure&) {
518  // abort in case of unreadable binary data
519  return RESTERR(req, HTTP_BAD_REQUEST, "Parse error");
520  }
521  break;
522  }
523 
524  case RetFormat::JSON: {
525  if (!fInputParsed)
526  return RESTERR(req, HTTP_BAD_REQUEST, "Error: empty request");
527  break;
528  }
529  default: {
530  return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
531  }
532  }
533 
534  // limit max outpoints
535  if (vOutPoints.size() > MAX_GETUTXOS_OUTPOINTS)
536  return RESTERR(req, HTTP_BAD_REQUEST, strprintf("Error: max outpoints exceeded (max: %d, tried: %d)", MAX_GETUTXOS_OUTPOINTS, vOutPoints.size()));
537 
538  // check spentness and form a bitmap (as well as a JSON capable human-readable string representation)
539  std::vector<unsigned char> bitmap;
540  std::vector<CCoin> outs;
541  std::string bitmapStringRepresentation;
542  std::vector<bool> hits;
543  bitmap.resize((vOutPoints.size() + 7) / 8);
544  ChainstateManager& chainman = EnsureAnyChainman(context);
545  {
546  auto process_utxos = [&vOutPoints, &outs, &hits](const CCoinsView& view, const CTxMemPool& mempool) {
547  for (const COutPoint& vOutPoint : vOutPoints) {
548  Coin coin;
549  bool hit = !mempool.isSpent(vOutPoint) && view.GetCoin(vOutPoint, coin);
550  hits.push_back(hit);
551  if (hit) outs.emplace_back(std::move(coin));
552  }
553  };
554 
555  if (fCheckMemPool) {
556  const CTxMemPool* mempool = GetMemPool(context, req);
557  if (!mempool) return false;
558  // use db+mempool as cache backend in case user likes to query mempool
559  LOCK2(cs_main, mempool->cs);
560  CCoinsViewCache& viewChain = chainman.ActiveChainstate().CoinsTip();
561  CCoinsViewMemPool viewMempool(&viewChain, *mempool);
562  process_utxos(viewMempool, *mempool);
563  } else {
564  LOCK(cs_main); // no need to lock mempool!
565  process_utxos(chainman.ActiveChainstate().CoinsTip(), CTxMemPool());
566  }
567 
568  for (size_t i = 0; i < hits.size(); ++i) {
569  const bool hit = hits[i];
570  bitmapStringRepresentation.append(hit ? "1" : "0"); // form a binary string representation (human-readable for json output)
571  bitmap[i / 8] |= ((uint8_t)hit) << (i % 8);
572  }
573  }
574 
575  switch (rf) {
576  case RetFormat::BINARY: {
577  // serialize data
578  // use exact same output as mentioned in Bip64
579  CDataStream ssGetUTXOResponse(SER_NETWORK, PROTOCOL_VERSION);
580  ssGetUTXOResponse << chainman.ActiveChain().Height() << chainman.ActiveChain().Tip()->GetBlockHash() << bitmap << outs;
581  std::string ssGetUTXOResponseString = ssGetUTXOResponse.str();
582 
583  req->WriteHeader("Content-Type", "application/octet-stream");
584  req->WriteReply(HTTP_OK, ssGetUTXOResponseString);
585  return true;
586  }
587 
588  case RetFormat::HEX: {
589  CDataStream ssGetUTXOResponse(SER_NETWORK, PROTOCOL_VERSION);
590  ssGetUTXOResponse << chainman.ActiveChain().Height() << chainman.ActiveChain().Tip()->GetBlockHash() << bitmap << outs;
591  std::string strHex = HexStr(ssGetUTXOResponse) + "\n";
592 
593  req->WriteHeader("Content-Type", "text/plain");
594  req->WriteReply(HTTP_OK, strHex);
595  return true;
596  }
597 
598  case RetFormat::JSON: {
599  UniValue objGetUTXOResponse(UniValue::VOBJ);
600 
601  // pack in some essentials
602  // use more or less the same output as mentioned in Bip64
603  objGetUTXOResponse.pushKV("chainHeight", chainman.ActiveChain().Height());
604  objGetUTXOResponse.pushKV("chaintipHash", chainman.ActiveChain().Tip()->GetBlockHash().GetHex());
605  objGetUTXOResponse.pushKV("bitmap", bitmapStringRepresentation);
606 
607  UniValue utxos(UniValue::VARR);
608  for (const CCoin& coin : outs) {
609  UniValue utxo(UniValue::VOBJ);
610  utxo.pushKV("height", (int32_t)coin.nHeight);
611  utxo.pushKV("value", ValueFromAmount(coin.out.nValue));
612 
613  // include the script in a json output
615  ScriptPubKeyToUniv(coin.out.scriptPubKey, o, true);
616  utxo.pushKV("scriptPubKey", o);
617  utxos.push_back(utxo);
618  }
619  objGetUTXOResponse.pushKV("utxos", utxos);
620 
621  // return json string
622  std::string strJSON = objGetUTXOResponse.write() + "\n";
623  req->WriteHeader("Content-Type", "application/json");
624  req->WriteReply(HTTP_OK, strJSON);
625  return true;
626  }
627  default: {
628  return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
629  }
630  }
631 }
632 
633 static bool rest_blockhash_by_height(const std::any& context, HTTPRequest* req,
634  const std::string& str_uri_part)
635 {
636  if (!CheckWarmup(req)) return false;
637  std::string height_str;
638  const RetFormat rf = ParseDataFormat(height_str, str_uri_part);
639 
640  int32_t blockheight = -1; // Initialization done only to prevent valgrind false positive, see https://github.com/bitcoin/bitcoin/pull/18785
641  if (!ParseInt32(height_str, &blockheight) || blockheight < 0) {
642  return RESTERR(req, HTTP_BAD_REQUEST, "Invalid height: " + SanitizeString(height_str));
643  }
644 
645  CBlockIndex* pblockindex = nullptr;
646  {
647  ChainstateManager& chainman = EnsureAnyChainman(context);
648  LOCK(cs_main);
649  const CChain& active_chain = chainman.ActiveChain();
650  if (blockheight > active_chain.Height()) {
651  return RESTERR(req, HTTP_NOT_FOUND, "Block height out of range");
652  }
653  pblockindex = active_chain[blockheight];
654  }
655  switch (rf) {
656  case RetFormat::BINARY: {
658  ss_blockhash << pblockindex->GetBlockHash();
659  req->WriteHeader("Content-Type", "application/octet-stream");
660  req->WriteReply(HTTP_OK, ss_blockhash.str());
661  return true;
662  }
663  case RetFormat::HEX: {
664  req->WriteHeader("Content-Type", "text/plain");
665  req->WriteReply(HTTP_OK, pblockindex->GetBlockHash().GetHex() + "\n");
666  return true;
667  }
668  case RetFormat::JSON: {
669  req->WriteHeader("Content-Type", "application/json");
671  resp.pushKV("blockhash", pblockindex->GetBlockHash().GetHex());
672  req->WriteReply(HTTP_OK, resp.write() + "\n");
673  return true;
674  }
675  default: {
676  return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
677  }
678  }
679 }
680 
681 static const struct {
682  const char* prefix;
683  bool (*handler)(const std::any& context, HTTPRequest* req, const std::string& strReq);
684 } uri_prefixes[] = {
685  {"/rest/tx/", rest_tx},
686  {"/rest/block/notxdetails/", rest_block_notxdetails},
687  {"/rest/block/", rest_block_extended},
688  {"/rest/chaininfo", rest_chaininfo},
689  {"/rest/mempool/info", rest_mempool_info},
690  {"/rest/mempool/contents", rest_mempool_contents},
691  {"/rest/headers/", rest_headers},
692  {"/rest/getutxos", rest_getutxos},
693  {"/rest/blockhashbyheight/", rest_blockhash_by_height},
694 };
695 
696 void StartREST(const std::any& context)
697 {
698  for (const auto& up : uri_prefixes) {
699  auto handler = [context, up](HTTPRequest* req, const std::string& prefix) { return up.handler(context, req, prefix); };
700  RegisterHTTPHandler(up.prefix, false, handler);
701  }
702 }
703 
705 {
706 }
707 
708 void StopREST()
709 {
710  for (const auto& up : uri_prefixes) {
711  UnregisterHTTPHandler(up.prefix, false);
712  }
713 }
AvailableDataFormatsString
static std::string AvailableDataFormatsString()
Definition: rest.cpp:132
block.h
ParseHashStr
bool ParseHashStr(const std::string &strHex, uint256 &result)
Parse a hex string into 256 bits.
Definition: core_read.cpp:239
LOCK2
#define LOCK2(cs1, cs2)
Definition: sync.h:233
rest_chaininfo
static bool rest_chaininfo(const std::any &context, HTTPRequest *req, const std::string &strURIPart)
Definition: rest.cpp:316
ParseDataFormat
static RetFormat ParseDataFormat(std::string &param, const std::string &strReq)
Definition: rest.cpp:110
HTTP_SERVICE_UNAVAILABLE
@ HTTP_SERVICE_UNAVAILABLE
Definition: protocol.h:19
ParseHex
std::vector< unsigned char > ParseHex(const char *psz)
Definition: strencodings.cpp:84
UniValue::VOBJ
@ VOBJ
Definition: univalue.h:21
count
static int count
Definition: tests.c:35
check.h
g_txindex
std::unique_ptr< TxIndex > g_txindex
The global transaction index, used in GetTransaction. May be null.
Definition: txindex.cpp:17
TxToUniv
void TxToUniv(const CTransaction &tx, const uint256 &hashBlock, bool include_addresses, UniValue &entry, bool include_hex=true, int serialize_flags=0, const CTxUndo *txundo=nullptr)
Definition: core_write.cpp:193
UnregisterHTTPHandler
void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
Unregister handler for prefix.
Definition: httpserver.cpp:640
RetFormat
RetFormat
Definition: rest.cpp:34
PACKAGE_BUGREPORT
#define PACKAGE_BUGREPORT
Definition: bitcoin-config.h:362
JSONRPCRequest::context
std::any context
Definition: request.h:38
CCoin::CCoin
CCoin(Coin &&in)
Definition: rest.cpp:56
streams.h
RPCHelpMan
Definition: util.h:338
sync.h
handler
bool(* handler)(const std::any &context, HTTPRequest *req, const std::string &strReq)
Definition: rest.cpp:683
transaction.h
HTTPStatusCode
HTTPStatusCode
HTTP status codes.
Definition: protocol.h:10
CTxMemPool
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:477
StartREST
void StartREST(const std::any &context)
Start HTTP REST subsystem.
Definition: rest.cpp:696
IsHex
bool IsHex(const std::string &str)
Definition: strencodings.cpp:61
HTTP_BAD_REQUEST
@ HTTP_BAD_REQUEST
Definition: protocol.h:13
MempoolInfoToJSON
UniValue MempoolInfoToJSON(const CTxMemPool &pool)
Mempool information to JSON.
Definition: blockchain.cpp:1534
CheckWarmup
static bool CheckWarmup(HTTPRequest *req)
Definition: rest.cpp:149
protocol.h
EnsureAnyChainman
ChainstateManager & EnsureAnyChainman(const std::any &context)
Definition: blockchain.cpp:90
RetFormat::UNDEF
@ UNDEF
chainparams.h
UniValue::write
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
Definition: univalue_write.cpp:29
ChainstateManager::ActiveChainstate
CChainState & ActiveChainstate() const
The most-work chain.
Definition: validation.cpp:5357
CTransactionRef
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:386
HTTPRequest::WriteHeader
void WriteHeader(const std::string &hdr, const std::string &value)
Write output header.
Definition: httpserver.cpp:552
CChain::Tip
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:403
cs_main
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: validation.cpp:131
context.h
version.h
rest_getutxos
static bool rest_getutxos(const std::any &context, HTTPRequest *req, const std::string &strURIPart)
Definition: rest.cpp:446
core_io.h
UniValue::pushKV
bool pushKV(const std::string &key, const UniValue &val)
Definition: univalue.cpp:133
ValueFromAmount
UniValue ValueFromAmount(const CAmount amount)
Definition: core_write.cpp:20
validation.h
UniValue
Definition: univalue.h:19
RetFormat::BINARY
@ BINARY
ChainstateManager::ActiveChain
CChain & ActiveChain() const
Definition: validation.h:908
RetFormat::JSON
@ JSON
txmempool.h
txindex.h
CCoinsView
Abstract view on the open txout dataset.
Definition: coins.h:159
prefix
const char * prefix
Definition: rest.cpp:682
rest_tx
static bool rest_tx(const std::any &context, HTTPRequest *req, const std::string &strURIPart)
Definition: rest.cpp:387
rest_block
static bool rest_block(const std::any &context, HTTPRequest *req, const std::string &strURIPart, bool showTxDetails)
Definition: rest.cpp:237
blockheaderToJSON
UniValue blockheaderToJSON(const CBlockIndex *tip, const CBlockIndex *blockindex)
Block header to JSON.
Definition: blockchain.cpp:142
CCoin::out
CTxOut out
Definition: rest.cpp:53
rest_mempool_contents
static bool rest_mempool_contents(const std::any &context, HTTPRequest *req, const std::string &strURIPart)
Definition: rest.cpp:364
CTxMemPool::cs
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition: txmempool.h:565
HTTPRequest
In-flight HTTP request.
Definition: httpserver.h:56
CTxOut
An output of a transaction.
Definition: transaction.h:128
Coin
A UTXO entry.
Definition: coins.h:32
RPCHelpMan::HandleRequest
UniValue HandleRequest(const JSONRPCRequest &request) const
Definition: util.cpp:553
rest_headers
static bool rest_headers(const std::any &context, HTTPRequest *req, const std::string &strURIPart)
Definition: rest.cpp:157
HTTPRequest::ReadBody
std::string ReadBody()
Read request body.
Definition: httpserver.cpp:532
univalue.h
rest_block_notxdetails
static bool rest_block_notxdetails(const std::any &context, HTTPRequest *req, const std::string &strURIPart)
Definition: rest.cpp:308
base_blob::GetHex
std::string GetHex() const
Definition: uint256.cpp:20
GetMemPool
static CTxMemPool * GetMemPool(const std::any &context, HTTPRequest *req)
Get the node context mempool.
Definition: rest.cpp:100
ReadBlockFromDisk
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos, const Consensus::Params &consensusParams)
Functions for disk access for blocks.
Definition: blockstorage.cpp:44
getblockchaininfo
RPCHelpMan getblockchaininfo()
Definition: blockchain.cpp:1312
uint256
256-bit opaque blob.
Definition: uint256.h:124
READWRITE
#define READWRITE(...)
Definition: serialize.h:175
StopREST
void StopREST()
Stop HTTP REST subsystem.
Definition: rest.cpp:708
rest_block_extended
static bool rest_block_extended(const std::any &context, HTTPRequest *req, const std::string &strURIPart)
Definition: rest.cpp:303
chain.h
rest_blockhash_by_height
static bool rest_blockhash_by_height(const std::any &context, HTTPRequest *req, const std::string &str_uri_part)
Definition: rest.cpp:633
RESTERR
static bool RESTERR(HTTPRequest *req, enum HTTPStatusCode status, std::string message)
Definition: rest.cpp:65
rest_mempool_info
static bool rest_mempool_info(const std::any &context, HTTPRequest *req, const std::string &strURIPart)
Definition: rest.cpp:340
CBlockIndex::GetBlockHash
uint256 GetBlockHash() const
Definition: chain.h:246
CCoin::SERIALIZE_METHODS
SERIALIZE_METHODS(CCoin, obj)
Definition: rest.cpp:58
CChain::Height
int Height() const
Return the maximal height in the chain.
Definition: chain.h:428
rf
RetFormat rf
Definition: rest.cpp:42
JSONRPCRequest::params
UniValue params
Definition: request.h:33
ChainstateManager
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:807
name
const char * name
Definition: rest.cpp:43
system.h
CBlock
Definition: block.h:62
strprintf
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
MempoolToJSON
UniValue MempoolToJSON(const CTxMemPool &pool, bool verbose, bool include_mempool_sequence)
Mempool to JSON.
Definition: blockchain.cpp:514
ParseInt32
bool ParseInt32(const std::string &str, int32_t *out)
Convert string to signed 32-bit integer with strict parse error feedback.
Definition: strencodings.cpp:296
SanitizeString
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
Definition: strencodings.cpp:27
CChain
An in-memory indexed chain of blocks.
Definition: chain.h:392
HTTP_OK
@ HTTP_OK
Definition: protocol.h:12
uri_prefixes
static const struct @10 uri_prefixes[]
CCoinsViewCache
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:215
LOCK
#define LOCK(cs)
Definition: sync.h:232
MAX_GETUTXOS_OUTPOINTS
static const size_t MAX_GETUTXOS_OUTPOINTS
Definition: rest.cpp:32
blockstorage.h
RPCSerializationFlags
int RPCSerializationFlags()
Definition: server.cpp:540
CCoin::nHeight
uint32_t nHeight
Definition: rest.cpp:52
RetFormat::HEX
@ HEX
HTTP_NOT_FOUND
@ HTTP_NOT_FOUND
Definition: protocol.h:16
CCoinsViewMemPool
CCoinsView that brings transactions from a mempool into view.
Definition: txmempool.h:863
UniValue::push_back
bool push_back(const UniValue &val)
Definition: univalue.cpp:108
ScriptPubKeyToUniv
void ScriptPubKeyToUniv(const CScript &scriptPubKey, UniValue &out, bool fIncludeHex, bool include_addresses)
Definition: core_write.cpp:161
Params
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:538
CChain::Contains
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:415
node
Definition: interfaces.cpp:66
CDataStream
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:204
GetNodeContext
static NodeContext * GetNodeContext(const std::any &context, HTTPRequest *req)
Get the node context.
Definition: rest.cpp:79
SER_NETWORK
@ SER_NETWORK
Definition: serialize.h:166
JSONRPCRequest
Definition: request.h:28
COutPoint
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:26
blockchain.h
httpserver.h
rf_names
static const struct @9 rf_names[]
RPCIsInWarmup
bool RPCIsInWarmup(std::string *outStatus)
Definition: server.cpp:344
UniValue::VARR
@ VARR
Definition: univalue.h:21
NodeContext
NodeContext struct containing references to chain state and connection state.
Definition: context.h:38
server.h
CBlockIndex
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:137
CDataStream::str
std::string str() const
Definition: streams.h:242
HexStr
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: strencodings.cpp:594
RegisterHTTPHandler
void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
Register handler for prefix.
Definition: httpserver.cpp:634
HTTPRequest::WriteReply
void WriteReply(int nStatus, const std::string &strReply="")
Write HTTP reply.
Definition: httpserver.cpp:564
CCoin
Definition: rest.cpp:51
IsBlockPruned
bool IsBlockPruned(const CBlockIndex *pblockindex)
Check whether the block associated with this index entry is pruned or not.
Definition: validation.h:1017
base_blob::SetHex
void SetHex(const char *psz)
Definition: uint256.cpp:30
CChainState::CoinsTip
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: validation.h:613
CChain::Next
CBlockIndex * Next(const CBlockIndex *pindex) const
Find the successor of a block in this chain, or nullptr if the given index is not found or is the tip...
Definition: chain.h:420
InterruptREST
void InterruptREST()
Interrupt RPC REST subsystem.
Definition: rest.cpp:704
CCoin::CCoin
CCoin()
Definition: rest.cpp:55
GetTransaction
CTransactionRef GetTransaction(const CBlockIndex *const block_index, const CTxMemPool *const mempool, const uint256 &hash, const Consensus::Params &consensusParams, uint256 &hashBlock)
Return transaction from the block at block_index.
Definition: validation.cpp:1125
blockToJSON
UniValue blockToJSON(const CBlock &block, const CBlockIndex *tip, const CBlockIndex *blockindex, bool txDetails)
Block description to JSON.
Definition: blockchain.cpp:171
PROTOCOL_VERSION
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:12
HTTP_INTERNAL_SERVER_ERROR
@ HTTP_INTERNAL_SERVER_ERROR
Definition: protocol.h:18