Merge #9206: Make test constant consistent with consensus.h
[bitcoinplatinum.git] / src / rest.cpp
blob90cca6f48055d7b633ea33f1503ef853d01f2a52
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2015 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 "main.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>
20 #include <boost/dynamic_bitset.hpp>
22 #include <univalue.h>
24 using namespace std;
26 static const size_t MAX_GETUTXOS_OUTPOINTS = 15; //allow a max of 15 outpoints to be queried at once
28 enum RetFormat {
29 RF_UNDEF,
30 RF_BINARY,
31 RF_HEX,
32 RF_JSON,
35 static const struct {
36 enum RetFormat rf;
37 const char* name;
38 } rf_names[] = {
39 {RF_UNDEF, ""},
40 {RF_BINARY, "bin"},
41 {RF_HEX, "hex"},
42 {RF_JSON, "json"},
45 struct CCoin {
46 uint32_t nTxVer; // Don't call this nVersion, that name has a special meaning inside IMPLEMENT_SERIALIZE
47 uint32_t nHeight;
48 CTxOut out;
50 ADD_SERIALIZE_METHODS;
52 template <typename Stream, typename Operation>
53 inline void SerializationOp(Stream& s, Operation ser_action)
55 READWRITE(nTxVer);
56 READWRITE(nHeight);
57 READWRITE(out);
61 extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry);
62 extern UniValue blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool txDetails = false);
63 extern UniValue mempoolInfoToJSON();
64 extern UniValue mempoolToJSON(bool fVerbose = false);
65 extern void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex);
66 extern UniValue blockheaderToJSON(const CBlockIndex* blockindex);
68 static bool RESTERR(HTTPRequest* req, enum HTTPStatusCode status, string message)
70 req->WriteHeader("Content-Type", "text/plain");
71 req->WriteReply(status, message + "\r\n");
72 return false;
75 static enum RetFormat ParseDataFormat(std::string& param, const std::string& strReq)
77 const std::string::size_type pos = strReq.rfind('.');
78 if (pos == std::string::npos)
80 param = strReq;
81 return rf_names[0].rf;
84 param = strReq.substr(0, pos);
85 const std::string suff(strReq, pos + 1);
87 for (unsigned int i = 0; i < ARRAYLEN(rf_names); i++)
88 if (suff == rf_names[i].name)
89 return rf_names[i].rf;
91 /* If no suffix is found, return original string. */
92 param = strReq;
93 return rf_names[0].rf;
96 static string AvailableDataFormatsString()
98 string formats = "";
99 for (unsigned int i = 0; i < ARRAYLEN(rf_names); i++)
100 if (strlen(rf_names[i].name) > 0) {
101 formats.append(".");
102 formats.append(rf_names[i].name);
103 formats.append(", ");
106 if (formats.length() > 0)
107 return formats.substr(0, formats.length() - 2);
109 return formats;
112 static bool ParseHashStr(const string& strReq, uint256& v)
114 if (!IsHex(strReq) || (strReq.size() != 64))
115 return false;
117 v.SetHex(strReq);
118 return true;
121 static bool CheckWarmup(HTTPRequest* req)
123 std::string statusmessage;
124 if (RPCIsInWarmup(&statusmessage))
125 return RESTERR(req, HTTP_SERVICE_UNAVAILABLE, "Service temporarily unavailable: " + statusmessage);
126 return true;
129 static bool rest_headers(HTTPRequest* req,
130 const std::string& strURIPart)
132 if (!CheckWarmup(req))
133 return false;
134 std::string param;
135 const RetFormat rf = ParseDataFormat(param, strURIPart);
136 vector<string> path;
137 boost::split(path, param, boost::is_any_of("/"));
139 if (path.size() != 2)
140 return RESTERR(req, HTTP_BAD_REQUEST, "No header count specified. Use /rest/headers/<count>/<hash>.<ext>.");
142 long count = strtol(path[0].c_str(), NULL, 10);
143 if (count < 1 || count > 2000)
144 return RESTERR(req, HTTP_BAD_REQUEST, "Header count out of range: " + path[0]);
146 string hashStr = path[1];
147 uint256 hash;
148 if (!ParseHashStr(hashStr, hash))
149 return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);
151 std::vector<const CBlockIndex *> headers;
152 headers.reserve(count);
154 LOCK(cs_main);
155 BlockMap::const_iterator it = mapBlockIndex.find(hash);
156 const CBlockIndex *pindex = (it != mapBlockIndex.end()) ? it->second : NULL;
157 while (pindex != NULL && chainActive.Contains(pindex)) {
158 headers.push_back(pindex);
159 if (headers.size() == (unsigned long)count)
160 break;
161 pindex = chainActive.Next(pindex);
165 CDataStream ssHeader(SER_NETWORK, PROTOCOL_VERSION);
166 BOOST_FOREACH(const CBlockIndex *pindex, headers) {
167 ssHeader << pindex->GetBlockHeader();
170 switch (rf) {
171 case RF_BINARY: {
172 string binaryHeader = ssHeader.str();
173 req->WriteHeader("Content-Type", "application/octet-stream");
174 req->WriteReply(HTTP_OK, binaryHeader);
175 return true;
178 case RF_HEX: {
179 string strHex = HexStr(ssHeader.begin(), ssHeader.end()) + "\n";
180 req->WriteHeader("Content-Type", "text/plain");
181 req->WriteReply(HTTP_OK, strHex);
182 return true;
184 case RF_JSON: {
185 UniValue jsonHeaders(UniValue::VARR);
186 BOOST_FOREACH(const CBlockIndex *pindex, headers) {
187 jsonHeaders.push_back(blockheaderToJSON(pindex));
189 string strJSON = jsonHeaders.write() + "\n";
190 req->WriteHeader("Content-Type", "application/json");
191 req->WriteReply(HTTP_OK, strJSON);
192 return true;
194 default: {
195 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: .bin, .hex)");
199 // not reached
200 return true; // continue to process further HTTP reqs on this cxn
203 static bool rest_block(HTTPRequest* req,
204 const std::string& strURIPart,
205 bool showTxDetails)
207 if (!CheckWarmup(req))
208 return false;
209 std::string hashStr;
210 const RetFormat rf = ParseDataFormat(hashStr, strURIPart);
212 uint256 hash;
213 if (!ParseHashStr(hashStr, hash))
214 return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);
216 CBlock block;
217 CBlockIndex* pblockindex = NULL;
219 LOCK(cs_main);
220 if (mapBlockIndex.count(hash) == 0)
221 return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found");
223 pblockindex = mapBlockIndex[hash];
224 if (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0)
225 return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not available (pruned data)");
227 if (!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus()))
228 return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found");
231 CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
232 ssBlock << block;
234 switch (rf) {
235 case RF_BINARY: {
236 string binaryBlock = ssBlock.str();
237 req->WriteHeader("Content-Type", "application/octet-stream");
238 req->WriteReply(HTTP_OK, binaryBlock);
239 return true;
242 case RF_HEX: {
243 string strHex = HexStr(ssBlock.begin(), ssBlock.end()) + "\n";
244 req->WriteHeader("Content-Type", "text/plain");
245 req->WriteReply(HTTP_OK, strHex);
246 return true;
249 case RF_JSON: {
250 UniValue objBlock = blockToJSON(block, pblockindex, showTxDetails);
251 string strJSON = objBlock.write() + "\n";
252 req->WriteHeader("Content-Type", "application/json");
253 req->WriteReply(HTTP_OK, strJSON);
254 return true;
257 default: {
258 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
262 // not reached
263 return true; // continue to process further HTTP reqs on this cxn
266 static bool rest_block_extended(HTTPRequest* req, const std::string& strURIPart)
268 return rest_block(req, strURIPart, true);
271 static bool rest_block_notxdetails(HTTPRequest* req, const std::string& strURIPart)
273 return rest_block(req, strURIPart, false);
276 // A bit of a hack - dependency on a function defined in rpc/blockchain.cpp
277 UniValue getblockchaininfo(const JSONRPCRequest& request);
279 static bool rest_chaininfo(HTTPRequest* req, const std::string& strURIPart)
281 if (!CheckWarmup(req))
282 return false;
283 std::string param;
284 const RetFormat rf = ParseDataFormat(param, strURIPart);
286 switch (rf) {
287 case RF_JSON: {
288 JSONRPCRequest jsonRequest;
289 jsonRequest.params = UniValue(UniValue::VARR);
290 UniValue chainInfoObject = getblockchaininfo(jsonRequest);
291 string strJSON = chainInfoObject.write() + "\n";
292 req->WriteHeader("Content-Type", "application/json");
293 req->WriteReply(HTTP_OK, strJSON);
294 return true;
296 default: {
297 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: json)");
301 // not reached
302 return true; // continue to process further HTTP reqs on this cxn
305 static bool rest_mempool_info(HTTPRequest* req, const std::string& strURIPart)
307 if (!CheckWarmup(req))
308 return false;
309 std::string param;
310 const RetFormat rf = ParseDataFormat(param, strURIPart);
312 switch (rf) {
313 case RF_JSON: {
314 UniValue mempoolInfoObject = mempoolInfoToJSON();
316 string strJSON = mempoolInfoObject.write() + "\n";
317 req->WriteHeader("Content-Type", "application/json");
318 req->WriteReply(HTTP_OK, strJSON);
319 return true;
321 default: {
322 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: json)");
326 // not reached
327 return true; // continue to process further HTTP reqs on this cxn
330 static bool rest_mempool_contents(HTTPRequest* req, const std::string& strURIPart)
332 if (!CheckWarmup(req))
333 return false;
334 std::string param;
335 const RetFormat rf = ParseDataFormat(param, strURIPart);
337 switch (rf) {
338 case RF_JSON: {
339 UniValue mempoolObject = mempoolToJSON(true);
341 string strJSON = mempoolObject.write() + "\n";
342 req->WriteHeader("Content-Type", "application/json");
343 req->WriteReply(HTTP_OK, strJSON);
344 return true;
346 default: {
347 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: json)");
351 // not reached
352 return true; // continue to process further HTTP reqs on this cxn
355 static bool rest_tx(HTTPRequest* req, const std::string& strURIPart)
357 if (!CheckWarmup(req))
358 return false;
359 std::string hashStr;
360 const RetFormat rf = ParseDataFormat(hashStr, strURIPart);
362 uint256 hash;
363 if (!ParseHashStr(hashStr, hash))
364 return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);
366 CTransaction tx;
367 uint256 hashBlock = uint256();
368 if (!GetTransaction(hash, tx, Params().GetConsensus(), hashBlock, true))
369 return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found");
371 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
372 ssTx << tx;
374 switch (rf) {
375 case RF_BINARY: {
376 string binaryTx = ssTx.str();
377 req->WriteHeader("Content-Type", "application/octet-stream");
378 req->WriteReply(HTTP_OK, binaryTx);
379 return true;
382 case RF_HEX: {
383 string strHex = HexStr(ssTx.begin(), ssTx.end()) + "\n";
384 req->WriteHeader("Content-Type", "text/plain");
385 req->WriteReply(HTTP_OK, strHex);
386 return true;
389 case RF_JSON: {
390 UniValue objTx(UniValue::VOBJ);
391 TxToJSON(tx, hashBlock, objTx);
392 string strJSON = objTx.write() + "\n";
393 req->WriteHeader("Content-Type", "application/json");
394 req->WriteReply(HTTP_OK, strJSON);
395 return true;
398 default: {
399 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
403 // not reached
404 return true; // continue to process further HTTP reqs on this cxn
407 static bool rest_getutxos(HTTPRequest* req, const std::string& strURIPart)
409 if (!CheckWarmup(req))
410 return false;
411 std::string param;
412 const RetFormat rf = ParseDataFormat(param, strURIPart);
414 vector<string> uriParts;
415 if (param.length() > 1)
417 std::string strUriParams = param.substr(1);
418 boost::split(uriParts, strUriParams, boost::is_any_of("/"));
421 // throw exception in case of a empty request
422 std::string strRequestMutable = req->ReadBody();
423 if (strRequestMutable.length() == 0 && uriParts.size() == 0)
424 return RESTERR(req, HTTP_BAD_REQUEST, "Error: empty request");
426 bool fInputParsed = false;
427 bool fCheckMemPool = false;
428 vector<COutPoint> vOutPoints;
430 // parse/deserialize input
431 // input-format = output-format, rest/getutxos/bin requires binary input, gives binary output, ...
433 if (uriParts.size() > 0)
436 //inputs is sent over URI scheme (/rest/getutxos/checkmempool/txid1-n/txid2-n/...)
437 if (uriParts.size() > 0 && uriParts[0] == "checkmempool")
438 fCheckMemPool = true;
440 for (size_t i = (fCheckMemPool) ? 1 : 0; i < uriParts.size(); i++)
442 uint256 txid;
443 int32_t nOutput;
444 std::string strTxid = uriParts[i].substr(0, uriParts[i].find("-"));
445 std::string strOutput = uriParts[i].substr(uriParts[i].find("-")+1);
447 if (!ParseInt32(strOutput, &nOutput) || !IsHex(strTxid))
448 return RESTERR(req, HTTP_BAD_REQUEST, "Parse error");
450 txid.SetHex(strTxid);
451 vOutPoints.push_back(COutPoint(txid, (uint32_t)nOutput));
454 if (vOutPoints.size() > 0)
455 fInputParsed = true;
456 else
457 return RESTERR(req, HTTP_BAD_REQUEST, "Error: empty request");
460 switch (rf) {
461 case RF_HEX: {
462 // convert hex to bin, continue then with bin part
463 std::vector<unsigned char> strRequestV = ParseHex(strRequestMutable);
464 strRequestMutable.assign(strRequestV.begin(), strRequestV.end());
467 case RF_BINARY: {
468 try {
469 //deserialize only if user sent a request
470 if (strRequestMutable.size() > 0)
472 if (fInputParsed) //don't allow sending input over URI and HTTP RAW DATA
473 return RESTERR(req, HTTP_BAD_REQUEST, "Combination of URI scheme inputs and raw post data is not allowed");
475 CDataStream oss(SER_NETWORK, PROTOCOL_VERSION);
476 oss << strRequestMutable;
477 oss >> fCheckMemPool;
478 oss >> vOutPoints;
480 } catch (const std::ios_base::failure& e) {
481 // abort in case of unreadable binary data
482 return RESTERR(req, HTTP_BAD_REQUEST, "Parse error");
484 break;
487 case RF_JSON: {
488 if (!fInputParsed)
489 return RESTERR(req, HTTP_BAD_REQUEST, "Error: empty request");
490 break;
492 default: {
493 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
497 // limit max outpoints
498 if (vOutPoints.size() > MAX_GETUTXOS_OUTPOINTS)
499 return RESTERR(req, HTTP_BAD_REQUEST, strprintf("Error: max outpoints exceeded (max: %d, tried: %d)", MAX_GETUTXOS_OUTPOINTS, vOutPoints.size()));
501 // check spentness and form a bitmap (as well as a JSON capable human-readable string representation)
502 vector<unsigned char> bitmap;
503 vector<CCoin> outs;
504 std::string bitmapStringRepresentation;
505 boost::dynamic_bitset<unsigned char> hits(vOutPoints.size());
507 LOCK2(cs_main, mempool.cs);
509 CCoinsView viewDummy;
510 CCoinsViewCache view(&viewDummy);
512 CCoinsViewCache& viewChain = *pcoinsTip;
513 CCoinsViewMemPool viewMempool(&viewChain, mempool);
515 if (fCheckMemPool)
516 view.SetBackend(viewMempool); // switch cache backend to db+mempool in case user likes to query mempool
518 for (size_t i = 0; i < vOutPoints.size(); i++) {
519 CCoins coins;
520 uint256 hash = vOutPoints[i].hash;
521 if (view.GetCoins(hash, coins)) {
522 mempool.pruneSpent(hash, coins);
523 if (coins.IsAvailable(vOutPoints[i].n)) {
524 hits[i] = true;
525 // Safe to index into vout here because IsAvailable checked if it's off the end of the array, or if
526 // n is valid but points to an already spent output (IsNull).
527 CCoin coin;
528 coin.nTxVer = coins.nVersion;
529 coin.nHeight = coins.nHeight;
530 coin.out = coins.vout.at(vOutPoints[i].n);
531 assert(!coin.out.IsNull());
532 outs.push_back(coin);
536 bitmapStringRepresentation.append(hits[i] ? "1" : "0"); // form a binary string representation (human-readable for json output)
539 boost::to_block_range(hits, std::back_inserter(bitmap));
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 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 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 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);