minor cleanup: remove unnecessary variable
[bitcoinplatinum.git] / src / rest.cpp
blob9dcaf269d645f9c08c9aabefec80a54d43a4e4e8
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/blockchain.h"
13 #include "rpc/server.h"
14 #include "streams.h"
15 #include "sync.h"
16 #include "txmempool.h"
17 #include "utilstrencodings.h"
18 #include "version.h"
20 #include <boost/algorithm/string.hpp>
22 #include <univalue.h>
24 static const size_t MAX_GETUTXOS_OUTPOINTS = 15; //allow a max of 15 outpoints to be queried at once
26 enum RetFormat {
27 RF_UNDEF,
28 RF_BINARY,
29 RF_HEX,
30 RF_JSON,
33 static const struct {
34 enum RetFormat rf;
35 const char* name;
36 } rf_names[] = {
37 {RF_UNDEF, ""},
38 {RF_BINARY, "bin"},
39 {RF_HEX, "hex"},
40 {RF_JSON, "json"},
43 struct CCoin {
44 uint32_t nTxVer; // Don't call this nVersion, that name has a special meaning inside IMPLEMENT_SERIALIZE
45 uint32_t nHeight;
46 CTxOut out;
48 ADD_SERIALIZE_METHODS;
50 template <typename Stream, typename Operation>
51 inline void SerializationOp(Stream& s, Operation ser_action)
53 READWRITE(nTxVer);
54 READWRITE(nHeight);
55 READWRITE(out);
59 /* Defined in rawtransaction.cpp */
60 void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry);
61 void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex);
63 static bool RESTERR(HTTPRequest* req, enum HTTPStatusCode status, std::string message)
65 req->WriteHeader("Content-Type", "text/plain");
66 req->WriteReply(status, message + "\r\n");
67 return false;
70 static enum RetFormat ParseDataFormat(std::string& param, const std::string& strReq)
72 const std::string::size_type pos = strReq.rfind('.');
73 if (pos == std::string::npos)
75 param = strReq;
76 return rf_names[0].rf;
79 param = strReq.substr(0, pos);
80 const std::string suff(strReq, pos + 1);
82 for (unsigned int i = 0; i < ARRAYLEN(rf_names); i++)
83 if (suff == rf_names[i].name)
84 return rf_names[i].rf;
86 /* If no suffix is found, return original string. */
87 param = strReq;
88 return rf_names[0].rf;
91 static std::string AvailableDataFormatsString()
93 std::string formats = "";
94 for (unsigned int i = 0; i < ARRAYLEN(rf_names); i++)
95 if (strlen(rf_names[i].name) > 0) {
96 formats.append(".");
97 formats.append(rf_names[i].name);
98 formats.append(", ");
101 if (formats.length() > 0)
102 return formats.substr(0, formats.length() - 2);
104 return formats;
107 static bool ParseHashStr(const std::string& strReq, uint256& v)
109 if (!IsHex(strReq) || (strReq.size() != 64))
110 return false;
112 v.SetHex(strReq);
113 return true;
116 static bool CheckWarmup(HTTPRequest* req)
118 std::string statusmessage;
119 if (RPCIsInWarmup(&statusmessage))
120 return RESTERR(req, HTTP_SERVICE_UNAVAILABLE, "Service temporarily unavailable: " + statusmessage);
121 return true;
124 static bool rest_headers(HTTPRequest* req,
125 const std::string& strURIPart)
127 if (!CheckWarmup(req))
128 return false;
129 std::string param;
130 const RetFormat rf = ParseDataFormat(param, strURIPart);
131 std::vector<std::string> path;
132 boost::split(path, param, boost::is_any_of("/"));
134 if (path.size() != 2)
135 return RESTERR(req, HTTP_BAD_REQUEST, "No header count specified. Use /rest/headers/<count>/<hash>.<ext>.");
137 long count = strtol(path[0].c_str(), NULL, 10);
138 if (count < 1 || count > 2000)
139 return RESTERR(req, HTTP_BAD_REQUEST, "Header count out of range: " + path[0]);
141 std::string hashStr = path[1];
142 uint256 hash;
143 if (!ParseHashStr(hashStr, hash))
144 return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);
146 std::vector<const CBlockIndex *> headers;
147 headers.reserve(count);
149 LOCK(cs_main);
150 BlockMap::const_iterator it = mapBlockIndex.find(hash);
151 const CBlockIndex *pindex = (it != mapBlockIndex.end()) ? it->second : NULL;
152 while (pindex != NULL && chainActive.Contains(pindex)) {
153 headers.push_back(pindex);
154 if (headers.size() == (unsigned long)count)
155 break;
156 pindex = chainActive.Next(pindex);
160 CDataStream ssHeader(SER_NETWORK, PROTOCOL_VERSION);
161 BOOST_FOREACH(const CBlockIndex *pindex, headers) {
162 ssHeader << pindex->GetBlockHeader();
165 switch (rf) {
166 case RF_BINARY: {
167 std::string binaryHeader = ssHeader.str();
168 req->WriteHeader("Content-Type", "application/octet-stream");
169 req->WriteReply(HTTP_OK, binaryHeader);
170 return true;
173 case RF_HEX: {
174 std::string strHex = HexStr(ssHeader.begin(), ssHeader.end()) + "\n";
175 req->WriteHeader("Content-Type", "text/plain");
176 req->WriteReply(HTTP_OK, strHex);
177 return true;
179 case RF_JSON: {
180 UniValue jsonHeaders(UniValue::VARR);
181 BOOST_FOREACH(const CBlockIndex *pindex, headers) {
182 jsonHeaders.push_back(blockheaderToJSON(pindex));
184 std::string strJSON = jsonHeaders.write() + "\n";
185 req->WriteHeader("Content-Type", "application/json");
186 req->WriteReply(HTTP_OK, strJSON);
187 return true;
189 default: {
190 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: .bin, .hex)");
194 // not reached
195 return true; // continue to process further HTTP reqs on this cxn
198 static bool rest_block(HTTPRequest* req,
199 const std::string& strURIPart,
200 bool showTxDetails)
202 if (!CheckWarmup(req))
203 return false;
204 std::string hashStr;
205 const RetFormat rf = ParseDataFormat(hashStr, strURIPart);
207 uint256 hash;
208 if (!ParseHashStr(hashStr, hash))
209 return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);
211 CBlock block;
212 CBlockIndex* pblockindex = NULL;
214 LOCK(cs_main);
215 if (mapBlockIndex.count(hash) == 0)
216 return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found");
218 pblockindex = mapBlockIndex[hash];
219 if (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0)
220 return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not available (pruned data)");
222 if (!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus()))
223 return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found");
226 CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags());
227 ssBlock << block;
229 switch (rf) {
230 case RF_BINARY: {
231 std::string binaryBlock = ssBlock.str();
232 req->WriteHeader("Content-Type", "application/octet-stream");
233 req->WriteReply(HTTP_OK, binaryBlock);
234 return true;
237 case RF_HEX: {
238 std::string strHex = HexStr(ssBlock.begin(), ssBlock.end()) + "\n";
239 req->WriteHeader("Content-Type", "text/plain");
240 req->WriteReply(HTTP_OK, strHex);
241 return true;
244 case RF_JSON: {
245 UniValue objBlock = blockToJSON(block, pblockindex, showTxDetails);
246 std::string strJSON = objBlock.write() + "\n";
247 req->WriteHeader("Content-Type", "application/json");
248 req->WriteReply(HTTP_OK, strJSON);
249 return true;
252 default: {
253 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
257 // not reached
258 return true; // continue to process further HTTP reqs on this cxn
261 static bool rest_block_extended(HTTPRequest* req, const std::string& strURIPart)
263 return rest_block(req, strURIPart, true);
266 static bool rest_block_notxdetails(HTTPRequest* req, const std::string& strURIPart)
268 return rest_block(req, strURIPart, false);
271 // A bit of a hack - dependency on a function defined in rpc/blockchain.cpp
272 UniValue getblockchaininfo(const JSONRPCRequest& request);
274 static bool rest_chaininfo(HTTPRequest* req, const std::string& strURIPart)
276 if (!CheckWarmup(req))
277 return false;
278 std::string param;
279 const RetFormat rf = ParseDataFormat(param, strURIPart);
281 switch (rf) {
282 case RF_JSON: {
283 JSONRPCRequest jsonRequest;
284 jsonRequest.params = UniValue(UniValue::VARR);
285 UniValue chainInfoObject = getblockchaininfo(jsonRequest);
286 std::string strJSON = chainInfoObject.write() + "\n";
287 req->WriteHeader("Content-Type", "application/json");
288 req->WriteReply(HTTP_OK, strJSON);
289 return true;
291 default: {
292 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: json)");
296 // not reached
297 return true; // continue to process further HTTP reqs on this cxn
300 static bool rest_mempool_info(HTTPRequest* req, const std::string& strURIPart)
302 if (!CheckWarmup(req))
303 return false;
304 std::string param;
305 const RetFormat rf = ParseDataFormat(param, strURIPart);
307 switch (rf) {
308 case RF_JSON: {
309 UniValue mempoolInfoObject = mempoolInfoToJSON();
311 std::string strJSON = mempoolInfoObject.write() + "\n";
312 req->WriteHeader("Content-Type", "application/json");
313 req->WriteReply(HTTP_OK, strJSON);
314 return true;
316 default: {
317 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: json)");
321 // not reached
322 return true; // continue to process further HTTP reqs on this cxn
325 static bool rest_mempool_contents(HTTPRequest* req, const std::string& strURIPart)
327 if (!CheckWarmup(req))
328 return false;
329 std::string param;
330 const RetFormat rf = ParseDataFormat(param, strURIPart);
332 switch (rf) {
333 case RF_JSON: {
334 UniValue mempoolObject = mempoolToJSON(true);
336 std::string strJSON = mempoolObject.write() + "\n";
337 req->WriteHeader("Content-Type", "application/json");
338 req->WriteReply(HTTP_OK, strJSON);
339 return true;
341 default: {
342 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: json)");
346 // not reached
347 return true; // continue to process further HTTP reqs on this cxn
350 static bool rest_tx(HTTPRequest* req, const std::string& strURIPart)
352 if (!CheckWarmup(req))
353 return false;
354 std::string hashStr;
355 const RetFormat rf = ParseDataFormat(hashStr, strURIPart);
357 uint256 hash;
358 if (!ParseHashStr(hashStr, hash))
359 return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);
361 CTransactionRef tx;
362 uint256 hashBlock = uint256();
363 if (!GetTransaction(hash, tx, Params().GetConsensus(), hashBlock, true))
364 return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found");
366 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags());
367 ssTx << tx;
369 switch (rf) {
370 case RF_BINARY: {
371 std::string binaryTx = ssTx.str();
372 req->WriteHeader("Content-Type", "application/octet-stream");
373 req->WriteReply(HTTP_OK, binaryTx);
374 return true;
377 case RF_HEX: {
378 std::string strHex = HexStr(ssTx.begin(), ssTx.end()) + "\n";
379 req->WriteHeader("Content-Type", "text/plain");
380 req->WriteReply(HTTP_OK, strHex);
381 return true;
384 case RF_JSON: {
385 UniValue objTx(UniValue::VOBJ);
386 TxToJSON(*tx, hashBlock, objTx);
387 std::string strJSON = objTx.write() + "\n";
388 req->WriteHeader("Content-Type", "application/json");
389 req->WriteReply(HTTP_OK, strJSON);
390 return true;
393 default: {
394 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
398 // not reached
399 return true; // continue to process further HTTP reqs on this cxn
402 static bool rest_getutxos(HTTPRequest* req, const std::string& strURIPart)
404 if (!CheckWarmup(req))
405 return false;
406 std::string param;
407 const RetFormat rf = ParseDataFormat(param, strURIPart);
409 std::vector<std::string> uriParts;
410 if (param.length() > 1)
412 std::string strUriParams = param.substr(1);
413 boost::split(uriParts, strUriParams, boost::is_any_of("/"));
416 // throw exception in case of a empty request
417 std::string strRequestMutable = req->ReadBody();
418 if (strRequestMutable.length() == 0 && uriParts.size() == 0)
419 return RESTERR(req, HTTP_BAD_REQUEST, "Error: empty request");
421 bool fInputParsed = false;
422 bool fCheckMemPool = false;
423 std::vector<COutPoint> vOutPoints;
425 // parse/deserialize input
426 // input-format = output-format, rest/getutxos/bin requires binary input, gives binary output, ...
428 if (uriParts.size() > 0)
431 //inputs is sent over URI scheme (/rest/getutxos/checkmempool/txid1-n/txid2-n/...)
432 if (uriParts.size() > 0 && uriParts[0] == "checkmempool")
433 fCheckMemPool = true;
435 for (size_t i = (fCheckMemPool) ? 1 : 0; i < uriParts.size(); i++)
437 uint256 txid;
438 int32_t nOutput;
439 std::string strTxid = uriParts[i].substr(0, uriParts[i].find("-"));
440 std::string strOutput = uriParts[i].substr(uriParts[i].find("-")+1);
442 if (!ParseInt32(strOutput, &nOutput) || !IsHex(strTxid))
443 return RESTERR(req, HTTP_BAD_REQUEST, "Parse error");
445 txid.SetHex(strTxid);
446 vOutPoints.push_back(COutPoint(txid, (uint32_t)nOutput));
449 if (vOutPoints.size() > 0)
450 fInputParsed = true;
451 else
452 return RESTERR(req, HTTP_BAD_REQUEST, "Error: empty request");
455 switch (rf) {
456 case RF_HEX: {
457 // convert hex to bin, continue then with bin part
458 std::vector<unsigned char> strRequestV = ParseHex(strRequestMutable);
459 strRequestMutable.assign(strRequestV.begin(), strRequestV.end());
462 case RF_BINARY: {
463 try {
464 //deserialize only if user sent a request
465 if (strRequestMutable.size() > 0)
467 if (fInputParsed) //don't allow sending input over URI and HTTP RAW DATA
468 return RESTERR(req, HTTP_BAD_REQUEST, "Combination of URI scheme inputs and raw post data is not allowed");
470 CDataStream oss(SER_NETWORK, PROTOCOL_VERSION);
471 oss << strRequestMutable;
472 oss >> fCheckMemPool;
473 oss >> vOutPoints;
475 } catch (const std::ios_base::failure& e) {
476 // abort in case of unreadable binary data
477 return RESTERR(req, HTTP_BAD_REQUEST, "Parse error");
479 break;
482 case RF_JSON: {
483 if (!fInputParsed)
484 return RESTERR(req, HTTP_BAD_REQUEST, "Error: empty request");
485 break;
487 default: {
488 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
492 // limit max outpoints
493 if (vOutPoints.size() > MAX_GETUTXOS_OUTPOINTS)
494 return RESTERR(req, HTTP_BAD_REQUEST, strprintf("Error: max outpoints exceeded (max: %d, tried: %d)", MAX_GETUTXOS_OUTPOINTS, vOutPoints.size()));
496 // check spentness and form a bitmap (as well as a JSON capable human-readable string representation)
497 std::vector<unsigned char> bitmap;
498 std::vector<CCoin> outs;
499 std::string bitmapStringRepresentation;
500 std::vector<bool> hits;
501 bitmap.resize((vOutPoints.size() + 7) / 8);
503 LOCK2(cs_main, mempool.cs);
505 CCoinsView viewDummy;
506 CCoinsViewCache view(&viewDummy);
508 CCoinsViewCache& viewChain = *pcoinsTip;
509 CCoinsViewMemPool viewMempool(&viewChain, mempool);
511 if (fCheckMemPool)
512 view.SetBackend(viewMempool); // switch cache backend to db+mempool in case user likes to query mempool
514 for (size_t i = 0; i < vOutPoints.size(); i++) {
515 CCoins coins;
516 uint256 hash = vOutPoints[i].hash;
517 bool hit = false;
518 if (view.GetCoins(hash, coins)) {
519 mempool.pruneSpent(hash, coins);
520 if (coins.IsAvailable(vOutPoints[i].n)) {
521 hit = true;
522 // Safe to index into vout here because IsAvailable checked if it's off the end of the array, or if
523 // n is valid but points to an already spent output (IsNull).
524 CCoin coin;
525 coin.nTxVer = coins.nVersion;
526 coin.nHeight = coins.nHeight;
527 coin.out = coins.vout.at(vOutPoints[i].n);
528 assert(!coin.out.IsNull());
529 outs.push_back(coin);
533 hits.push_back(hit);
534 bitmapStringRepresentation.append(hit ? "1" : "0"); // form a binary string representation (human-readable for json output)
535 bitmap[i / 8] |= ((uint8_t)hit) << (i % 8);
539 switch (rf) {
540 case RF_BINARY: {
541 // serialize data
542 // use exact same output as mentioned in Bip64
543 CDataStream ssGetUTXOResponse(SER_NETWORK, PROTOCOL_VERSION);
544 ssGetUTXOResponse << chainActive.Height() << chainActive.Tip()->GetBlockHash() << bitmap << outs;
545 std::string ssGetUTXOResponseString = ssGetUTXOResponse.str();
547 req->WriteHeader("Content-Type", "application/octet-stream");
548 req->WriteReply(HTTP_OK, ssGetUTXOResponseString);
549 return true;
552 case RF_HEX: {
553 CDataStream ssGetUTXOResponse(SER_NETWORK, PROTOCOL_VERSION);
554 ssGetUTXOResponse << chainActive.Height() << chainActive.Tip()->GetBlockHash() << bitmap << outs;
555 std::string strHex = HexStr(ssGetUTXOResponse.begin(), ssGetUTXOResponse.end()) + "\n";
557 req->WriteHeader("Content-Type", "text/plain");
558 req->WriteReply(HTTP_OK, strHex);
559 return true;
562 case RF_JSON: {
563 UniValue objGetUTXOResponse(UniValue::VOBJ);
565 // pack in some essentials
566 // use more or less the same output as mentioned in Bip64
567 objGetUTXOResponse.push_back(Pair("chainHeight", chainActive.Height()));
568 objGetUTXOResponse.push_back(Pair("chaintipHash", chainActive.Tip()->GetBlockHash().GetHex()));
569 objGetUTXOResponse.push_back(Pair("bitmap", bitmapStringRepresentation));
571 UniValue utxos(UniValue::VARR);
572 BOOST_FOREACH (const CCoin& coin, outs) {
573 UniValue utxo(UniValue::VOBJ);
574 utxo.push_back(Pair("txvers", (int32_t)coin.nTxVer));
575 utxo.push_back(Pair("height", (int32_t)coin.nHeight));
576 utxo.push_back(Pair("value", ValueFromAmount(coin.out.nValue)));
578 // include the script in a json output
579 UniValue o(UniValue::VOBJ);
580 ScriptPubKeyToJSON(coin.out.scriptPubKey, o, true);
581 utxo.push_back(Pair("scriptPubKey", o));
582 utxos.push_back(utxo);
584 objGetUTXOResponse.push_back(Pair("utxos", utxos));
586 // return json string
587 std::string strJSON = objGetUTXOResponse.write() + "\n";
588 req->WriteHeader("Content-Type", "application/json");
589 req->WriteReply(HTTP_OK, strJSON);
590 return true;
592 default: {
593 return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
597 // not reached
598 return true; // continue to process further HTTP reqs on this cxn
601 static const struct {
602 const char* prefix;
603 bool (*handler)(HTTPRequest* req, const std::string& strReq);
604 } uri_prefixes[] = {
605 {"/rest/tx/", rest_tx},
606 {"/rest/block/notxdetails/", rest_block_notxdetails},
607 {"/rest/block/", rest_block_extended},
608 {"/rest/chaininfo", rest_chaininfo},
609 {"/rest/mempool/info", rest_mempool_info},
610 {"/rest/mempool/contents", rest_mempool_contents},
611 {"/rest/headers/", rest_headers},
612 {"/rest/getutxos", rest_getutxos},
615 bool StartREST()
617 for (unsigned int i = 0; i < ARRAYLEN(uri_prefixes); i++)
618 RegisterHTTPHandler(uri_prefixes[i].prefix, false, uri_prefixes[i].handler);
619 return true;
622 void InterruptREST()
626 void StopREST()
628 for (unsigned int i = 0; i < ARRAYLEN(uri_prefixes); i++)
629 UnregisterHTTPHandler(uri_prefixes[i].prefix, false);