1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 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 "primitives/block.h"
7 #include "primitives/transaction.h"
12 #include "txmempool.h"
13 #include "utilstrencodings.h"
16 #include <boost/algorithm/string.hpp>
17 #include <boost/dynamic_bitset.hpp>
20 using namespace json_spirit;
22 static const int MAX_GETUTXOS_OUTPOINTS = 15; //allow a max of 15 outpoints to be queried at once
42 uint32_t nTxVer; // Don't call this nVersion, that name has a special meaning inside IMPLEMENT_SERIALIZE
46 ADD_SERIALIZE_METHODS;
48 template <typename Stream, typename Operation>
49 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
60 enum HTTPStatusCode status;
64 extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry);
65 extern Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool txDetails = false);
66 extern void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out, bool fIncludeHex);
68 static RestErr RESTERR(enum HTTPStatusCode status, string message)
76 static enum RetFormat ParseDataFormat(vector<string>& params, const string strReq)
78 boost::split(params, strReq, boost::is_any_of("."));
79 if (params.size() > 1) {
80 for (unsigned int i = 0; i < ARRAYLEN(rf_names); i++)
81 if (params[1] == rf_names[i].name)
82 return rf_names[i].rf;
85 return rf_names[0].rf;
88 static string AvailableDataFormatsString()
91 for (unsigned int i = 0; i < ARRAYLEN(rf_names); i++)
92 if (strlen(rf_names[i].name) > 0) {
94 formats.append(rf_names[i].name);
98 if (formats.length() > 0)
99 return formats.substr(0, formats.length() - 2);
104 static bool ParseHashStr(const string& strReq, uint256& v)
106 if (!IsHex(strReq) || (strReq.size() != 64))
113 static bool rest_headers(AcceptedConnection* conn,
114 const std::string& strURIPart,
115 const std::string& strRequest,
116 const std::map<std::string, std::string>& mapHeaders,
119 vector<string> params;
120 const RetFormat rf = ParseDataFormat(params, strURIPart);
122 boost::split(path, params[0], boost::is_any_of("/"));
124 if (path.size() != 2)
125 throw RESTERR(HTTP_BAD_REQUEST, "No header count specified. Use /rest/headers/<count>/<hash>.<ext>.");
127 long count = strtol(path[0].c_str(), NULL, 10);
128 if (count < 1 || count > 2000)
129 throw RESTERR(HTTP_BAD_REQUEST, "Header count out of range: " + path[0]);
131 string hashStr = path[1];
133 if (!ParseHashStr(hashStr, hash))
134 throw RESTERR(HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);
136 std::vector<CBlockHeader> headers;
137 headers.reserve(count);
140 BlockMap::const_iterator it = mapBlockIndex.find(hash);
141 const CBlockIndex *pindex = (it != mapBlockIndex.end()) ? it->second : NULL;
142 while (pindex != NULL && chainActive.Contains(pindex)) {
143 headers.push_back(pindex->GetBlockHeader());
144 if (headers.size() == (unsigned long)count)
146 pindex = chainActive.Next(pindex);
150 CDataStream ssHeader(SER_NETWORK, PROTOCOL_VERSION);
151 BOOST_FOREACH(const CBlockHeader &header, headers) {
157 string binaryHeader = ssHeader.str();
158 conn->stream() << HTTPReplyHeader(HTTP_OK, fRun, binaryHeader.size(), "application/octet-stream") << binaryHeader << std::flush;
163 string strHex = HexStr(ssHeader.begin(), ssHeader.end()) + "\n";
164 conn->stream() << HTTPReply(HTTP_OK, strHex, fRun, false, "text/plain") << std::flush;
169 throw RESTERR(HTTP_NOT_FOUND, "output format not found (available: .bin, .hex)");
174 return true; // continue to process further HTTP reqs on this cxn
177 static bool rest_block(AcceptedConnection* conn,
178 const std::string& strURIPart,
179 const std::string& strRequest,
180 const std::map<std::string, std::string>& mapHeaders,
184 vector<string> params;
185 const RetFormat rf = ParseDataFormat(params, strURIPart);
187 string hashStr = params[0];
189 if (!ParseHashStr(hashStr, hash))
190 throw RESTERR(HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);
193 CBlockIndex* pblockindex = NULL;
196 if (mapBlockIndex.count(hash) == 0)
197 throw RESTERR(HTTP_NOT_FOUND, hashStr + " not found");
199 pblockindex = mapBlockIndex[hash];
200 if (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0)
201 throw RESTERR(HTTP_NOT_FOUND, hashStr + " not available (pruned data)");
203 if (!ReadBlockFromDisk(block, pblockindex))
204 throw RESTERR(HTTP_NOT_FOUND, hashStr + " not found");
207 CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
212 string binaryBlock = ssBlock.str();
213 conn->stream() << HTTPReplyHeader(HTTP_OK, fRun, binaryBlock.size(), "application/octet-stream") << binaryBlock << std::flush;
218 string strHex = HexStr(ssBlock.begin(), ssBlock.end()) + "\n";
219 conn->stream() << HTTPReply(HTTP_OK, strHex, fRun, false, "text/plain") << std::flush;
224 Object objBlock = blockToJSON(block, pblockindex, showTxDetails);
225 string strJSON = write_string(Value(objBlock), false) + "\n";
226 conn->stream() << HTTPReply(HTTP_OK, strJSON, fRun) << std::flush;
231 throw RESTERR(HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
236 return true; // continue to process further HTTP reqs on this cxn
239 static bool rest_block_extended(AcceptedConnection* conn,
240 const std::string& strURIPart,
241 const std::string& strRequest,
242 const std::map<std::string, std::string>& mapHeaders,
245 return rest_block(conn, strURIPart, strRequest, mapHeaders, fRun, true);
248 static bool rest_block_notxdetails(AcceptedConnection* conn,
249 const std::string& strURIPart,
250 const std::string& strRequest,
251 const std::map<std::string, std::string>& mapHeaders,
254 return rest_block(conn, strURIPart, strRequest, mapHeaders, fRun, false);
257 static bool rest_chaininfo(AcceptedConnection* conn,
258 const std::string& strURIPart,
259 const std::string& strRequest,
260 const std::map<std::string, std::string>& mapHeaders,
263 vector<string> params;
264 const RetFormat rf = ParseDataFormat(params, strURIPart);
269 Value chainInfoObject = getblockchaininfo(rpcParams, false);
271 string strJSON = write_string(chainInfoObject, false) + "\n";
272 conn->stream() << HTTPReply(HTTP_OK, strJSON, fRun) << std::flush;
276 throw RESTERR(HTTP_NOT_FOUND, "output format not found (available: json)");
281 return true; // continue to process further HTTP reqs on this cxn
284 static bool rest_tx(AcceptedConnection* conn,
285 const std::string& strURIPart,
286 const std::string& strRequest,
287 const std::map<std::string, std::string>& mapHeaders,
290 vector<string> params;
291 const RetFormat rf = ParseDataFormat(params, strURIPart);
293 string hashStr = params[0];
295 if (!ParseHashStr(hashStr, hash))
296 throw RESTERR(HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);
299 uint256 hashBlock = uint256();
300 if (!GetTransaction(hash, tx, hashBlock, true))
301 throw RESTERR(HTTP_NOT_FOUND, hashStr + " not found");
303 CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
308 string binaryTx = ssTx.str();
309 conn->stream() << HTTPReplyHeader(HTTP_OK, fRun, binaryTx.size(), "application/octet-stream") << binaryTx << std::flush;
314 string strHex = HexStr(ssTx.begin(), ssTx.end()) + "\n";
315 conn->stream() << HTTPReply(HTTP_OK, strHex, fRun, false, "text/plain") << std::flush;
321 TxToJSON(tx, hashBlock, objTx);
322 string strJSON = write_string(Value(objTx), false) + "\n";
323 conn->stream() << HTTPReply(HTTP_OK, strJSON, fRun) << std::flush;
328 throw RESTERR(HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
333 return true; // continue to process further HTTP reqs on this cxn
336 static bool rest_getutxos(AcceptedConnection* conn,
337 const std::string& strURIPart,
338 const std::string& strRequest,
339 const std::map<std::string, std::string>& mapHeaders,
342 vector<string> params;
343 enum RetFormat rf = ParseDataFormat(params, strURIPart);
345 vector<string> uriParts;
346 if (params.size() > 0 && params[0].length() > 1)
348 std::string strUriParams = params[0].substr(1);
349 boost::split(uriParts, strUriParams, boost::is_any_of("/"));
352 // throw exception in case of a empty request
353 if (strRequest.length() == 0 && uriParts.size() == 0)
354 throw RESTERR(HTTP_INTERNAL_SERVER_ERROR, "Error: empty request");
356 bool fInputParsed = false;
357 bool fCheckMemPool = false;
358 vector<COutPoint> vOutPoints;
360 // parse/deserialize input
361 // input-format = output-format, rest/getutxos/bin requires binary input, gives binary output, ...
363 if (uriParts.size() > 0)
366 //inputs is sent over URI scheme (/rest/getutxos/checkmempool/txid1-n/txid2-n/...)
367 if (uriParts.size() > 0 && uriParts[0] == "checkmempool")
368 fCheckMemPool = true;
370 for (size_t i = (fCheckMemPool) ? 1 : 0; i < uriParts.size(); i++)
374 std::string strTxid = uriParts[i].substr(0, uriParts[i].find("-"));
375 std::string strOutput = uriParts[i].substr(uriParts[i].find("-")+1);
377 if (!ParseInt32(strOutput, &nOutput) || !IsHex(strTxid))
378 throw RESTERR(HTTP_INTERNAL_SERVER_ERROR, "Parse error");
380 txid.SetHex(strTxid);
381 vOutPoints.push_back(COutPoint(txid, (uint32_t)nOutput));
384 if (vOutPoints.size() > 0)
387 throw RESTERR(HTTP_INTERNAL_SERVER_ERROR, "Error: empty request");
390 string strRequestMutable = strRequest; //convert const string to string for allowing hex to bin converting
394 // convert hex to bin, continue then with bin part
395 std::vector<unsigned char> strRequestV = ParseHex(strRequest);
396 strRequestMutable.assign(strRequestV.begin(), strRequestV.end());
401 //deserialize only if user sent a request
402 if (strRequestMutable.size() > 0)
404 if (fInputParsed) //don't allow sending input over URI and HTTP RAW DATA
405 throw RESTERR(HTTP_INTERNAL_SERVER_ERROR, "Combination of URI scheme inputs and raw post data is not allowed");
407 CDataStream oss(SER_NETWORK, PROTOCOL_VERSION);
408 oss << strRequestMutable;
409 oss >> fCheckMemPool;
412 } catch (const std::ios_base::failure& e) {
413 // abort in case of unreadable binary data
414 throw RESTERR(HTTP_INTERNAL_SERVER_ERROR, "Parse error");
421 throw RESTERR(HTTP_INTERNAL_SERVER_ERROR, "Error: empty request");
425 throw RESTERR(HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
429 // limit max outpoints
430 if (vOutPoints.size() > MAX_GETUTXOS_OUTPOINTS)
431 throw RESTERR(HTTP_INTERNAL_SERVER_ERROR, strprintf("Error: max outpoints exceeded (max: %d, tried: %d)", MAX_GETUTXOS_OUTPOINTS, vOutPoints.size()));
433 // check spentness and form a bitmap (as well as a JSON capable human-readble string representation)
434 vector<unsigned char> bitmap;
436 std::string bitmapStringRepresentation;
437 boost::dynamic_bitset<unsigned char> hits(vOutPoints.size());
439 LOCK2(cs_main, mempool.cs);
441 CCoinsView viewDummy;
442 CCoinsViewCache view(&viewDummy);
444 CCoinsViewCache& viewChain = *pcoinsTip;
445 CCoinsViewMemPool viewMempool(&viewChain, mempool);
448 view.SetBackend(viewMempool); // switch cache backend to db+mempool in case user likes to query mempool
450 for (size_t i = 0; i < vOutPoints.size(); i++) {
452 uint256 hash = vOutPoints[i].hash;
453 if (view.GetCoins(hash, coins)) {
454 mempool.pruneSpent(hash, coins);
455 if (coins.IsAvailable(vOutPoints[i].n)) {
457 // Safe to index into vout here because IsAvailable checked if it's off the end of the array, or if
458 // n is valid but points to an already spent output (IsNull).
460 coin.nTxVer = coins.nVersion;
461 coin.nHeight = coins.nHeight;
462 coin.out = coins.vout.at(vOutPoints[i].n);
463 assert(!coin.out.IsNull());
464 outs.push_back(coin);
468 bitmapStringRepresentation.append(hits[i] ? "1" : "0"); // form a binary string representation (human-readable for json output)
471 boost::to_block_range(hits, std::back_inserter(bitmap));
476 // use exact same output as mentioned in Bip64
477 CDataStream ssGetUTXOResponse(SER_NETWORK, PROTOCOL_VERSION);
478 ssGetUTXOResponse << chainActive.Height() << chainActive.Tip()->GetBlockHash() << bitmap << outs;
479 string ssGetUTXOResponseString = ssGetUTXOResponse.str();
481 conn->stream() << HTTPReplyHeader(HTTP_OK, fRun, ssGetUTXOResponseString.size(), "application/octet-stream") << ssGetUTXOResponseString << std::flush;
486 CDataStream ssGetUTXOResponse(SER_NETWORK, PROTOCOL_VERSION);
487 ssGetUTXOResponse << chainActive.Height() << chainActive.Tip()->GetBlockHash() << bitmap << outs;
488 string strHex = HexStr(ssGetUTXOResponse.begin(), ssGetUTXOResponse.end()) + "\n";
490 conn->stream() << HTTPReply(HTTP_OK, strHex, fRun, false, "text/plain") << std::flush;
495 Object objGetUTXOResponse;
497 // pack in some essentials
498 // use more or less the same output as mentioned in Bip64
499 objGetUTXOResponse.push_back(Pair("chainHeight", chainActive.Height()));
500 objGetUTXOResponse.push_back(Pair("chaintipHash", chainActive.Tip()->GetBlockHash().GetHex()));
501 objGetUTXOResponse.push_back(Pair("bitmap", bitmapStringRepresentation));
504 BOOST_FOREACH (const CCoin& coin, outs) {
506 utxo.push_back(Pair("txvers", (int32_t)coin.nTxVer));
507 utxo.push_back(Pair("height", (int32_t)coin.nHeight));
508 utxo.push_back(Pair("value", ValueFromAmount(coin.out.nValue)));
509 //utxo.push_back(Pair("interest", ValueFromAmount(komodo_interest(coin.out.nValue,coin.nLockTime,chainActive.Tip()->nTime))));
511 // include the script in a json output
513 ScriptPubKeyToJSON(coin.out.scriptPubKey, o, true);
514 utxo.push_back(Pair("scriptPubKey", o));
515 utxos.push_back(utxo);
517 objGetUTXOResponse.push_back(Pair("utxos", utxos));
519 // return json string
520 string strJSON = write_string(Value(objGetUTXOResponse), false) + "\n";
521 conn->stream() << HTTPReply(HTTP_OK, strJSON, fRun) << std::flush;
525 throw RESTERR(HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
530 return true; // continue to process further HTTP reqs on this cxn
533 static const struct {
535 bool (*handler)(AcceptedConnection* conn,
536 const std::string& strURIPart,
537 const std::string& strRequest,
538 const std::map<std::string, std::string>& mapHeaders,
541 {"/rest/tx/", rest_tx},
542 {"/rest/block/notxdetails/", rest_block_notxdetails},
543 {"/rest/block/", rest_block_extended},
544 {"/rest/chaininfo", rest_chaininfo},
545 {"/rest/headers/", rest_headers},
546 {"/rest/getutxos", rest_getutxos},
549 bool HTTPReq_REST(AcceptedConnection* conn,
550 const std::string& strURI,
551 const string& strRequest,
552 const std::map<std::string, std::string>& mapHeaders,
556 std::string statusmessage;
557 if (RPCIsInWarmup(&statusmessage))
558 throw RESTERR(HTTP_SERVICE_UNAVAILABLE, "Service temporarily unavailable: " + statusmessage);
560 for (unsigned int i = 0; i < ARRAYLEN(uri_prefixes); i++) {
561 unsigned int plen = strlen(uri_prefixes[i].prefix);
562 if (strURI.substr(0, plen) == uri_prefixes[i].prefix) {
563 string strURIPart = strURI.substr(plen);
564 return uri_prefixes[i].handler(conn, strURIPart, strRequest, mapHeaders, fRun);
567 } catch (const RestErr& re) {
568 conn->stream() << HTTPReply(re.status, re.message + "\r\n", false, false, "text/plain") << std::flush;
572 conn->stream() << HTTPError(HTTP_NOT_FOUND, false) << std::flush;