64 uint32_t nTxVerDummy = 0;
65 READWRITE(nTxVerDummy, obj.nHeight, obj.out);
70 std::string message) {
84 auto node_context = util::AnyPtr<NodeContext>(context);
88 "Internal bug detected: Node context not found!\n"
89 "You may report this issue here: %s\n",
90 __FILE__, __LINE__, __func__, PACKAGE_BUGREPORT));
104 auto node_context = util::AnyPtr<NodeContext>(context);
105 if (!node_context || !node_context->mempool) {
109 return node_context->mempool.get();
121 auto node_context = util::AnyPtr<NodeContext>(context);
122 if (!node_context || !node_context->chainman) {
125 "Internal bug detected: Chainman disabled or instance"
127 "You may report this issue here: %s\n",
128 __FILE__, __LINE__, __func__, PACKAGE_BUGREPORT));
131 return node_context->chainman.get();
135 const std::string &strReq) {
136 const std::string::size_type pos = strReq.rfind(
'.');
137 if (pos == std::string::npos) {
142 param = strReq.substr(0, pos);
143 const std::string suff(strReq, pos + 1);
145 for (
const auto &rf_name :
rf_names) {
146 if (suff == rf_name.name) {
158 for (
const auto &rf_name :
rf_names) {
159 if (strlen(rf_name.name) > 0) {
161 formats.append(rf_name.name);
162 formats.append(
", ");
166 if (formats.length() > 0) {
167 return formats.substr(0, formats.length() - 2);
174 std::string statusmessage;
177 "Service temporarily unavailable: " + statusmessage);
191 std::vector<std::string> path =
SplitString(param,
'/');
193 if (path.size() != 2) {
195 "No header count specified. Use "
196 "/rest/headers/<count>/<hash>.<ext>.");
199 long count = strtol(path[0].c_str(),
nullptr, 10);
200 if (count < 1 || count > 2000) {
202 "Header count out of range: " + path[0]);
205 const std::string &hashStr = path[1];
214 std::vector<const CBlockIndex *> headers;
215 headers.reserve(
count);
218 if (!maybe_chainman) {
224 tip = active_chain.
Tip();
226 while (pindex !=
nullptr && active_chain.
Contains(pindex)) {
227 headers.push_back(pindex);
228 if (headers.size() ==
size_t(
count)) {
231 pindex = active_chain.
Next(pindex);
239 ssHeader << pindex->GetBlockHeader();
242 std::string binaryHeader = ssHeader.
str();
243 req->
WriteHeader(
"Content-Type",
"application/octet-stream");
251 ssHeader << pindex->GetBlockHeader();
254 std::string strHex =
HexStr(ssHeader) +
"\n";
264 std::string strJSON = jsonHeaders.
write() +
"\n";
265 req->
WriteHeader(
"Content-Type",
"application/json");
272 "output format not found (available: .bin, .hex, .json)");
298 if (!maybe_chainman) {
309 if (chainman.
m_blockman.IsBlockPruned(*pblockindex)) {
311 hashStr +
" not available (pruned data)");
322 std::string binaryBlock = ssBlock.str();
323 req->
WriteHeader(
"Content-Type",
"application/octet-stream");
331 std::string strHex =
HexStr(ssBlock) +
"\n";
339 *pblockindex, tx_verbosity);
340 std::string strJSON = objBlock.
write() +
"\n";
341 req->
WriteHeader(
"Content-Type",
"application/json");
348 "output format not found (available: " +
356 const std::string &strURIPart) {
357 return rest_block(config, context, req, strURIPart,
363 const std::string &strURIPart) {
383 std::string strJSON = chainInfoObject.
write() +
"\n";
384 req->
WriteHeader(
"Content-Type",
"application/json");
390 "output format not found (available: json)");
413 std::string strJSON = mempoolInfoObject.
write() +
"\n";
414 req->
WriteHeader(
"Content-Type",
"application/json");
420 "output format not found (available: json)");
427 const std::string &strURIPart) {
444 std::string strJSON = mempoolObject.
write() +
"\n";
445 req->
WriteHeader(
"Content-Type",
"application/json");
451 "output format not found (available: json)");
457 const std::string &strURIPart) {
470 const TxId txid(hash);
473 g_txindex->BlockUntilSyncedToCurrentChain();
483 hashBlock,
node->chainman->m_blockman);
493 std::string binaryTx = ssTx.
str();
494 req->
WriteHeader(
"Content-Type",
"application/octet-stream");
503 std::string strHex =
HexStr(ssTx) +
"\n";
512 std::string strJSON = objTx.
write() +
"\n";
513 req->
WriteHeader(
"Content-Type",
"application/json");
520 "output format not found (available: " +
535 std::vector<std::string> uriParts;
536 if (param.length() > 1) {
537 std::string strUriParams = param.substr(1);
542 std::string strRequestMutable = req->
ReadBody();
543 if (strRequestMutable.length() == 0 && uriParts.size() == 0) {
547 bool fInputParsed =
false;
548 bool fCheckMemPool =
false;
549 std::vector<COutPoint> vOutPoints;
555 if (uriParts.size() > 0) {
558 if (uriParts[0] ==
"checkmempool") {
559 fCheckMemPool =
true;
562 for (
size_t i = (fCheckMemPool) ? 1 : 0; i < uriParts.size(); i++) {
564 std::string strTxid = uriParts[i].substr(0, uriParts[i].find(
'-'));
565 std::string strOutput =
566 uriParts[i].substr(uriParts[i].find(
'-') + 1);
574 vOutPoints.push_back(COutPoint(txid, uint32_t(nOutput)));
577 if (vOutPoints.size() > 0) {
587 std::vector<uint8_t> strRequestV =
ParseHex(strRequestMutable);
588 strRequestMutable.assign(strRequestV.begin(), strRequestV.end());
594 if (strRequestMutable.size() > 0) {
598 "Combination of URI scheme inputs and "
599 "raw post data is not allowed");
603 oss << strRequestMutable;
604 oss >> fCheckMemPool;
607 }
catch (
const std::ios_base::failure &) {
622 "output format not found (available: " +
631 strprintf(
"Error: max outpoints exceeded (max: %d, tried: %d)",
637 std::vector<uint8_t> bitmap;
638 std::vector<CCoin> outs;
639 std::string bitmapStringRepresentation;
640 std::vector<bool> hits;
641 bitmap.resize((vOutPoints.size() + 7) / 8);
643 if (!maybe_chainman) {
651 [&vOutPoints, &outs, &hits, &active_height, &active_hash,
654 for (
const COutPoint &vOutPoint : vOutPoints) {
656 bool hit = (!mempool || !mempool->isSpent(vOutPoint)) &&
657 view.GetCoin(vOutPoint, coin);
660 outs.emplace_back(std::move(coin));
678 process_utxos(viewMempool, mempool);
685 for (
size_t i = 0; i < hits.size(); ++i) {
686 const bool hit = hits[i];
689 bitmapStringRepresentation.append(hit ?
"1" :
"0");
690 bitmap[i / 8] |= ((uint8_t)hit) << (i % 8);
699 ssGetUTXOResponse << active_height << active_hash << bitmap << outs;
700 std::string ssGetUTXOResponseString = ssGetUTXOResponse.str();
702 req->
WriteHeader(
"Content-Type",
"application/octet-stream");
709 ssGetUTXOResponse << active_height << active_hash << bitmap << outs;
710 std::string strHex =
HexStr(ssGetUTXOResponse) +
"\n";
722 objGetUTXOResponse.
pushKV(
"chainHeight", active_height);
723 objGetUTXOResponse.
pushKV(
"chaintipHash", active_hash.
GetHex());
724 objGetUTXOResponse.
pushKV(
"bitmap", bitmapStringRepresentation);
727 for (
const CCoin &coin : outs) {
729 utxo.
pushKV(
"height", int32_t(coin.nHeight));
730 utxo.
pushKV(
"value", coin.out.nValue);
735 utxo.
pushKV(
"scriptPubKey", std::move(o));
738 objGetUTXOResponse.
pushKV(
"utxos", std::move(utxos));
741 std::string strJSON = objGetUTXOResponse.
write() +
"\n";
742 req->
WriteHeader(
"Content-Type",
"application/json");
748 "output format not found (available: " +
756 const std::string &str_uri_part) {
760 std::string height_str;
764 if (!
ParseInt32(height_str, &blockheight) || blockheight < 0) {
772 if (!maybe_chainman) {
778 if (blockheight > active_chain.
Height()) {
781 pblockindex = active_chain[blockheight];
787 req->
WriteHeader(
"Content-Type",
"application/octet-stream");
798 req->
WriteHeader(
"Content-Type",
"application/json");
806 "output format not found (available: " +
815 const std::string &strReq);
831 const std::string &
prefix) {
832 return up.handler(config, context, req,
prefix);
RPCHelpMan getblockchaininfo()
UniValue blockheaderToJSON(const CBlockIndex &tip, const CBlockIndex &blockindex)
Block header to JSON.
UniValue blockToJSON(BlockManager &blockman, const CBlock &block, const CBlockIndex &tip, const CBlockIndex &blockindex, TxVerbosity verbosity)
Block description to JSON.
The block chain is a tree shaped structure starting with the genesis block at the root,...
BlockHash GetBlockHash() const
An in-memory indexed chain of blocks.
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
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...
int Height() const
Return the maximal height in the chain.
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Abstract view on the open txout dataset.
CCoinsView that brings transactions from a mempool into view.
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
An output of a transaction.
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
SnapshotCompletionResult MaybeCompleteSnapshotValidation() EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex *GetSnapshotBaseBlock() const EXCLUSIVE_LOCKS_REQUIRED(Chainstate ActiveChainstate)() const
Once the background validation chainstate has reached the height which is the base of the UTXO snapsh...
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
CChain & ActiveChain() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Double ended buffer combining vector and stream-like interfaces.
void WriteReply(int nStatus, const std::string &strReply="")
Write HTTP reply.
void WriteHeader(const std::string &hdr, const std::string &value)
Write output header.
std::string ReadBody()
Read request body.
UniValue HandleRequest(const Config &config, const JSONRPCRequest &request) const
void push_back(UniValue val)
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
void pushKV(std::string key, UniValue val)
void SetHex(const char *psz)
std::string GetHex() const
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos) const
Functions for disk access for blocks.
CBlockIndex * LookupBlockIndex(const BlockHash &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
void ScriptPubKeyToUniv(const CScript &scriptPubKey, UniValue &out, bool fIncludeHex)
bool ParseHashStr(const std::string &strHex, uint256 &result)
Parse a hex string into 256 bits.
TxVerbosity
Verbose level for block's transaction.
@ SHOW_DETAILS_AND_PREVOUT
The same as previous option with information about prevouts if available.
@ SHOW_TXID
Only TXID for each block's transaction.
void TxToUniv(const CTransaction &tx, const BlockHash &hashBlock, UniValue &entry, bool include_hex=true, const CTxUndo *txundo=nullptr, TxVerbosity verbosity=TxVerbosity::SHOW_DETAILS, std::function< bool(const CTxOut &)> is_change_func={})
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
Unregister handler for prefix.
void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
Register handler for prefix.
UniValue MempoolInfoToJSON(const CTxMemPool &pool)
Mempool information to JSON.
UniValue MempoolToJSON(const CTxMemPool &pool, bool verbose, bool include_mempool_sequence)
Mempool to JSON.
CTransactionRef GetTransaction(const CBlockIndex *const block_index, const CTxMemPool *const mempool, const TxId &txid, BlockHash &hashBlock, const BlockManager &blockman)
Return transaction with a given txid.
Implement std::hash so RCUPtr can be used as a key for maps or sets.
std::shared_ptr< const CTransaction > CTransactionRef
static RetFormat ParseDataFormat(std::string ¶m, const std::string &strReq)
static bool rest_blockhash_by_height(Config &config, const std::any &context, HTTPRequest *req, const std::string &str_uri_part)
void StartREST(const std::any &context)
Start HTTP REST subsystem.
bool(* handler)(Config &config, const std::any &context, HTTPRequest *req, const std::string &strReq)
static bool rest_block(const Config &config, const std::any &context, HTTPRequest *req, const std::string &strURIPart, TxVerbosity tx_verbosity)
void StopREST()
Stop HTTP REST subsystem.
static bool rest_mempool_info(Config &config, const std::any &context, HTTPRequest *req, const std::string &strURIPart)
static const struct @12 rf_names[]
static bool rest_headers(Config &config, const std::any &context, HTTPRequest *req, const std::string &strURIPart)
static bool rest_block_extended(Config &config, const std::any &context, HTTPRequest *req, const std::string &strURIPart)
static bool rest_mempool_contents(Config &config, const std::any &context, HTTPRequest *req, const std::string &strURIPart)
void InterruptREST()
Interrupt RPC REST subsystem.
static bool RESTERR(HTTPRequest *req, enum HTTPStatusCode status, std::string message)
static bool CheckWarmup(HTTPRequest *req)
static bool rest_block_notxdetails(Config &config, const std::any &context, HTTPRequest *req, const std::string &strURIPart)
static ChainstateManager * GetChainman(const std::any &context, HTTPRequest *req)
Get the node context chainstatemanager.
static bool rest_chaininfo(Config &config, const std::any &context, HTTPRequest *req, const std::string &strURIPart)
static bool rest_tx(Config &config, const std::any &context, HTTPRequest *req, const std::string &strURIPart)
static const struct @13 uri_prefixes[]
static CTxMemPool * GetMemPool(const std::any &context, HTTPRequest *req)
Get the node context mempool.
static bool rest_getutxos(Config &config, const std::any &context, HTTPRequest *req, const std::string &strURIPart)
static const size_t MAX_GETUTXOS_OUTPOINTS
static std::string AvailableDataFormatsString()
static NodeContext * GetNodeContext(const std::any &context, HTTPRequest *req)
Get the node context.
HTTPStatusCode
HTTP status codes.
@ HTTP_SERVICE_UNAVAILABLE
@ HTTP_INTERNAL_SERVER_ERROR
bool RPCIsInWarmup(std::string *outStatus)
Returns the current warmup state.
std::vector< std::string > SplitString(std::string_view str, char sep)
A BlockHash is a unqiue identifier for a block.
SERIALIZE_METHODS(CCoin, obj)
A TxId is the identifier of a transaction.
NodeContext struct containing references to chain state and connection state.
#define EXCLUSIVE_LOCKS_REQUIRED(...)
std::unique_ptr< TxIndex > g_txindex
The global transaction index, used in GetTransaction. May be null.
bool ParseInt32(std::string_view str, int32_t *out)
Convert string to signed 32-bit integer with strict parse error feedback.
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
template std::vector< std::byte > ParseHex(std::string_view)
bool IsHex(std::string_view str)
Returns true if each character in str is a hex character, and has an even number of hex digits.
std::string SanitizeString(std::string_view str, int rule)
Remove unsafe chars.