Introduce enum ServiceFlags for service flags
[bitcoinplatinum.git] / src / rest.cpp
blob2dff8d7daddfcf2f2481b86ea11454ad8e88c687
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, int nType, int nVersion)
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 UniValue& params, bool fHelp);
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 UniValue rpcParams(UniValue::VARR);
289 UniValue chainInfoObject = getblockchaininfo(rpcParams, false);
290 string strJSON = chainInfoObject.write() + "\n";
291 req->WriteHeader("Content-Type", "application/json");
292 req->WriteReply(HTTP_OK, strJSON);
293 return true;
295 default: {
296 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: json)");
300 // not reached
301 return true; // continue to process further HTTP reqs on this cxn
304 static bool rest_mempool_info(HTTPRequest* req, const std::string& strURIPart)
306 if (!CheckWarmup(req))
307 return false;
308 std::string param;
309 const RetFormat rf = ParseDataFormat(param, strURIPart);
311 switch (rf) {
312 case RF_JSON: {
313 UniValue mempoolInfoObject = mempoolInfoToJSON();
315 string strJSON = mempoolInfoObject.write() + "\n";
316 req->WriteHeader("Content-Type", "application/json");
317 req->WriteReply(HTTP_OK, strJSON);
318 return true;
320 default: {
321 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: json)");
325 // not reached
326 return true; // continue to process further HTTP reqs on this cxn
329 static bool rest_mempool_contents(HTTPRequest* req, const std::string& strURIPart)
331 if (!CheckWarmup(req))
332 return false;
333 std::string param;
334 const RetFormat rf = ParseDataFormat(param, strURIPart);
336 switch (rf) {
337 case RF_JSON: {
338 UniValue mempoolObject = mempoolToJSON(true);
340 string strJSON = mempoolObject.write() + "\n";
341 req->WriteHeader("Content-Type", "application/json");
342 req->WriteReply(HTTP_OK, strJSON);
343 return true;
345 default: {
346 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: json)");
350 // not reached
351 return true; // continue to process further HTTP reqs on this cxn
354 static bool rest_tx(HTTPRequest* req, const std::string& strURIPart)
356 if (!CheckWarmup(req))
357 return false;
358 std::string hashStr;
359 const RetFormat rf = ParseDataFormat(hashStr, strURIPart);
361 uint256 hash;
362 if (!ParseHashStr(hashStr, hash))
363 return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);
365 CTransaction tx;
366 uint256 hashBlock = uint256();
367 if (!GetTransaction(hash, tx, Params().GetConsensus(), hashBlock, true))
368 return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found");
370 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
371 ssTx << tx;
373 switch (rf) {
374 case RF_BINARY: {
375 string binaryTx = ssTx.str();
376 req->WriteHeader("Content-Type", "application/octet-stream");
377 req->WriteReply(HTTP_OK, binaryTx);
378 return true;
381 case RF_HEX: {
382 string strHex = HexStr(ssTx.begin(), ssTx.end()) + "\n";
383 req->WriteHeader("Content-Type", "text/plain");
384 req->WriteReply(HTTP_OK, strHex);
385 return true;
388 case RF_JSON: {
389 UniValue objTx(UniValue::VOBJ);
390 TxToJSON(tx, hashBlock, objTx);
391 string strJSON = objTx.write() + "\n";
392 req->WriteHeader("Content-Type", "application/json");
393 req->WriteReply(HTTP_OK, strJSON);
394 return true;
397 default: {
398 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
402 // not reached
403 return true; // continue to process further HTTP reqs on this cxn
406 static bool rest_getutxos(HTTPRequest* req, const std::string& strURIPart)
408 if (!CheckWarmup(req))
409 return false;
410 std::string param;
411 const RetFormat rf = ParseDataFormat(param, strURIPart);
413 vector<string> uriParts;
414 if (param.length() > 1)
416 std::string strUriParams = param.substr(1);
417 boost::split(uriParts, strUriParams, boost::is_any_of("/"));
420 // throw exception in case of a empty request
421 std::string strRequestMutable = req->ReadBody();
422 if (strRequestMutable.length() == 0 && uriParts.size() == 0)
423 return RESTERR(req, HTTP_INTERNAL_SERVER_ERROR, "Error: empty request");
425 bool fInputParsed = false;
426 bool fCheckMemPool = false;
427 vector<COutPoint> vOutPoints;
429 // parse/deserialize input
430 // input-format = output-format, rest/getutxos/bin requires binary input, gives binary output, ...
432 if (uriParts.size() > 0)
435 //inputs is sent over URI scheme (/rest/getutxos/checkmempool/txid1-n/txid2-n/...)
436 if (uriParts.size() > 0 && uriParts[0] == "checkmempool")
437 fCheckMemPool = true;
439 for (size_t i = (fCheckMemPool) ? 1 : 0; i < uriParts.size(); i++)
441 uint256 txid;
442 int32_t nOutput;
443 std::string strTxid = uriParts[i].substr(0, uriParts[i].find("-"));
444 std::string strOutput = uriParts[i].substr(uriParts[i].find("-")+1);
446 if (!ParseInt32(strOutput, &nOutput) || !IsHex(strTxid))
447 return RESTERR(req, HTTP_INTERNAL_SERVER_ERROR, "Parse error");
449 txid.SetHex(strTxid);
450 vOutPoints.push_back(COutPoint(txid, (uint32_t)nOutput));
453 if (vOutPoints.size() > 0)
454 fInputParsed = true;
455 else
456 return RESTERR(req, HTTP_INTERNAL_SERVER_ERROR, "Error: empty request");
459 switch (rf) {
460 case RF_HEX: {
461 // convert hex to bin, continue then with bin part
462 std::vector<unsigned char> strRequestV = ParseHex(strRequestMutable);
463 strRequestMutable.assign(strRequestV.begin(), strRequestV.end());
466 case RF_BINARY: {
467 try {
468 //deserialize only if user sent a request
469 if (strRequestMutable.size() > 0)
471 if (fInputParsed) //don't allow sending input over URI and HTTP RAW DATA
472 return RESTERR(req, HTTP_INTERNAL_SERVER_ERROR, "Combination of URI scheme inputs and raw post data is not allowed");
474 CDataStream oss(SER_NETWORK, PROTOCOL_VERSION);
475 oss << strRequestMutable;
476 oss >> fCheckMemPool;
477 oss >> vOutPoints;
479 } catch (const std::ios_base::failure& e) {
480 // abort in case of unreadable binary data
481 return RESTERR(req, HTTP_INTERNAL_SERVER_ERROR, "Parse error");
483 break;
486 case RF_JSON: {
487 if (!fInputParsed)
488 return RESTERR(req, HTTP_INTERNAL_SERVER_ERROR, "Error: empty request");
489 break;
491 default: {
492 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
496 // limit max outpoints
497 if (vOutPoints.size() > MAX_GETUTXOS_OUTPOINTS)
498 return RESTERR(req, HTTP_INTERNAL_SERVER_ERROR, strprintf("Error: max outpoints exceeded (max: %d, tried: %d)", MAX_GETUTXOS_OUTPOINTS, vOutPoints.size()));
500 // check spentness and form a bitmap (as well as a JSON capable human-readable string representation)
501 vector<unsigned char> bitmap;
502 vector<CCoin> outs;
503 std::string bitmapStringRepresentation;
504 boost::dynamic_bitset<unsigned char> hits(vOutPoints.size());
506 LOCK2(cs_main, mempool.cs);
508 CCoinsView viewDummy;
509 CCoinsViewCache view(&viewDummy);
511 CCoinsViewCache& viewChain = *pcoinsTip;
512 CCoinsViewMemPool viewMempool(&viewChain, mempool);
514 if (fCheckMemPool)
515 view.SetBackend(viewMempool); // switch cache backend to db+mempool in case user likes to query mempool
517 for (size_t i = 0; i < vOutPoints.size(); i++) {
518 CCoins coins;
519 uint256 hash = vOutPoints[i].hash;
520 if (view.GetCoins(hash, coins)) {
521 mempool.pruneSpent(hash, coins);
522 if (coins.IsAvailable(vOutPoints[i].n)) {
523 hits[i] = 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 bitmapStringRepresentation.append(hits[i] ? "1" : "0"); // form a binary string representation (human-readable for json output)
538 boost::to_block_range(hits, std::back_inserter(bitmap));
540 switch (rf) {
541 case RF_BINARY: {
542 // serialize data
543 // use exact same output as mentioned in Bip64
544 CDataStream ssGetUTXOResponse(SER_NETWORK, PROTOCOL_VERSION);
545 ssGetUTXOResponse << chainActive.Height() << chainActive.Tip()->GetBlockHash() << bitmap << outs;
546 string ssGetUTXOResponseString = ssGetUTXOResponse.str();
548 req->WriteHeader("Content-Type", "application/octet-stream");
549 req->WriteReply(HTTP_OK, ssGetUTXOResponseString);
550 return true;
553 case RF_HEX: {
554 CDataStream ssGetUTXOResponse(SER_NETWORK, PROTOCOL_VERSION);
555 ssGetUTXOResponse << chainActive.Height() << chainActive.Tip()->GetBlockHash() << bitmap << outs;
556 string strHex = HexStr(ssGetUTXOResponse.begin(), ssGetUTXOResponse.end()) + "\n";
558 req->WriteHeader("Content-Type", "text/plain");
559 req->WriteReply(HTTP_OK, strHex);
560 return true;
563 case RF_JSON: {
564 UniValue objGetUTXOResponse(UniValue::VOBJ);
566 // pack in some essentials
567 // use more or less the same output as mentioned in Bip64
568 objGetUTXOResponse.push_back(Pair("chainHeight", chainActive.Height()));
569 objGetUTXOResponse.push_back(Pair("chaintipHash", chainActive.Tip()->GetBlockHash().GetHex()));
570 objGetUTXOResponse.push_back(Pair("bitmap", bitmapStringRepresentation));
572 UniValue utxos(UniValue::VARR);
573 BOOST_FOREACH (const CCoin& coin, outs) {
574 UniValue utxo(UniValue::VOBJ);
575 utxo.push_back(Pair("txvers", (int32_t)coin.nTxVer));
576 utxo.push_back(Pair("height", (int32_t)coin.nHeight));
577 utxo.push_back(Pair("value", ValueFromAmount(coin.out.nValue)));
579 // include the script in a json output
580 UniValue o(UniValue::VOBJ);
581 ScriptPubKeyToJSON(coin.out.scriptPubKey, o, true);
582 utxo.push_back(Pair("scriptPubKey", o));
583 utxos.push_back(utxo);
585 objGetUTXOResponse.push_back(Pair("utxos", utxos));
587 // return json string
588 string strJSON = objGetUTXOResponse.write() + "\n";
589 req->WriteHeader("Content-Type", "application/json");
590 req->WriteReply(HTTP_OK, strJSON);
591 return true;
593 default: {
594 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
598 // not reached
599 return true; // continue to process further HTTP reqs on this cxn
602 static const struct {
603 const char* prefix;
604 bool (*handler)(HTTPRequest* req, const std::string& strReq);
605 } uri_prefixes[] = {
606 {"/rest/tx/", rest_tx},
607 {"/rest/block/notxdetails/", rest_block_notxdetails},
608 {"/rest/block/", rest_block_extended},
609 {"/rest/chaininfo", rest_chaininfo},
610 {"/rest/mempool/info", rest_mempool_info},
611 {"/rest/mempool/contents", rest_mempool_contents},
612 {"/rest/headers/", rest_headers},
613 {"/rest/getutxos", rest_getutxos},
616 bool StartREST()
618 for (unsigned int i = 0; i < ARRAYLEN(uri_prefixes); i++)
619 RegisterHTTPHandler(uri_prefixes[i].prefix, false, uri_prefixes[i].handler);
620 return true;
623 void InterruptREST()
627 void StopREST()
629 for (unsigned int i = 0; i < ARRAYLEN(uri_prefixes); i++)
630 UnregisterHTTPHandler(uri_prefixes[i].prefix, false);