]> Git Repo - VerusCoin.git/blob - src/rest.cpp
Merge pull request #44 from jl777/dev
[VerusCoin.git] / src / rest.cpp
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.
5
6 #include "primitives/block.h"
7 #include "primitives/transaction.h"
8 #include "main.h"
9 #include "httpserver.h"
10 #include "rpcserver.h"
11 #include "streams.h"
12 #include "sync.h"
13 #include "txmempool.h"
14 #include "utilstrencodings.h"
15 #include "version.h"
16
17 #include <boost/algorithm/string.hpp>
18 #include <boost/dynamic_bitset.hpp>
19
20 #include <univalue.h>
21
22 using namespace std;
23
24 static const size_t MAX_GETUTXOS_OUTPOINTS = 15; //allow a max of 15 outpoints to be queried at once
25
26 enum RetFormat {
27     RF_UNDEF,
28     RF_BINARY,
29     RF_HEX,
30     RF_JSON,
31 };
32
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"},
41 };
42
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;
47
48     ADD_SERIALIZE_METHODS;
49
50     template <typename Stream, typename Operation>
51     inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
52     {
53         READWRITE(nTxVer);
54         READWRITE(nHeight);
55         READWRITE(out);
56     }
57 };
58
59 extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry);
60 extern UniValue blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool txDetails = false);
61 extern UniValue mempoolInfoToJSON();
62 extern UniValue mempoolToJSON(bool fVerbose = false);
63 extern void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex);
64 extern UniValue blockheaderToJSON(const CBlockIndex* blockindex);
65
66 static bool RESTERR(HTTPRequest* req, enum HTTPStatusCode status, string message)
67 {
68     req->WriteHeader("Content-Type", "text/plain");
69     req->WriteReply(status, message + "\r\n");
70     return false;
71 }
72
73 static enum RetFormat ParseDataFormat(vector<string>& params, const string& strReq)
74 {
75     boost::split(params, strReq, boost::is_any_of("."));
76     if (params.size() > 1) {
77         for (unsigned int i = 0; i < ARRAYLEN(rf_names); i++)
78             if (params[1] == rf_names[i].name)
79                 return rf_names[i].rf;
80     }
81
82     return rf_names[0].rf;
83 }
84
85 static string AvailableDataFormatsString()
86 {
87     string formats = "";
88     for (unsigned int i = 0; i < ARRAYLEN(rf_names); i++)
89         if (strlen(rf_names[i].name) > 0) {
90             formats.append(".");
91             formats.append(rf_names[i].name);
92             formats.append(", ");
93         }
94
95     if (formats.length() > 0)
96         return formats.substr(0, formats.length() - 2);
97
98     return formats;
99 }
100
101 static bool ParseHashStr(const string& strReq, uint256& v)
102 {
103     if (!IsHex(strReq) || (strReq.size() != 64))
104         return false;
105
106     v.SetHex(strReq);
107     return true;
108 }
109
110 static bool CheckWarmup(HTTPRequest* req)
111 {
112     std::string statusmessage;
113     if (RPCIsInWarmup(&statusmessage))
114          return RESTERR(req, HTTP_SERVICE_UNAVAILABLE, "Service temporarily unavailable: " + statusmessage);
115     return true;
116 }
117
118 static bool rest_headers(HTTPRequest* req,
119                          const std::string& strURIPart)
120 {
121     if (!CheckWarmup(req))
122         return false;
123     vector<string> params;
124     const RetFormat rf = ParseDataFormat(params, strURIPart);
125     vector<string> path;
126     boost::split(path, params[0], boost::is_any_of("/"));
127
128     if (path.size() != 2)
129         return RESTERR(req, HTTP_BAD_REQUEST, "No header count specified. Use /rest/headers/<count>/<hash>.<ext>.");
130
131     long count = strtol(path[0].c_str(), NULL, 10);
132     if (count < 1 || count > 2000)
133         return RESTERR(req, HTTP_BAD_REQUEST, "Header count out of range: " + path[0]);
134
135     string hashStr = path[1];
136     uint256 hash;
137     if (!ParseHashStr(hashStr, hash))
138         return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);
139
140     std::vector<const CBlockIndex *> headers;
141     headers.reserve(count);
142     {
143         LOCK(cs_main);
144         BlockMap::const_iterator it = mapBlockIndex.find(hash);
145         const CBlockIndex *pindex = (it != mapBlockIndex.end()) ? it->second : NULL;
146         while (pindex != NULL && chainActive.Contains(pindex)) {
147             headers.push_back(pindex);
148             if (headers.size() == (unsigned long)count)
149                 break;
150             pindex = chainActive.Next(pindex);
151         }
152     }
153
154     CDataStream ssHeader(SER_NETWORK, PROTOCOL_VERSION);
155     BOOST_FOREACH(const CBlockIndex *pindex, headers) {
156         ssHeader << pindex->GetBlockHeader();
157     }
158
159     switch (rf) {
160     case RF_BINARY: {
161         string binaryHeader = ssHeader.str();
162         req->WriteHeader("Content-Type", "application/octet-stream");
163         req->WriteReply(HTTP_OK, binaryHeader);
164         return true;
165     }
166
167     case RF_HEX: {
168         string strHex = HexStr(ssHeader.begin(), ssHeader.end()) + "\n";
169         req->WriteHeader("Content-Type", "text/plain");
170         req->WriteReply(HTTP_OK, strHex);
171         return true;
172     }
173     case RF_JSON: {
174         UniValue jsonHeaders(UniValue::VARR);
175         BOOST_FOREACH(const CBlockIndex *pindex, headers) {
176             jsonHeaders.push_back(blockheaderToJSON(pindex));
177         }
178         string strJSON = jsonHeaders.write() + "\n";
179         req->WriteHeader("Content-Type", "application/json");
180         req->WriteReply(HTTP_OK, strJSON);
181         return true;
182     }
183     default: {
184         return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: .bin, .hex)");
185     }
186     }
187
188     // not reached
189     return true; // continue to process further HTTP reqs on this cxn
190 }
191
192 static bool rest_block(HTTPRequest* req,
193                        const std::string& strURIPart,
194                        bool showTxDetails)
195 {
196     if (!CheckWarmup(req))
197         return false;
198     vector<string> params;
199     const RetFormat rf = ParseDataFormat(params, strURIPart);
200
201     string hashStr = params[0];
202     uint256 hash;
203     if (!ParseHashStr(hashStr, hash))
204         return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);
205
206     CBlock block;
207     CBlockIndex* pblockindex = NULL;
208     {
209         LOCK(cs_main);
210         if (mapBlockIndex.count(hash) == 0)
211             return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found");
212
213         pblockindex = mapBlockIndex[hash];
214         if (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0)
215             return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not available (pruned data)");
216
217         if (!ReadBlockFromDisk(block, pblockindex,1))
218             return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found");
219     }
220
221     CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
222     ssBlock << block;
223
224     switch (rf) {
225     case RF_BINARY: {
226         string binaryBlock = ssBlock.str();
227         req->WriteHeader("Content-Type", "application/octet-stream");
228         req->WriteReply(HTTP_OK, binaryBlock);
229         return true;
230     }
231
232     case RF_HEX: {
233         string strHex = HexStr(ssBlock.begin(), ssBlock.end()) + "\n";
234         req->WriteHeader("Content-Type", "text/plain");
235         req->WriteReply(HTTP_OK, strHex);
236         return true;
237     }
238
239     case RF_JSON: {
240         UniValue objBlock = blockToJSON(block, pblockindex, showTxDetails);
241         string strJSON = objBlock.write() + "\n";
242         req->WriteHeader("Content-Type", "application/json");
243         req->WriteReply(HTTP_OK, strJSON);
244         return true;
245     }
246
247     default: {
248         return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
249     }
250     }
251
252     // not reached
253     return true; // continue to process further HTTP reqs on this cxn
254 }
255
256 static bool rest_block_extended(HTTPRequest* req, const std::string& strURIPart)
257 {
258     return rest_block(req, strURIPart, true);
259 }
260
261 static bool rest_block_notxdetails(HTTPRequest* req, const std::string& strURIPart)
262 {
263     return rest_block(req, strURIPart, false);
264 }
265
266 static bool rest_chaininfo(HTTPRequest* req, const std::string& strURIPart)
267 {
268     if (!CheckWarmup(req))
269         return false;
270     vector<string> params;
271     const RetFormat rf = ParseDataFormat(params, strURIPart);
272
273     switch (rf) {
274     case RF_JSON: {
275         UniValue rpcParams(UniValue::VARR);
276         UniValue chainInfoObject = getblockchaininfo(rpcParams, false);
277         string strJSON = chainInfoObject.write() + "\n";
278         req->WriteHeader("Content-Type", "application/json");
279         req->WriteReply(HTTP_OK, strJSON);
280         return true;
281     }
282     default: {
283         return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: json)");
284     }
285     }
286
287     // not reached
288     return true; // continue to process further HTTP reqs on this cxn
289 }
290
291 static bool rest_mempool_info(HTTPRequest* req, const std::string& strURIPart)
292 {
293     if (!CheckWarmup(req))
294         return false;
295     vector<string> params;
296     const RetFormat rf = ParseDataFormat(params, strURIPart);
297
298     switch (rf) {
299     case RF_JSON: {
300         UniValue mempoolInfoObject = mempoolInfoToJSON();
301
302         string strJSON = mempoolInfoObject.write() + "\n";
303         req->WriteHeader("Content-Type", "application/json");
304         req->WriteReply(HTTP_OK, strJSON);
305         return true;
306     }
307     default: {
308         return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: json)");
309     }
310     }
311
312     // not reached
313     return true; // continue to process further HTTP reqs on this cxn
314 }
315
316 static bool rest_mempool_contents(HTTPRequest* req, const std::string& strURIPart)
317 {
318     if (!CheckWarmup(req))
319         return false;
320     vector<string> params;
321     const RetFormat rf = ParseDataFormat(params, strURIPart);
322
323     switch (rf) {
324     case RF_JSON: {
325         UniValue mempoolObject = mempoolToJSON(true);
326
327         string strJSON = mempoolObject.write() + "\n";
328         req->WriteHeader("Content-Type", "application/json");
329         req->WriteReply(HTTP_OK, strJSON);
330         return true;
331     }
332     default: {
333         return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: json)");
334     }
335     }
336
337     // not reached
338     return true; // continue to process further HTTP reqs on this cxn
339 }
340
341 static bool rest_tx(HTTPRequest* req, const std::string& strURIPart)
342 {
343     if (!CheckWarmup(req))
344         return false;
345     vector<string> params;
346     const RetFormat rf = ParseDataFormat(params, strURIPart);
347
348     string hashStr = params[0];
349     uint256 hash;
350     if (!ParseHashStr(hashStr, hash))
351         return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);
352
353     CTransaction tx;
354     uint256 hashBlock = uint256();
355     if (!GetTransaction(hash, tx, hashBlock, true))
356         return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found");
357
358     CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
359     ssTx << tx;
360
361     switch (rf) {
362     case RF_BINARY: {
363         string binaryTx = ssTx.str();
364         req->WriteHeader("Content-Type", "application/octet-stream");
365         req->WriteReply(HTTP_OK, binaryTx);
366         return true;
367     }
368
369     case RF_HEX: {
370         string strHex = HexStr(ssTx.begin(), ssTx.end()) + "\n";
371         req->WriteHeader("Content-Type", "text/plain");
372         req->WriteReply(HTTP_OK, strHex);
373         return true;
374     }
375
376     case RF_JSON: {
377         UniValue objTx(UniValue::VOBJ);
378         TxToJSON(tx, hashBlock, objTx);
379         string strJSON = objTx.write() + "\n";
380         req->WriteHeader("Content-Type", "application/json");
381         req->WriteReply(HTTP_OK, strJSON);
382         return true;
383     }
384
385     default: {
386         return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
387     }
388     }
389
390     // not reached
391     return true; // continue to process further HTTP reqs on this cxn
392 }
393
394 static bool rest_getutxos(HTTPRequest* req, const std::string& strURIPart)
395 {
396     if (!CheckWarmup(req))
397         return false;
398     vector<string> params;
399     enum RetFormat rf = ParseDataFormat(params, strURIPart);
400
401     vector<string> uriParts;
402     if (params.size() > 0 && params[0].length() > 1)
403     {
404         std::string strUriParams = params[0].substr(1);
405         boost::split(uriParts, strUriParams, boost::is_any_of("/"));
406     }
407
408     // throw exception in case of an empty request
409     std::string strRequestMutable = req->ReadBody();
410     if (strRequestMutable.length() == 0 && uriParts.size() == 0)
411         return RESTERR(req, HTTP_INTERNAL_SERVER_ERROR, "Error: empty request");
412
413     bool fInputParsed = false;
414     bool fCheckMemPool = false;
415     vector<COutPoint> vOutPoints;
416
417     // parse/deserialize input
418     // input-format = output-format, rest/getutxos/bin requires binary input, gives binary output, ...
419
420     if (uriParts.size() > 0)
421     {
422
423         //inputs is sent over URI scheme (/rest/getutxos/checkmempool/txid1-n/txid2-n/...)
424         if (uriParts.size() > 0 && uriParts[0] == "checkmempool")
425             fCheckMemPool = true;
426
427         for (size_t i = (fCheckMemPool) ? 1 : 0; i < uriParts.size(); i++)
428         {
429             uint256 txid;
430             int32_t nOutput;
431             std::string strTxid = uriParts[i].substr(0, uriParts[i].find("-"));
432             std::string strOutput = uriParts[i].substr(uriParts[i].find("-")+1);
433
434             if (!ParseInt32(strOutput, &nOutput) || !IsHex(strTxid))
435                 return RESTERR(req, HTTP_INTERNAL_SERVER_ERROR, "Parse error");
436
437             txid.SetHex(strTxid);
438             vOutPoints.push_back(COutPoint(txid, (uint32_t)nOutput));
439         }
440
441         if (vOutPoints.size() > 0)
442             fInputParsed = true;
443         else
444             return RESTERR(req, HTTP_INTERNAL_SERVER_ERROR, "Error: empty request");
445     }
446
447     switch (rf) {
448     case RF_HEX: {
449         // convert hex to bin, continue then with bin part
450         std::vector<unsigned char> strRequestV = ParseHex(strRequestMutable);
451         strRequestMutable.assign(strRequestV.begin(), strRequestV.end());
452     }
453
454     case RF_BINARY: {
455         try {
456             //deserialize only if user sent a request
457             if (strRequestMutable.size() > 0)
458             {
459                 if (fInputParsed) //don't allow sending input over URI and HTTP RAW DATA
460                     return RESTERR(req, HTTP_INTERNAL_SERVER_ERROR, "Combination of URI scheme inputs and raw post data is not allowed");
461
462                 CDataStream oss(SER_NETWORK, PROTOCOL_VERSION);
463                 oss << strRequestMutable;
464                 oss >> fCheckMemPool;
465                 oss >> vOutPoints;
466             }
467         } catch (const std::ios_base::failure& e) {
468             // abort in case of unreadable binary data
469             return RESTERR(req, HTTP_INTERNAL_SERVER_ERROR, "Parse error");
470         }
471         break;
472     }
473
474     case RF_JSON: {
475         if (!fInputParsed)
476             return RESTERR(req, HTTP_INTERNAL_SERVER_ERROR, "Error: empty request");
477         break;
478     }
479     default: {
480         return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
481     }
482     }
483
484     // limit max outpoints
485     if (vOutPoints.size() > MAX_GETUTXOS_OUTPOINTS)
486         return RESTERR(req, HTTP_INTERNAL_SERVER_ERROR, strprintf("Error: max outpoints exceeded (max: %d, tried: %d)", MAX_GETUTXOS_OUTPOINTS, vOutPoints.size()));
487
488     // check spentness and form a bitmap (as well as a JSON capable human-readable string representation)
489     vector<unsigned char> bitmap;
490     vector<CCoin> outs;
491     std::string bitmapStringRepresentation;
492     boost::dynamic_bitset<unsigned char> hits(vOutPoints.size());
493     {
494         LOCK2(cs_main, mempool.cs);
495
496         CCoinsView viewDummy;
497         CCoinsViewCache view(&viewDummy);
498
499         CCoinsViewCache& viewChain = *pcoinsTip;
500         CCoinsViewMemPool viewMempool(&viewChain, mempool);
501
502         if (fCheckMemPool)
503             view.SetBackend(viewMempool); // switch cache backend to db+mempool in case user likes to query mempool
504
505         for (size_t i = 0; i < vOutPoints.size(); i++) {
506             CCoins coins;
507             uint256 hash = vOutPoints[i].hash;
508             if (view.GetCoins(hash, coins)) {
509                 mempool.pruneSpent(hash, coins);
510                 if (coins.IsAvailable(vOutPoints[i].n)) {
511                     hits[i] = true;
512                     // Safe to index into vout here because IsAvailable checked if it's off the end of the array, or if
513                     // n is valid but points to an already spent output (IsNull).
514                     CCoin coin;
515                     coin.nTxVer = coins.nVersion;
516                     coin.nHeight = coins.nHeight;
517                     coin.out = coins.vout.at(vOutPoints[i].n);
518                     assert(!coin.out.IsNull());
519                     outs.push_back(coin);
520                 }
521             }
522
523             bitmapStringRepresentation.append(hits[i] ? "1" : "0"); // form a binary string representation (human-readable for json output)
524         }
525     }
526     boost::to_block_range(hits, std::back_inserter(bitmap));
527
528     switch (rf) {
529     case RF_BINARY: {
530         // serialize data
531         // use exact same output as mentioned in Bip64
532         CDataStream ssGetUTXOResponse(SER_NETWORK, PROTOCOL_VERSION);
533         ssGetUTXOResponse << chainActive.Height() << chainActive.LastTip()->GetBlockHash() << bitmap << outs;
534         string ssGetUTXOResponseString = ssGetUTXOResponse.str();
535
536         req->WriteHeader("Content-Type", "application/octet-stream");
537         req->WriteReply(HTTP_OK, ssGetUTXOResponseString);
538         return true;
539     }
540
541     case RF_HEX: {
542         CDataStream ssGetUTXOResponse(SER_NETWORK, PROTOCOL_VERSION);
543         ssGetUTXOResponse << chainActive.Height() << chainActive.LastTip()->GetBlockHash() << bitmap << outs;
544         string strHex = HexStr(ssGetUTXOResponse.begin(), ssGetUTXOResponse.end()) + "\n";
545
546         req->WriteHeader("Content-Type", "text/plain");
547         req->WriteReply(HTTP_OK, strHex);
548         return true;
549     }
550
551     case RF_JSON: {
552         UniValue objGetUTXOResponse(UniValue::VOBJ);
553
554         // pack in some essentials
555         // use more or less the same output as mentioned in Bip64
556         objGetUTXOResponse.push_back(Pair("chainHeight", chainActive.Height()));
557         objGetUTXOResponse.push_back(Pair("chaintipHash", chainActive.LastTip()->GetBlockHash().GetHex()));
558         objGetUTXOResponse.push_back(Pair("bitmap", bitmapStringRepresentation));
559
560         UniValue utxos(UniValue::VARR);
561         BOOST_FOREACH (const CCoin& coin, outs) {
562             UniValue utxo(UniValue::VOBJ);
563             utxo.push_back(Pair("txvers", (int32_t)coin.nTxVer));
564             utxo.push_back(Pair("height", (int32_t)coin.nHeight));
565             utxo.push_back(Pair("value", ValueFromAmount(coin.out.nValue)));
566
567             // include the script in a json output
568             UniValue o(UniValue::VOBJ);
569             ScriptPubKeyToJSON(coin.out.scriptPubKey, o, true);
570             utxo.push_back(Pair("scriptPubKey", o));
571             utxos.push_back(utxo);
572         }
573         objGetUTXOResponse.push_back(Pair("utxos", utxos));
574
575         // return json string
576         string strJSON = objGetUTXOResponse.write() + "\n";
577         req->WriteHeader("Content-Type", "application/json");
578         req->WriteReply(HTTP_OK, strJSON);
579         return true;
580     }
581     default: {
582         return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
583     }
584     }
585
586     // not reached
587     return true; // continue to process further HTTP reqs on this cxn
588 }
589
590 static const struct {
591     const char* prefix;
592     bool (*handler)(HTTPRequest* req, const std::string& strReq);
593 } uri_prefixes[] = {
594       {"/rest/tx/", rest_tx},
595       {"/rest/block/notxdetails/", rest_block_notxdetails},
596       {"/rest/block/", rest_block_extended},
597       {"/rest/chaininfo", rest_chaininfo},
598       {"/rest/mempool/info", rest_mempool_info},
599       {"/rest/mempool/contents", rest_mempool_contents},
600       {"/rest/headers/", rest_headers},
601       {"/rest/getutxos", rest_getutxos},
602 };
603
604 bool StartREST()
605 {
606     for (unsigned int i = 0; i < ARRAYLEN(uri_prefixes); i++)
607         RegisterHTTPHandler(uri_prefixes[i].prefix, false, uri_prefixes[i].handler);
608     return true;
609 }
610
611 void InterruptREST()
612 {
613 }
614
615 void StopREST()
616 {
617     for (unsigned int i = 0; i < ARRAYLEN(uri_prefixes); i++)
618         UnregisterHTTPHandler(uri_prefixes[i].prefix, false);
619 }
This page took 0.060427 seconds and 4 git commands to generate.