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.
7 #include "chainparams.h"
8 #include "primitives/block.h"
9 #include "primitives/transaction.h"
11 #include "httpserver.h"
12 #include "rpc/server.h"
15 #include "txmempool.h"
16 #include "utilstrencodings.h"
19 #include <boost/algorithm/string.hpp>
20 #include <boost/dynamic_bitset.hpp>
26 static const size_t MAX_GETUTXOS_OUTPOINTS
= 15; //allow a max of 15 outpoints to be queried at once
46 uint32_t nTxVer
; // Don't call this nVersion, that name has a special meaning inside IMPLEMENT_SERIALIZE
50 ADD_SERIALIZE_METHODS
;
52 template <typename Stream
, typename Operation
>
53 inline void SerializationOp(Stream
& s
, Operation ser_action
)
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");
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
)
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. */
93 return rf_names
[0].rf
;
96 static string
AvailableDataFormatsString()
99 for (unsigned int i
= 0; i
< ARRAYLEN(rf_names
); i
++)
100 if (strlen(rf_names
[i
].name
) > 0) {
102 formats
.append(rf_names
[i
].name
);
103 formats
.append(", ");
106 if (formats
.length() > 0)
107 return formats
.substr(0, formats
.length() - 2);
112 static bool ParseHashStr(const string
& strReq
, uint256
& v
)
114 if (!IsHex(strReq
) || (strReq
.size() != 64))
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
);
129 static bool rest_headers(HTTPRequest
* req
,
130 const std::string
& strURIPart
)
132 if (!CheckWarmup(req
))
135 const RetFormat rf
= ParseDataFormat(param
, strURIPart
);
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];
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
);
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
)
161 pindex
= chainActive
.Next(pindex
);
165 CDataStream
ssHeader(SER_NETWORK
, PROTOCOL_VERSION
);
166 BOOST_FOREACH(const CBlockIndex
*pindex
, headers
) {
167 ssHeader
<< pindex
->GetBlockHeader();
172 string binaryHeader
= ssHeader
.str();
173 req
->WriteHeader("Content-Type", "application/octet-stream");
174 req
->WriteReply(HTTP_OK
, binaryHeader
);
179 string strHex
= HexStr(ssHeader
.begin(), ssHeader
.end()) + "\n";
180 req
->WriteHeader("Content-Type", "text/plain");
181 req
->WriteReply(HTTP_OK
, strHex
);
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
);
195 return RESTERR(req
, HTTP_NOT_FOUND
, "output format not found (available: .bin, .hex)");
200 return true; // continue to process further HTTP reqs on this cxn
203 static bool rest_block(HTTPRequest
* req
,
204 const std::string
& strURIPart
,
207 if (!CheckWarmup(req
))
210 const RetFormat rf
= ParseDataFormat(hashStr
, strURIPart
);
213 if (!ParseHashStr(hashStr
, hash
))
214 return RESTERR(req
, HTTP_BAD_REQUEST
, "Invalid hash: " + hashStr
);
217 CBlockIndex
* pblockindex
= NULL
;
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
);
236 string binaryBlock
= ssBlock
.str();
237 req
->WriteHeader("Content-Type", "application/octet-stream");
238 req
->WriteReply(HTTP_OK
, binaryBlock
);
243 string strHex
= HexStr(ssBlock
.begin(), ssBlock
.end()) + "\n";
244 req
->WriteHeader("Content-Type", "text/plain");
245 req
->WriteReply(HTTP_OK
, strHex
);
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
);
258 return RESTERR(req
, HTTP_NOT_FOUND
, "output format not found (available: " + AvailableDataFormatsString() + ")");
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 JSONRPCRequest
& request
);
279 static bool rest_chaininfo(HTTPRequest
* req
, const std::string
& strURIPart
)
281 if (!CheckWarmup(req
))
284 const RetFormat rf
= ParseDataFormat(param
, strURIPart
);
288 JSONRPCRequest jsonRequest
;
289 jsonRequest
.params
= UniValue(UniValue::VARR
);
290 UniValue chainInfoObject
= getblockchaininfo(jsonRequest
);
291 string strJSON
= chainInfoObject
.write() + "\n";
292 req
->WriteHeader("Content-Type", "application/json");
293 req
->WriteReply(HTTP_OK
, strJSON
);
297 return RESTERR(req
, HTTP_NOT_FOUND
, "output format not found (available: json)");
302 return true; // continue to process further HTTP reqs on this cxn
305 static bool rest_mempool_info(HTTPRequest
* req
, const std::string
& strURIPart
)
307 if (!CheckWarmup(req
))
310 const RetFormat rf
= ParseDataFormat(param
, strURIPart
);
314 UniValue mempoolInfoObject
= mempoolInfoToJSON();
316 string strJSON
= mempoolInfoObject
.write() + "\n";
317 req
->WriteHeader("Content-Type", "application/json");
318 req
->WriteReply(HTTP_OK
, strJSON
);
322 return RESTERR(req
, HTTP_NOT_FOUND
, "output format not found (available: json)");
327 return true; // continue to process further HTTP reqs on this cxn
330 static bool rest_mempool_contents(HTTPRequest
* req
, const std::string
& strURIPart
)
332 if (!CheckWarmup(req
))
335 const RetFormat rf
= ParseDataFormat(param
, strURIPart
);
339 UniValue mempoolObject
= mempoolToJSON(true);
341 string strJSON
= mempoolObject
.write() + "\n";
342 req
->WriteHeader("Content-Type", "application/json");
343 req
->WriteReply(HTTP_OK
, strJSON
);
347 return RESTERR(req
, HTTP_NOT_FOUND
, "output format not found (available: json)");
352 return true; // continue to process further HTTP reqs on this cxn
355 static bool rest_tx(HTTPRequest
* req
, const std::string
& strURIPart
)
357 if (!CheckWarmup(req
))
360 const RetFormat rf
= ParseDataFormat(hashStr
, strURIPart
);
363 if (!ParseHashStr(hashStr
, hash
))
364 return RESTERR(req
, HTTP_BAD_REQUEST
, "Invalid hash: " + hashStr
);
367 uint256 hashBlock
= uint256();
368 if (!GetTransaction(hash
, tx
, Params().GetConsensus(), hashBlock
, true))
369 return RESTERR(req
, HTTP_NOT_FOUND
, hashStr
+ " not found");
371 CDataStream
ssTx(SER_NETWORK
, PROTOCOL_VERSION
);
376 string binaryTx
= ssTx
.str();
377 req
->WriteHeader("Content-Type", "application/octet-stream");
378 req
->WriteReply(HTTP_OK
, binaryTx
);
383 string strHex
= HexStr(ssTx
.begin(), ssTx
.end()) + "\n";
384 req
->WriteHeader("Content-Type", "text/plain");
385 req
->WriteReply(HTTP_OK
, strHex
);
390 UniValue
objTx(UniValue::VOBJ
);
391 TxToJSON(tx
, hashBlock
, objTx
);
392 string strJSON
= objTx
.write() + "\n";
393 req
->WriteHeader("Content-Type", "application/json");
394 req
->WriteReply(HTTP_OK
, strJSON
);
399 return RESTERR(req
, HTTP_NOT_FOUND
, "output format not found (available: " + AvailableDataFormatsString() + ")");
404 return true; // continue to process further HTTP reqs on this cxn
407 static bool rest_getutxos(HTTPRequest
* req
, const std::string
& strURIPart
)
409 if (!CheckWarmup(req
))
412 const RetFormat rf
= ParseDataFormat(param
, strURIPart
);
414 vector
<string
> uriParts
;
415 if (param
.length() > 1)
417 std::string strUriParams
= param
.substr(1);
418 boost::split(uriParts
, strUriParams
, boost::is_any_of("/"));
421 // throw exception in case of a empty request
422 std::string strRequestMutable
= req
->ReadBody();
423 if (strRequestMutable
.length() == 0 && uriParts
.size() == 0)
424 return RESTERR(req
, HTTP_BAD_REQUEST
, "Error: empty request");
426 bool fInputParsed
= false;
427 bool fCheckMemPool
= false;
428 vector
<COutPoint
> vOutPoints
;
430 // parse/deserialize input
431 // input-format = output-format, rest/getutxos/bin requires binary input, gives binary output, ...
433 if (uriParts
.size() > 0)
436 //inputs is sent over URI scheme (/rest/getutxos/checkmempool/txid1-n/txid2-n/...)
437 if (uriParts
.size() > 0 && uriParts
[0] == "checkmempool")
438 fCheckMemPool
= true;
440 for (size_t i
= (fCheckMemPool
) ? 1 : 0; i
< uriParts
.size(); i
++)
444 std::string strTxid
= uriParts
[i
].substr(0, uriParts
[i
].find("-"));
445 std::string strOutput
= uriParts
[i
].substr(uriParts
[i
].find("-")+1);
447 if (!ParseInt32(strOutput
, &nOutput
) || !IsHex(strTxid
))
448 return RESTERR(req
, HTTP_BAD_REQUEST
, "Parse error");
450 txid
.SetHex(strTxid
);
451 vOutPoints
.push_back(COutPoint(txid
, (uint32_t)nOutput
));
454 if (vOutPoints
.size() > 0)
457 return RESTERR(req
, HTTP_BAD_REQUEST
, "Error: empty request");
462 // convert hex to bin, continue then with bin part
463 std::vector
<unsigned char> strRequestV
= ParseHex(strRequestMutable
);
464 strRequestMutable
.assign(strRequestV
.begin(), strRequestV
.end());
469 //deserialize only if user sent a request
470 if (strRequestMutable
.size() > 0)
472 if (fInputParsed
) //don't allow sending input over URI and HTTP RAW DATA
473 return RESTERR(req
, HTTP_BAD_REQUEST
, "Combination of URI scheme inputs and raw post data is not allowed");
475 CDataStream
oss(SER_NETWORK
, PROTOCOL_VERSION
);
476 oss
<< strRequestMutable
;
477 oss
>> fCheckMemPool
;
480 } catch (const std::ios_base::failure
& e
) {
481 // abort in case of unreadable binary data
482 return RESTERR(req
, HTTP_BAD_REQUEST
, "Parse error");
489 return RESTERR(req
, HTTP_BAD_REQUEST
, "Error: empty request");
493 return RESTERR(req
, HTTP_NOT_FOUND
, "output format not found (available: " + AvailableDataFormatsString() + ")");
497 // limit max outpoints
498 if (vOutPoints
.size() > MAX_GETUTXOS_OUTPOINTS
)
499 return RESTERR(req
, HTTP_BAD_REQUEST
, strprintf("Error: max outpoints exceeded (max: %d, tried: %d)", MAX_GETUTXOS_OUTPOINTS
, vOutPoints
.size()));
501 // check spentness and form a bitmap (as well as a JSON capable human-readable string representation)
502 vector
<unsigned char> bitmap
;
504 std::string bitmapStringRepresentation
;
505 boost::dynamic_bitset
<unsigned char> hits(vOutPoints
.size());
507 LOCK2(cs_main
, mempool
.cs
);
509 CCoinsView viewDummy
;
510 CCoinsViewCache
view(&viewDummy
);
512 CCoinsViewCache
& viewChain
= *pcoinsTip
;
513 CCoinsViewMemPool
viewMempool(&viewChain
, mempool
);
516 view
.SetBackend(viewMempool
); // switch cache backend to db+mempool in case user likes to query mempool
518 for (size_t i
= 0; i
< vOutPoints
.size(); i
++) {
520 uint256 hash
= vOutPoints
[i
].hash
;
521 if (view
.GetCoins(hash
, coins
)) {
522 mempool
.pruneSpent(hash
, coins
);
523 if (coins
.IsAvailable(vOutPoints
[i
].n
)) {
525 // Safe to index into vout here because IsAvailable checked if it's off the end of the array, or if
526 // n is valid but points to an already spent output (IsNull).
528 coin
.nTxVer
= coins
.nVersion
;
529 coin
.nHeight
= coins
.nHeight
;
530 coin
.out
= coins
.vout
.at(vOutPoints
[i
].n
);
531 assert(!coin
.out
.IsNull());
532 outs
.push_back(coin
);
536 bitmapStringRepresentation
.append(hits
[i
] ? "1" : "0"); // form a binary string representation (human-readable for json output)
539 boost::to_block_range(hits
, std::back_inserter(bitmap
));
544 // use exact same output as mentioned in Bip64
545 CDataStream
ssGetUTXOResponse(SER_NETWORK
, PROTOCOL_VERSION
);
546 ssGetUTXOResponse
<< chainActive
.Height() << chainActive
.Tip()->GetBlockHash() << bitmap
<< outs
;
547 string ssGetUTXOResponseString
= ssGetUTXOResponse
.str();
549 req
->WriteHeader("Content-Type", "application/octet-stream");
550 req
->WriteReply(HTTP_OK
, ssGetUTXOResponseString
);
555 CDataStream
ssGetUTXOResponse(SER_NETWORK
, PROTOCOL_VERSION
);
556 ssGetUTXOResponse
<< chainActive
.Height() << chainActive
.Tip()->GetBlockHash() << bitmap
<< outs
;
557 string strHex
= HexStr(ssGetUTXOResponse
.begin(), ssGetUTXOResponse
.end()) + "\n";
559 req
->WriteHeader("Content-Type", "text/plain");
560 req
->WriteReply(HTTP_OK
, strHex
);
565 UniValue
objGetUTXOResponse(UniValue::VOBJ
);
567 // pack in some essentials
568 // use more or less the same output as mentioned in Bip64
569 objGetUTXOResponse
.push_back(Pair("chainHeight", chainActive
.Height()));
570 objGetUTXOResponse
.push_back(Pair("chaintipHash", chainActive
.Tip()->GetBlockHash().GetHex()));
571 objGetUTXOResponse
.push_back(Pair("bitmap", bitmapStringRepresentation
));
573 UniValue
utxos(UniValue::VARR
);
574 BOOST_FOREACH (const CCoin
& coin
, outs
) {
575 UniValue
utxo(UniValue::VOBJ
);
576 utxo
.push_back(Pair("txvers", (int32_t)coin
.nTxVer
));
577 utxo
.push_back(Pair("height", (int32_t)coin
.nHeight
));
578 utxo
.push_back(Pair("value", ValueFromAmount(coin
.out
.nValue
)));
580 // include the script in a json output
581 UniValue
o(UniValue::VOBJ
);
582 ScriptPubKeyToJSON(coin
.out
.scriptPubKey
, o
, true);
583 utxo
.push_back(Pair("scriptPubKey", o
));
584 utxos
.push_back(utxo
);
586 objGetUTXOResponse
.push_back(Pair("utxos", utxos
));
588 // return json string
589 string strJSON
= objGetUTXOResponse
.write() + "\n";
590 req
->WriteHeader("Content-Type", "application/json");
591 req
->WriteReply(HTTP_OK
, strJSON
);
595 return RESTERR(req
, HTTP_NOT_FOUND
, "output format not found (available: " + AvailableDataFormatsString() + ")");
600 return true; // continue to process further HTTP reqs on this cxn
603 static const struct {
605 bool (*handler
)(HTTPRequest
* req
, const std::string
& strReq
);
607 {"/rest/tx/", rest_tx
},
608 {"/rest/block/notxdetails/", rest_block_notxdetails
},
609 {"/rest/block/", rest_block_extended
},
610 {"/rest/chaininfo", rest_chaininfo
},
611 {"/rest/mempool/info", rest_mempool_info
},
612 {"/rest/mempool/contents", rest_mempool_contents
},
613 {"/rest/headers/", rest_headers
},
614 {"/rest/getutxos", rest_getutxos
},
619 for (unsigned int i
= 0; i
< ARRAYLEN(uri_prefixes
); i
++)
620 RegisterHTTPHandler(uri_prefixes
[i
].prefix
, false, uri_prefixes
[i
].handler
);
630 for (unsigned int i
= 0; i
< ARRAYLEN(uri_prefixes
); i
++)
631 UnregisterHTTPHandler(uri_prefixes
[i
].prefix
, false);