]> Git Repo - VerusCoin.git/blob - src/rest.cpp
Major updates integration from all upstreams
[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 "rpc/server.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)
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 // A bit of a hack - dependency on a function defined in rpc/blockchain.cpp
267 UniValue getblockchaininfo(const UniValue& params, bool fHelp);
268
269 static bool rest_chaininfo(HTTPRequest* req, const std::string& strURIPart)
270 {
271     if (!CheckWarmup(req))
272         return false;
273     vector<string> params;
274     const RetFormat rf = ParseDataFormat(params, strURIPart);
275
276     switch (rf) {
277     case RF_JSON: {
278         UniValue rpcParams(UniValue::VARR);
279         UniValue chainInfoObject = getblockchaininfo(rpcParams, false);
280         string strJSON = chainInfoObject.write() + "\n";
281         req->WriteHeader("Content-Type", "application/json");
282         req->WriteReply(HTTP_OK, strJSON);
283         return true;
284     }
285     default: {
286         return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: json)");
287     }
288     }
289
290     // not reached
291     return true; // continue to process further HTTP reqs on this cxn
292 }
293
294 static bool rest_mempool_info(HTTPRequest* req, const std::string& strURIPart)
295 {
296     if (!CheckWarmup(req))
297         return false;
298     vector<string> params;
299     const RetFormat rf = ParseDataFormat(params, strURIPart);
300
301     switch (rf) {
302     case RF_JSON: {
303         UniValue mempoolInfoObject = mempoolInfoToJSON();
304
305         string strJSON = mempoolInfoObject.write() + "\n";
306         req->WriteHeader("Content-Type", "application/json");
307         req->WriteReply(HTTP_OK, strJSON);
308         return true;
309     }
310     default: {
311         return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: json)");
312     }
313     }
314
315     // not reached
316     return true; // continue to process further HTTP reqs on this cxn
317 }
318
319 static bool rest_mempool_contents(HTTPRequest* req, const std::string& strURIPart)
320 {
321     if (!CheckWarmup(req))
322         return false;
323     vector<string> params;
324     const RetFormat rf = ParseDataFormat(params, strURIPart);
325
326     switch (rf) {
327     case RF_JSON: {
328         UniValue mempoolObject = mempoolToJSON(true);
329
330         string strJSON = mempoolObject.write() + "\n";
331         req->WriteHeader("Content-Type", "application/json");
332         req->WriteReply(HTTP_OK, strJSON);
333         return true;
334     }
335     default: {
336         return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: json)");
337     }
338     }
339
340     // not reached
341     return true; // continue to process further HTTP reqs on this cxn
342 }
343
344 static bool rest_tx(HTTPRequest* req, const std::string& strURIPart)
345 {
346     if (!CheckWarmup(req))
347         return false;
348     vector<string> params;
349     const RetFormat rf = ParseDataFormat(params, strURIPart);
350
351     string hashStr = params[0];
352     uint256 hash;
353     if (!ParseHashStr(hashStr, hash))
354         return RESTERR(req, HTTP_BAD_REQUEST, "Invalid hash: " + hashStr);
355
356     CTransaction tx;
357     uint256 hashBlock = uint256();
358     if (!GetTransaction(hash, tx, hashBlock, true))
359         return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found");
360
361     CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
362     ssTx << tx;
363
364     switch (rf) {
365     case RF_BINARY: {
366         string binaryTx = ssTx.str();
367         req->WriteHeader("Content-Type", "application/octet-stream");
368         req->WriteReply(HTTP_OK, binaryTx);
369         return true;
370     }
371
372     case RF_HEX: {
373         string strHex = HexStr(ssTx.begin(), ssTx.end()) + "\n";
374         req->WriteHeader("Content-Type", "text/plain");
375         req->WriteReply(HTTP_OK, strHex);
376         return true;
377     }
378
379     case RF_JSON: {
380         UniValue objTx(UniValue::VOBJ);
381         TxToJSON(tx, hashBlock, objTx);
382         string strJSON = objTx.write() + "\n";
383         req->WriteHeader("Content-Type", "application/json");
384         req->WriteReply(HTTP_OK, strJSON);
385         return true;
386     }
387
388     default: {
389         return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
390     }
391     }
392
393     // not reached
394     return true; // continue to process further HTTP reqs on this cxn
395 }
396
397 static bool rest_getutxos(HTTPRequest* req, const std::string& strURIPart)
398 {
399     if (!CheckWarmup(req))
400         return false;
401     vector<string> params;
402     enum RetFormat rf = ParseDataFormat(params, strURIPart);
403
404     vector<string> uriParts;
405     if (params.size() > 0 && params[0].length() > 1)
406     {
407         std::string strUriParams = params[0].substr(1);
408         boost::split(uriParts, strUriParams, boost::is_any_of("/"));
409     }
410
411     // throw exception in case of an empty request
412     std::string strRequestMutable = req->ReadBody();
413     if (strRequestMutable.length() == 0 && uriParts.size() == 0)
414         return RESTERR(req, HTTP_INTERNAL_SERVER_ERROR, "Error: empty request");
415
416     bool fInputParsed = false;
417     bool fCheckMemPool = false;
418     vector<COutPoint> vOutPoints;
419
420     // parse/deserialize input
421     // input-format = output-format, rest/getutxos/bin requires binary input, gives binary output, ...
422
423     if (uriParts.size() > 0)
424     {
425
426         //inputs is sent over URI scheme (/rest/getutxos/checkmempool/txid1-n/txid2-n/...)
427         if (uriParts.size() > 0 && uriParts[0] == "checkmempool")
428             fCheckMemPool = true;
429
430         for (size_t i = (fCheckMemPool) ? 1 : 0; i < uriParts.size(); i++)
431         {
432             uint256 txid;
433             int32_t nOutput;
434             std::string strTxid = uriParts[i].substr(0, uriParts[i].find("-"));
435             std::string strOutput = uriParts[i].substr(uriParts[i].find("-")+1);
436
437             if (!ParseInt32(strOutput, &nOutput) || !IsHex(strTxid))
438                 return RESTERR(req, HTTP_INTERNAL_SERVER_ERROR, "Parse error");
439
440             txid.SetHex(strTxid);
441             vOutPoints.push_back(COutPoint(txid, (uint32_t)nOutput));
442         }
443
444         if (vOutPoints.size() > 0)
445             fInputParsed = true;
446         else
447             return RESTERR(req, HTTP_INTERNAL_SERVER_ERROR, "Error: empty request");
448     }
449
450     switch (rf) {
451     case RF_HEX: {
452         // convert hex to bin, continue then with bin part
453         std::vector<unsigned char> strRequestV = ParseHex(strRequestMutable);
454         strRequestMutable.assign(strRequestV.begin(), strRequestV.end());
455     }
456
457     case RF_BINARY: {
458         try {
459             //deserialize only if user sent a request
460             if (strRequestMutable.size() > 0)
461             {
462                 if (fInputParsed) //don't allow sending input over URI and HTTP RAW DATA
463                     return RESTERR(req, HTTP_INTERNAL_SERVER_ERROR, "Combination of URI scheme inputs and raw post data is not allowed");
464
465                 CDataStream oss(SER_NETWORK, PROTOCOL_VERSION);
466                 oss << strRequestMutable;
467                 oss >> fCheckMemPool;
468                 oss >> vOutPoints;
469             }
470         } catch (const std::ios_base::failure& e) {
471             // abort in case of unreadable binary data
472             return RESTERR(req, HTTP_INTERNAL_SERVER_ERROR, "Parse error");
473         }
474         break;
475     }
476
477     case RF_JSON: {
478         if (!fInputParsed)
479             return RESTERR(req, HTTP_INTERNAL_SERVER_ERROR, "Error: empty request");
480         break;
481     }
482     default: {
483         return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
484     }
485     }
486
487     // limit max outpoints
488     if (vOutPoints.size() > MAX_GETUTXOS_OUTPOINTS)
489         return RESTERR(req, HTTP_INTERNAL_SERVER_ERROR, strprintf("Error: max outpoints exceeded (max: %d, tried: %d)", MAX_GETUTXOS_OUTPOINTS, vOutPoints.size()));
490
491     // check spentness and form a bitmap (as well as a JSON capable human-readable string representation)
492     vector<unsigned char> bitmap;
493     vector<CCoin> outs;
494     std::string bitmapStringRepresentation;
495     boost::dynamic_bitset<unsigned char> hits(vOutPoints.size());
496     {
497         LOCK2(cs_main, mempool.cs);
498
499         CCoinsView viewDummy;
500         CCoinsViewCache view(&viewDummy);
501
502         CCoinsViewCache& viewChain = *pcoinsTip;
503         CCoinsViewMemPool viewMempool(&viewChain, mempool);
504
505         if (fCheckMemPool)
506             view.SetBackend(viewMempool); // switch cache backend to db+mempool in case user likes to query mempool
507
508         for (size_t i = 0; i < vOutPoints.size(); i++) {
509             CCoins coins;
510             uint256 hash = vOutPoints[i].hash;
511             if (view.GetCoins(hash, coins)) {
512                 mempool.pruneSpent(hash, coins);
513                 if (coins.IsAvailable(vOutPoints[i].n)) {
514                     hits[i] = true;
515                     // Safe to index into vout here because IsAvailable checked if it's off the end of the array, or if
516                     // n is valid but points to an already spent output (IsNull).
517                     CCoin coin;
518                     coin.nTxVer = coins.nVersion;
519                     coin.nHeight = coins.nHeight;
520                     coin.out = coins.vout.at(vOutPoints[i].n);
521                     assert(!coin.out.IsNull());
522                     outs.push_back(coin);
523                 }
524             }
525
526             bitmapStringRepresentation.append(hits[i] ? "1" : "0"); // form a binary string representation (human-readable for json output)
527         }
528     }
529     boost::to_block_range(hits, std::back_inserter(bitmap));
530
531     switch (rf) {
532     case RF_BINARY: {
533         // serialize data
534         // use exact same output as mentioned in Bip64
535         CDataStream ssGetUTXOResponse(SER_NETWORK, PROTOCOL_VERSION);
536         ssGetUTXOResponse << chainActive.Height() << chainActive.LastTip()->GetBlockHash() << bitmap << outs;
537         string ssGetUTXOResponseString = ssGetUTXOResponse.str();
538
539         req->WriteHeader("Content-Type", "application/octet-stream");
540         req->WriteReply(HTTP_OK, ssGetUTXOResponseString);
541         return true;
542     }
543
544     case RF_HEX: {
545         CDataStream ssGetUTXOResponse(SER_NETWORK, PROTOCOL_VERSION);
546         ssGetUTXOResponse << chainActive.Height() << chainActive.LastTip()->GetBlockHash() << bitmap << outs;
547         string strHex = HexStr(ssGetUTXOResponse.begin(), ssGetUTXOResponse.end()) + "\n";
548
549         req->WriteHeader("Content-Type", "text/plain");
550         req->WriteReply(HTTP_OK, strHex);
551         return true;
552     }
553
554     case RF_JSON: {
555         UniValue objGetUTXOResponse(UniValue::VOBJ);
556
557         // pack in some essentials
558         // use more or less the same output as mentioned in Bip64
559         objGetUTXOResponse.push_back(Pair("chainHeight", chainActive.Height()));
560         objGetUTXOResponse.push_back(Pair("chaintipHash", chainActive.LastTip()->GetBlockHash().GetHex()));
561         objGetUTXOResponse.push_back(Pair("bitmap", bitmapStringRepresentation));
562
563         UniValue utxos(UniValue::VARR);
564         BOOST_FOREACH (const CCoin& coin, outs) {
565             UniValue utxo(UniValue::VOBJ);
566             utxo.push_back(Pair("txvers", (int32_t)coin.nTxVer));
567             utxo.push_back(Pair("height", (int32_t)coin.nHeight));
568             utxo.push_back(Pair("value", ValueFromAmount(coin.out.nValue)));
569
570             // include the script in a json output
571             UniValue o(UniValue::VOBJ);
572             ScriptPubKeyToJSON(coin.out.scriptPubKey, o, true);
573             utxo.push_back(Pair("scriptPubKey", o));
574             utxos.push_back(utxo);
575         }
576         objGetUTXOResponse.push_back(Pair("utxos", utxos));
577
578         // return json string
579         string strJSON = objGetUTXOResponse.write() + "\n";
580         req->WriteHeader("Content-Type", "application/json");
581         req->WriteReply(HTTP_OK, strJSON);
582         return true;
583     }
584     default: {
585         return RESTERR(req, HTTP_NOT_FOUND, "output format not found (available: " + AvailableDataFormatsString() + ")");
586     }
587     }
588
589     // not reached
590     return true; // continue to process further HTTP reqs on this cxn
591 }
592
593 static const struct {
594     const char* prefix;
595     bool (*handler)(HTTPRequest* req, const std::string& strReq);
596 } uri_prefixes[] = {
597       {"/rest/tx/", rest_tx},
598       {"/rest/block/notxdetails/", rest_block_notxdetails},
599       {"/rest/block/", rest_block_extended},
600       {"/rest/chaininfo", rest_chaininfo},
601       {"/rest/mempool/info", rest_mempool_info},
602       {"/rest/mempool/contents", rest_mempool_contents},
603       {"/rest/headers/", rest_headers},
604       {"/rest/getutxos", rest_getutxos},
605 };
606
607 bool StartREST()
608 {
609     for (unsigned int i = 0; i < ARRAYLEN(uri_prefixes); i++)
610         RegisterHTTPHandler(uri_prefixes[i].prefix, false, uri_prefixes[i].handler);
611     return true;
612 }
613
614 void InterruptREST()
615 {
616 }
617
618 void StopREST()
619 {
620     for (unsigned int i = 0; i < ARRAYLEN(uri_prefixes); i++)
621         UnregisterHTTPHandler(uri_prefixes[i].prefix, false);
622 }
This page took 0.058545 seconds and 4 git commands to generate.