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 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)");
279 bool showTxDetails) {
298 if (!maybe_chainman) {
310 if (chainman.
m_blockman.IsBlockPruned(pblockindex)) {
312 hashStr +
" not available (pruned data)");
324 std::string binaryBlock = ssBlock.
str();
325 req->
WriteHeader(
"Content-Type",
"application/octet-stream");
334 std::string strHex =
HexStr(ssBlock) +
"\n";
342 pblockindex, showTxDetails);
343 std::string strJSON = objBlock.
write() +
"\n";
344 req->
WriteHeader(
"Content-Type",
"application/json");
351 "output format not found (available: " +
359 const std::string &strURIPart) {
360 return rest_block(config, context, req, strURIPart,
true);
365 const std::string &strURIPart) {
366 return rest_block(config, context, req, strURIPart,
false);
385 std::string strJSON = chainInfoObject.
write() +
"\n";
386 req->
WriteHeader(
"Content-Type",
"application/json");
392 "output format not found (available: json)");
415 std::string strJSON = mempoolInfoObject.
write() +
"\n";
416 req->
WriteHeader(
"Content-Type",
"application/json");
422 "output format not found (available: json)");
429 const std::string &strURIPart) {
446 std::string strJSON = mempoolObject.
write() +
"\n";
447 req->
WriteHeader(
"Content-Type",
"application/json");
453 "output format not found (available: json)");
459 const std::string &strURIPart) {
472 const TxId txid(hash);
475 g_txindex->BlockUntilSyncedToCurrentChain();
485 hashBlock,
node->chainman->m_blockman);
496 std::string binaryTx = ssTx.
str();
497 req->
WriteHeader(
"Content-Type",
"application/octet-stream");
507 std::string strHex =
HexStr(ssTx) +
"\n";
516 std::string strJSON = objTx.
write() +
"\n";
517 req->
WriteHeader(
"Content-Type",
"application/json");
524 "output format not found (available: " +
539 std::vector<std::string> uriParts;
540 if (param.length() > 1) {
541 std::string strUriParams = param.substr(1);
546 std::string strRequestMutable = req->
ReadBody();
547 if (strRequestMutable.length() == 0 && uriParts.size() == 0) {
551 bool fInputParsed =
false;
552 bool fCheckMemPool =
false;
553 std::vector<COutPoint> vOutPoints;
559 if (uriParts.size() > 0) {
562 if (uriParts[0] ==
"checkmempool") {
563 fCheckMemPool =
true;
566 for (
size_t i = (fCheckMemPool) ? 1 : 0; i < uriParts.size(); i++) {
568 std::string strTxid = uriParts[i].substr(0, uriParts[i].find(
'-'));
569 std::string strOutput =
570 uriParts[i].substr(uriParts[i].find(
'-') + 1);
578 vOutPoints.push_back(COutPoint(txid, uint32_t(nOutput)));
581 if (vOutPoints.size() > 0) {
591 std::vector<uint8_t> strRequestV =
ParseHex(strRequestMutable);
592 strRequestMutable.assign(strRequestV.begin(), strRequestV.end());
598 if (strRequestMutable.size() > 0) {
602 "Combination of URI scheme inputs and "
603 "raw post data is not allowed");
607 oss << strRequestMutable;
608 oss >> fCheckMemPool;
611 }
catch (
const std::ios_base::failure &) {
626 "output format not found (available: " +
635 strprintf(
"Error: max outpoints exceeded (max: %d, tried: %d)",
641 std::vector<uint8_t> bitmap;
642 std::vector<CCoin> outs;
643 std::string bitmapStringRepresentation;
644 std::vector<bool> hits;
645 bitmap.resize((vOutPoints.size() + 7) / 8);
647 if (!maybe_chainman) {
655 [&vOutPoints, &outs, &hits, &active_height, &active_hash,
658 for (
const COutPoint &vOutPoint : vOutPoints) {
660 bool hit = (!mempool || !mempool->isSpent(vOutPoint)) &&
661 view.GetCoin(vOutPoint, coin);
664 outs.emplace_back(std::move(coin));
682 process_utxos(viewMempool, mempool);
689 for (
size_t i = 0; i < hits.size(); ++i) {
690 const bool hit = hits[i];
693 bitmapStringRepresentation.append(hit ?
"1" :
"0");
694 bitmap[i / 8] |= ((uint8_t)hit) << (i % 8);
703 ssGetUTXOResponse << active_height << active_hash << bitmap << outs;
704 std::string ssGetUTXOResponseString = ssGetUTXOResponse.
str();
706 req->
WriteHeader(
"Content-Type",
"application/octet-stream");
713 ssGetUTXOResponse << active_height << active_hash << bitmap << outs;
714 std::string strHex =
HexStr(ssGetUTXOResponse) +
"\n";
726 objGetUTXOResponse.
pushKV(
"chainHeight", active_height);
727 objGetUTXOResponse.
pushKV(
"chaintipHash", active_hash.
GetHex());
728 objGetUTXOResponse.
pushKV(
"bitmap", bitmapStringRepresentation);
731 for (
const CCoin &coin : outs) {
733 utxo.
pushKV(
"height", int32_t(coin.nHeight));
734 utxo.
pushKV(
"value", coin.out.nValue);
739 utxo.
pushKV(
"scriptPubKey", o);
742 objGetUTXOResponse.
pushKV(
"utxos", utxos);
745 std::string strJSON = objGetUTXOResponse.
write() +
"\n";
746 req->
WriteHeader(
"Content-Type",
"application/json");
752 "output format not found (available: " +
760 const std::string &str_uri_part) {
764 std::string height_str;
768 if (!
ParseInt32(height_str, &blockheight) || blockheight < 0) {
776 if (!maybe_chainman) {
782 if (blockheight > active_chain.
Height()) {
785 pblockindex = active_chain[blockheight];
791 req->
WriteHeader(
"Content-Type",
"application/octet-stream");
802 req->
WriteHeader(
"Content-Type",
"application/json");
810 "output format not found (available: " +
819 const std::string &strReq);
835 const std::string &
prefix) {
836 return up.handler(config, context, req,
prefix);
RPCHelpMan getblockchaininfo()
UniValue blockToJSON(BlockManager &blockman, const CBlock &block, const CBlockIndex *tip, const CBlockIndex *blockindex, bool txDetails)
Block description to JSON.
UniValue blockheaderToJSON(const CBlockIndex *tip, const CBlockIndex *blockindex)
Block header 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.
Double ended buffer combining vector and stream-like interfaces.
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...
RecursiveMutex & GetMutex() const LOCK_RETURNED(
Alias for cs_main.
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
SnapshotCompletionResult MaybeCompleteSnapshotValidation(std::function< void(bilingual_str)> shutdown_fnc=[](bilingual_str msg) { AbortNode(msg.original, msg);}) EXCLUSIVE_LOCKS_REQUIRED(Chainstate & ActiveChainstate() const
Once the background validation chainstate has reached the height which is the base of the UTXO snapsh...
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...
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 TxToUniv(const CTransaction &tx, const BlockHash &hashBlock, UniValue &entry, bool include_hex=true, int serialize_flags=0, const CTxUndo *txundo=nullptr)
void ScriptPubKeyToUniv(const CScript &scriptPubKey, UniValue &out, bool fIncludeHex)
bool ParseHashStr(const std::string &strHex, uint256 &result)
Parse a hex string into 256 bits.
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)
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_block(const Config &config, const std::any &context, HTTPRequest *req, const std::string &strURIPart, bool showTxDetails)
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.
int RPCSerializationFlags()
Retrieves any serialization flags requested in command line argument.
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.
static const int PROTOCOL_VERSION
network protocol versioning