Merge #10027: Set to nullptr after delete
[bitcoinplatinum.git] / src / rest.cpp
blob54eefcafe364fc570afbebcff49505725760774d
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 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.
6 #include "chain.h"
7 #include "chainparams.h"
8 #include "primitives/block.h"
9 #include "primitives/transaction.h"
10 #include "validation.h"
11 #include "httpserver.h"
12 #include "rpc/server.h"
13 #include "streams.h"
14 #include "sync.h"
15 #include "txmempool.h"
16 #include "utilstrencodings.h"
17 #include "version.h"
19 #include <boost/algorithm/string.hpp>
21 #include <univalue.h>
23 static const size_t MAX_GETUTXOS_OUTPOINTS = 15; //allow a max of 15 outpoints to be queried at once
25 enum RetFormat {
26 RF_UNDEF,
27 RF_BINARY,
28 RF_HEX,
29 RF_JSON,
32 static const struct {
33 enum RetFormat rf;
34 const char* name;
35 } rf_names[] = {
36 {RF_UNDEF, ""},
37 {RF_BINARY, "bin"},
38 {RF_HEX, "hex"},
39 {RF_JSON, "json"},
42 struct CCoin {
43 uint32_t nTxVer; // Don't call this nVersion, that name has a special meaning inside IMPLEMENT_SERIALIZE
44 uint32_t nHeight;
45 CTxOut out;
47 ADD_SERIALIZE_METHODS;
49 template <typename Stream, typename Operation>
50 inline void SerializationOp(Stream& s, Operation ser_action)
52 READWRITE(nTxVer);
53 READWRITE(nHeight);
54 READWRITE(out);
58 extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry);
59 extern UniValue blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool txDetails = false);
60 extern UniValue mempoolInfoToJSON();
61 extern UniValue mempoolToJSON(bool fVerbose = false);
62 extern void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex);
63 extern UniValue blockheaderToJSON(const CBlockIndex* blockindex);
65 static bool RESTERR(HTTPRequest* req, enum HTTPStatusCode status, std::string message)
67 req->WriteHeader("Content-Type", "text/plain");
68 req->WriteReply(status, message + "\r\n");
69 return false;
72 static enum RetFormat ParseDataFormat(std::string& param, const std::string& strReq)
74 const std::string::size_type pos = strReq.rfind('.');
75 if (pos == std::string::npos)
77 param = strReq;
78 return rf_names[0].rf;
81 param = strReq.substr(0, pos);
82 const std::string suff(strReq, pos + 1);
84 for (unsigned int i = 0; i < ARRAYLEN(rf_names); i++)
85 if (suff == rf_names[i].name)
86 return rf_names[i].rf;
88 /* If no suffix is found, return original string. */
89 param = strReq;
90 return rf_names[0].rf;
93 static std::string AvailableDataFormatsString()
95 std::string formats = "";
96 for (unsigned int i = 0; i < ARRAYLEN(rf_names); i++)
97 if (strlen(rf_names[i].name) > 0) {
98 formats.append(".");
99 formats.append(rf_names[i].name);
100 formats.append(", ");
103 if (formats.length() > 0)
104 return formats.substr(0, formats.length() - 2);
106 return formats;
109 static bool ParseHashStr(const std::string& strReq, uint256& v)
111 if (!IsHex(strReq) || (strReq.size() != 64))
112 return false;
114 v.SetHex(strReq);
115 return true;
118 static bool CheckWarmup(HTTPRequest* req)
120 std::string statusmessage;
121 if (RPCIsInWarmup(&statusmessage))
122 return RESTERR(req, HTTP_SERVICE_UNAVAILABLE, "Service temporarily unavailable: " + statusmessage);
123 return true;
126 static bool rest_headers(HTTPRequest* req,
127 const std::string& strURIPart)
129 if (!CheckWarmup(req))
130 return false;
131 std::string param;
132 const RetFormat rf = ParseDataFormat(param, strURIPart);
133 std::vector<std::string> path;
134 boost::split(path, param, boost::is_any_of("/"));
136 if (path.size() != 2)
137 return RESTERR(req, HTTP_BAD_REQUEST, "No header count specified. Use /rest/headers/<count>/<hash>.<ext>.");
139 long count = strtol(path[0].c_str(), NULL, 10);
140 if (count < 1 || count > 2000)
141 return RESTERR(req, HTTP_BAD_REQUEST, "Header count out of range: " + path[0]);
143 std::string hashStr = path[1];
144 uint256 hash;
145 if (!ParseHashStr(hashStr, hash))
146 return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);
148 std::vector<const CBlockIndex *> headers;
149 headers.reserve(count);
151 LOCK(cs_main);
152 BlockMap::const_iterator it = mapBlockIndex.find(hash);
153 const CBlockIndex *pindex = (it != mapBlockIndex.end()) ? it->second : NULL;
154 while (pindex != NULL && chainActive.Contains(pindex)) {
155 headers.push_back(pindex);
156 if (headers.size() == (unsigned long)count)
157 break;
158 pindex = chainActive.Next(pindex);
162 CDataStream ssHeader(SER_NETWORK, PROTOCOL_VERSION);
163 BOOST_FOREACH(const CBlockIndex *pindex, headers) {
164 ssHeader << pindex->GetBlockHeader();
167 switch (rf) {
168 case RF_BINARY: {
169 std::string binaryHeader = ssHeader.str();
170 req->WriteHeader("Content-Type", "application/octet-stream");
171 req->WriteReply(HTTP_OK, binaryHeader);
172 return true;
175 case RF_HEX: {
176 std::string strHex = HexStr(ssHeader.begin(), ssHeader.end()) + "\n";
177 req->WriteHeader("Content-Type", "text/plain");
178 req->WriteReply(HTTP_OK, strHex);
179 return true;
181 case RF_JSON: {
182 UniValue jsonHeaders(UniValue::VARR);
183 BOOST_FOREACH(const CBlockIndex *pindex, headers) {
184 jsonHeaders.push_back(blockheaderToJSON(pindex));
186 std::string strJSON = jsonHeaders.write() + "\n";
187 req->WriteHeader("Content-Type", "application/json");
188 req->WriteReply(HTTP_OK, strJSON);
189 return true;
191 default: {
192 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: .bin, .hex)");
196 // not reached
197 return true; // continue to process further HTTP reqs on this cxn
200 static bool rest_block(HTTPRequest* req,
201 const std::string& strURIPart,
202 bool showTxDetails)
204 if (!CheckWarmup(req))
205 return false;
206 std::string hashStr;
207 const RetFormat rf = ParseDataFormat(hashStr, strURIPart);
209 uint256 hash;
210 if (!ParseHashStr(hashStr, hash))
211 return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);
213 CBlock block;
214 CBlockIndex* pblockindex = NULL;
216 LOCK(cs_main);
217 if (mapBlockIndex.count(hash) == 0)
218 return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found");
220 pblockindex = mapBlockIndex[hash];
221 if (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0)
222 return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not available (pruned data)");
224 if (!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus()))
225 return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found");
228 CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags());
229 ssBlock << block;
231 switch (rf) {
232 case RF_BINARY: {
233 std::string binaryBlock = ssBlock.str();
234 req->WriteHeader("Content-Type", "application/octet-stream");
235 req->WriteReply(HTTP_OK, binaryBlock);
236 return true;
239 case RF_HEX: {
240 std::string strHex = HexStr(ssBlock.begin(), ssBlock.end()) + "\n";
241 req->WriteHeader("Content-Type", "text/plain");
242 req->WriteReply(HTTP_OK, strHex);
243 return true;
246 case RF_JSON: {
247 UniValue objBlock = blockToJSON(block, pblockindex, showTxDetails);
248 std::string strJSON = objBlock.write() + "\n";
249 req->WriteHeader("Content-Type", "application/json");
250 req->WriteReply(HTTP_OK, strJSON);
251 return true;
254 default: {
255 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
259 // not reached
260 return true; // continue to process further HTTP reqs on this cxn
263 static bool rest_block_extended(HTTPRequest* req, const std::string& strURIPart)
265 return rest_block(req, strURIPart, true);
268 static bool rest_block_notxdetails(HTTPRequest* req, const std::string& strURIPart)
270 return rest_block(req, strURIPart, false);
273 // A bit of a hack - dependency on a function defined in rpc/blockchain.cpp
274 UniValue getblockchaininfo(const JSONRPCRequest& request);
276 static bool rest_chaininfo(HTTPRequest* req, const std::string& strURIPart)
278 if (!CheckWarmup(req))
279 return false;
280 std::string param;
281 const RetFormat rf = ParseDataFormat(param, strURIPart);
283 switch (rf) {
284 case RF_JSON: {
285 JSONRPCRequest jsonRequest;
286 jsonRequest.params = UniValue(UniValue::VARR);
287 UniValue chainInfoObject = getblockchaininfo(jsonRequest);
288 std::string strJSON = chainInfoObject.write() + "\n";
289 req->WriteHeader("Content-Type", "application/json");
290 req->WriteReply(HTTP_OK, strJSON);
291 return true;
293 default: {
294 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: json)");
298 // not reached
299 return true; // continue to process further HTTP reqs on this cxn
302 static bool rest_mempool_info(HTTPRequest* req, const std::string& strURIPart)
304 if (!CheckWarmup(req))
305 return false;
306 std::string param;
307 const RetFormat rf = ParseDataFormat(param, strURIPart);
309 switch (rf) {
310 case RF_JSON: {
311 UniValue mempoolInfoObject = mempoolInfoToJSON();
313 std::string strJSON = mempoolInfoObject.write() + "\n";
314 req->WriteHeader("Content-Type", "application/json");
315 req->WriteReply(HTTP_OK, strJSON);
316 return true;
318 default: {
319 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: json)");
323 // not reached
324 return true; // continue to process further HTTP reqs on this cxn
327 static bool rest_mempool_contents(HTTPRequest* req, const std::string& strURIPart)
329 if (!CheckWarmup(req))
330 return false;
331 std::string param;
332 const RetFormat rf = ParseDataFormat(param, strURIPart);
334 switch (rf) {
335 case RF_JSON: {
336 UniValue mempoolObject = mempoolToJSON(true);
338 std::string strJSON = mempoolObject.write() + "\n";
339 req->WriteHeader("Content-Type", "application/json");
340 req->WriteReply(HTTP_OK, strJSON);
341 return true;
343 default: {
344 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: json)");
348 // not reached
349 return true; // continue to process further HTTP reqs on this cxn
352 static bool rest_tx(HTTPRequest* req, const std::string& strURIPart)
354 if (!CheckWarmup(req))
355 return false;
356 std::string hashStr;
357 const RetFormat rf = ParseDataFormat(hashStr, strURIPart);
359 uint256 hash;
360 if (!ParseHashStr(hashStr, hash))
361 return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);
363 CTransactionRef tx;
364 uint256 hashBlock = uint256();
365 if (!GetTransaction(hash, tx, Params().GetConsensus(), hashBlock, true))
366 return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found");
368 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags());
369 ssTx << tx;
371 switch (rf) {
372 case RF_BINARY: {
373 std::string binaryTx = ssTx.str();
374 req->WriteHeader("Content-Type", "application/octet-stream");
375 req->WriteReply(HTTP_OK, binaryTx);
376 return true;
379 case RF_HEX: {
380 std::string strHex = HexStr(ssTx.begin(), ssTx.end()) + "\n";
381 req->WriteHeader("Content-Type", "text/plain");
382 req->WriteReply(HTTP_OK, strHex);
383 return true;
386 case RF_JSON: {
387 UniValue objTx(UniValue::VOBJ);
388 TxToJSON(*tx, hashBlock, objTx);
389 std::string strJSON = objTx.write() + "\n";
390 req->WriteHeader("Content-Type", "application/json");
391 req->WriteReply(HTTP_OK, strJSON);
392 return true;
395 default: {
396 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
400 // not reached
401 return true; // continue to process further HTTP reqs on this cxn
404 static bool rest_getutxos(HTTPRequest* req, const std::string& strURIPart)
406 if (!CheckWarmup(req))
407 return false;
408 std::string param;
409 const RetFormat rf = ParseDataFormat(param, strURIPart);
411 std::vector<std::string> uriParts;
412 if (param.length() > 1)
414 std::string strUriParams = param.substr(1);
415 boost::split(uriParts, strUriParams, boost::is_any_of("/"));
418 // throw exception in case of a empty request
419 std::string strRequestMutable = req->ReadBody();
420 if (strRequestMutable.length() == 0 && uriParts.size() == 0)
421 return RESTERR(req, HTTP_BAD_REQUEST, "Error: empty request");
423 bool fInputParsed = false;
424 bool fCheckMemPool = false;
425 std::vector<COutPoint> vOutPoints;
427 // parse/deserialize input
428 // input-format = output-format, rest/getutxos/bin requires binary input, gives binary output, ...
430 if (uriParts.size() > 0)
433 //inputs is sent over URI scheme (/rest/getutxos/checkmempool/txid1-n/txid2-n/...)
434 if (uriParts.size() > 0 && uriParts[0] == "checkmempool")
435 fCheckMemPool = true;
437 for (size_t i = (fCheckMemPool) ? 1 : 0; i < uriParts.size(); i++)
439 uint256 txid;
440 int32_t nOutput;
441 std::string strTxid = uriParts[i].substr(0, uriParts[i].find("-"));
442 std::string strOutput = uriParts[i].substr(uriParts[i].find("-")+1);
444 if (!ParseInt32(strOutput, &nOutput) || !IsHex(strTxid))
445 return RESTERR(req, HTTP_BAD_REQUEST, "Parse error");
447 txid.SetHex(strTxid);
448 vOutPoints.push_back(COutPoint(txid, (uint32_t)nOutput));
451 if (vOutPoints.size() > 0)
452 fInputParsed = true;
453 else
454 return RESTERR(req, HTTP_BAD_REQUEST, "Error: empty request");
457 switch (rf) {
458 case RF_HEX: {
459 // convert hex to bin, continue then with bin part
460 std::vector<unsigned char> strRequestV = ParseHex(strRequestMutable);
461 strRequestMutable.assign(strRequestV.begin(), strRequestV.end());
464 case RF_BINARY: {
465 try {
466 //deserialize only if user sent a request
467 if (strRequestMutable.size() > 0)
469 if (fInputParsed) //don't allow sending input over URI and HTTP RAW DATA
470 return RESTERR(req, HTTP_BAD_REQUEST, "Combination of URI scheme inputs and raw post data is not allowed");
472 CDataStream oss(SER_NETWORK, PROTOCOL_VERSION);
473 oss << strRequestMutable;
474 oss >> fCheckMemPool;
475 oss >> vOutPoints;
477 } catch (const std::ios_base::failure& e) {
478 // abort in case of unreadable binary data
479 return RESTERR(req, HTTP_BAD_REQUEST, "Parse error");
481 break;
484 case RF_JSON: {
485 if (!fInputParsed)
486 return RESTERR(req, HTTP_BAD_REQUEST, "Error: empty request");
487 break;
489 default: {
490 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
494 // limit max outpoints
495 if (vOutPoints.size() > MAX_GETUTXOS_OUTPOINTS)
496 return RESTERR(req, HTTP_BAD_REQUEST, strprintf("Error: max outpoints exceeded (max: %d, tried: %d)", MAX_GETUTXOS_OUTPOINTS, vOutPoints.size()));
498 // check spentness and form a bitmap (as well as a JSON capable human-readable string representation)
499 std::vector<unsigned char> bitmap;
500 std::vector<CCoin> outs;
501 std::string bitmapStringRepresentation;
502 std::vector<bool> hits;
503 bitmap.resize((vOutPoints.size() + 7) / 8);
505 LOCK2(cs_main, mempool.cs);
507 CCoinsView viewDummy;
508 CCoinsViewCache view(&viewDummy);
510 CCoinsViewCache& viewChain = *pcoinsTip;
511 CCoinsViewMemPool viewMempool(&viewChain, mempool);
513 if (fCheckMemPool)
514 view.SetBackend(viewMempool); // switch cache backend to db+mempool in case user likes to query mempool
516 for (size_t i = 0; i < vOutPoints.size(); i++) {
517 CCoins coins;
518 uint256 hash = vOutPoints[i].hash;
519 bool hit = false;
520 if (view.GetCoins(hash, coins)) {
521 mempool.pruneSpent(hash, coins);
522 if (coins.IsAvailable(vOutPoints[i].n)) {
523 hit = true;
524 // Safe to index into vout here because IsAvailable checked if it's off the end of the array, or if
525 // n is valid but points to an already spent output (IsNull).
526 CCoin coin;
527 coin.nTxVer = coins.nVersion;
528 coin.nHeight = coins.nHeight;
529 coin.out = coins.vout.at(vOutPoints[i].n);
530 assert(!coin.out.IsNull());
531 outs.push_back(coin);
535 hits.push_back(hit);
536 bitmapStringRepresentation.append(hit ? "1" : "0"); // form a binary string representation (human-readable for json output)
537 bitmap[i / 8] |= ((uint8_t)hit) << (i % 8);
541 switch (rf) {
542 case RF_BINARY: {
543 // serialize data
544 // use exact same output as mentioned in Bip64
545 CDataStream ssGetUTXOResponse(SER_NETWORK, PROTOCOL_VERSION);
546 ssGetUTXOResponse << chainActive.Height() << chainActive.Tip()->GetBlockHash() << bitmap << outs;
547 std::string ssGetUTXOResponseString = ssGetUTXOResponse.str();
549 req->WriteHeader("Content-Type", "application/octet-stream");
550 req->WriteReply(HTTP_OK, ssGetUTXOResponseString);
551 return true;
554 case RF_HEX: {
555 CDataStream ssGetUTXOResponse(SER_NETWORK, PROTOCOL_VERSION);
556 ssGetUTXOResponse << chainActive.Height() << chainActive.Tip()->GetBlockHash() << bitmap << outs;
557 std::string strHex = HexStr(ssGetUTXOResponse.begin(), ssGetUTXOResponse.end()) + "\n";
559 req->WriteHeader("Content-Type", "text/plain");
560 req->WriteReply(HTTP_OK, strHex);
561 return true;
564 case RF_JSON: {
565 UniValue objGetUTXOResponse(UniValue::VOBJ);
567 // pack in some essentials
568 // use more or less the same output as mentioned in Bip64
569 objGetUTXOResponse.push_back(Pair("chainHeight", chainActive.Height()));
570 objGetUTXOResponse.push_back(Pair("chaintipHash", chainActive.Tip()->GetBlockHash().GetHex()));
571 objGetUTXOResponse.push_back(Pair("bitmap", bitmapStringRepresentation));
573 UniValue utxos(UniValue::VARR);
574 BOOST_FOREACH (const CCoin& coin, outs) {
575 UniValue utxo(UniValue::VOBJ);
576 utxo.push_back(Pair("txvers", (int32_t)coin.nTxVer));
577 utxo.push_back(Pair("height", (int32_t)coin.nHeight));
578 utxo.push_back(Pair("value", ValueFromAmount(coin.out.nValue)));
580 // include the script in a json output
581 UniValue o(UniValue::VOBJ);
582 ScriptPubKeyToJSON(coin.out.scriptPubKey, o, true);
583 utxo.push_back(Pair("scriptPubKey", o));
584 utxos.push_back(utxo);
586 objGetUTXOResponse.push_back(Pair("utxos", utxos));
588 // return json string
589 std::string strJSON = objGetUTXOResponse.write() + "\n";
590 req->WriteHeader("Content-Type", "application/json");
591 req->WriteReply(HTTP_OK, strJSON);
592 return true;
594 default: {
595 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
599 // not reached
600 return true; // continue to process further HTTP reqs on this cxn
603 static const struct {
604 const char* prefix;
605 bool (*handler)(HTTPRequest* req, const std::string& strReq);
606 } uri_prefixes[] = {
607 {"/rest/tx/", rest_tx},
608 {"/rest/block/notxdetails/", rest_block_notxdetails},
609 {"/rest/block/", rest_block_extended},
610 {"/rest/chaininfo", rest_chaininfo},
611 {"/rest/mempool/info", rest_mempool_info},
612 {"/rest/mempool/contents", rest_mempool_contents},
613 {"/rest/headers/", rest_headers},
614 {"/rest/getutxos", rest_getutxos},
617 bool StartREST()
619 for (unsigned int i = 0; i < ARRAYLEN(uri_prefixes); i++)
620 RegisterHTTPHandler(uri_prefixes[i].prefix, false, uri_prefixes[i].handler);
621 return true;
624 void InterruptREST()
628 void StopREST()
630 for (unsigned int i = 0; i < ARRAYLEN(uri_prefixes); i++)
631 UnregisterHTTPHandler(uri_prefixes[i].prefix, false);