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
, int nType
, int nVersion
)
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 UniValue
& params
, bool fHelp
);
279 static bool rest_chaininfo(HTTPRequest
* req
, const std::string
& strURIPart
)
281 if (!CheckWarmup(req
))
284 const RetFormat rf
= ParseDataFormat(param
, strURIPart
);
288 UniValue
rpcParams(UniValue::VARR
);
289 UniValue chainInfoObject
= getblockchaininfo(rpcParams
, false);
290 string strJSON
= chainInfoObject
.write() + "\n";
291 req
->WriteHeader("Content-Type", "application/json");
292 req
->WriteReply(HTTP_OK
, strJSON
);
296 return RESTERR(req
, HTTP_NOT_FOUND
, "output format not found (available: json)");
301 return true; // continue to process further HTTP reqs on this cxn
304 static bool rest_mempool_info(HTTPRequest
* req
, const std::string
& strURIPart
)
306 if (!CheckWarmup(req
))
309 const RetFormat rf
= ParseDataFormat(param
, strURIPart
);
313 UniValue mempoolInfoObject
= mempoolInfoToJSON();
315 string strJSON
= mempoolInfoObject
.write() + "\n";
316 req
->WriteHeader("Content-Type", "application/json");
317 req
->WriteReply(HTTP_OK
, strJSON
);
321 return RESTERR(req
, HTTP_NOT_FOUND
, "output format not found (available: json)");
326 return true; // continue to process further HTTP reqs on this cxn
329 static bool rest_mempool_contents(HTTPRequest
* req
, const std::string
& strURIPart
)
331 if (!CheckWarmup(req
))
334 const RetFormat rf
= ParseDataFormat(param
, strURIPart
);
338 UniValue mempoolObject
= mempoolToJSON(true);
340 string strJSON
= mempoolObject
.write() + "\n";
341 req
->WriteHeader("Content-Type", "application/json");
342 req
->WriteReply(HTTP_OK
, strJSON
);
346 return RESTERR(req
, HTTP_NOT_FOUND
, "output format not found (available: json)");
351 return true; // continue to process further HTTP reqs on this cxn
354 static bool rest_tx(HTTPRequest
* req
, const std::string
& strURIPart
)
356 if (!CheckWarmup(req
))
359 const RetFormat rf
= ParseDataFormat(hashStr
, strURIPart
);
362 if (!ParseHashStr(hashStr
, hash
))
363 return RESTERR(req
, HTTP_BAD_REQUEST
, "Invalid hash: " + hashStr
);
366 uint256 hashBlock
= uint256();
367 if (!GetTransaction(hash
, tx
, Params().GetConsensus(), hashBlock
, true))
368 return RESTERR(req
, HTTP_NOT_FOUND
, hashStr
+ " not found");
370 CDataStream
ssTx(SER_NETWORK
, PROTOCOL_VERSION
);
375 string binaryTx
= ssTx
.str();
376 req
->WriteHeader("Content-Type", "application/octet-stream");
377 req
->WriteReply(HTTP_OK
, binaryTx
);
382 string strHex
= HexStr(ssTx
.begin(), ssTx
.end()) + "\n";
383 req
->WriteHeader("Content-Type", "text/plain");
384 req
->WriteReply(HTTP_OK
, strHex
);
389 UniValue
objTx(UniValue::VOBJ
);
390 TxToJSON(tx
, hashBlock
, objTx
);
391 string strJSON
= objTx
.write() + "\n";
392 req
->WriteHeader("Content-Type", "application/json");
393 req
->WriteReply(HTTP_OK
, strJSON
);
398 return RESTERR(req
, HTTP_NOT_FOUND
, "output format not found (available: " + AvailableDataFormatsString() + ")");
403 return true; // continue to process further HTTP reqs on this cxn
406 static bool rest_getutxos(HTTPRequest
* req
, const std::string
& strURIPart
)
408 if (!CheckWarmup(req
))
411 const RetFormat rf
= ParseDataFormat(param
, strURIPart
);
413 vector
<string
> uriParts
;
414 if (param
.length() > 1)
416 std::string strUriParams
= param
.substr(1);
417 boost::split(uriParts
, strUriParams
, boost::is_any_of("/"));
420 // throw exception in case of a empty request
421 std::string strRequestMutable
= req
->ReadBody();
422 if (strRequestMutable
.length() == 0 && uriParts
.size() == 0)
423 return RESTERR(req
, HTTP_INTERNAL_SERVER_ERROR
, "Error: empty request");
425 bool fInputParsed
= false;
426 bool fCheckMemPool
= false;
427 vector
<COutPoint
> vOutPoints
;
429 // parse/deserialize input
430 // input-format = output-format, rest/getutxos/bin requires binary input, gives binary output, ...
432 if (uriParts
.size() > 0)
435 //inputs is sent over URI scheme (/rest/getutxos/checkmempool/txid1-n/txid2-n/...)
436 if (uriParts
.size() > 0 && uriParts
[0] == "checkmempool")
437 fCheckMemPool
= true;
439 for (size_t i
= (fCheckMemPool
) ? 1 : 0; i
< uriParts
.size(); i
++)
443 std::string strTxid
= uriParts
[i
].substr(0, uriParts
[i
].find("-"));
444 std::string strOutput
= uriParts
[i
].substr(uriParts
[i
].find("-")+1);
446 if (!ParseInt32(strOutput
, &nOutput
) || !IsHex(strTxid
))
447 return RESTERR(req
, HTTP_INTERNAL_SERVER_ERROR
, "Parse error");
449 txid
.SetHex(strTxid
);
450 vOutPoints
.push_back(COutPoint(txid
, (uint32_t)nOutput
));
453 if (vOutPoints
.size() > 0)
456 return RESTERR(req
, HTTP_INTERNAL_SERVER_ERROR
, "Error: empty request");
461 // convert hex to bin, continue then with bin part
462 std::vector
<unsigned char> strRequestV
= ParseHex(strRequestMutable
);
463 strRequestMutable
.assign(strRequestV
.begin(), strRequestV
.end());
468 //deserialize only if user sent a request
469 if (strRequestMutable
.size() > 0)
471 if (fInputParsed
) //don't allow sending input over URI and HTTP RAW DATA
472 return RESTERR(req
, HTTP_INTERNAL_SERVER_ERROR
, "Combination of URI scheme inputs and raw post data is not allowed");
474 CDataStream
oss(SER_NETWORK
, PROTOCOL_VERSION
);
475 oss
<< strRequestMutable
;
476 oss
>> fCheckMemPool
;
479 } catch (const std::ios_base::failure
& e
) {
480 // abort in case of unreadable binary data
481 return RESTERR(req
, HTTP_INTERNAL_SERVER_ERROR
, "Parse error");
488 return RESTERR(req
, HTTP_INTERNAL_SERVER_ERROR
, "Error: empty request");
492 return RESTERR(req
, HTTP_NOT_FOUND
, "output format not found (available: " + AvailableDataFormatsString() + ")");
496 // limit max outpoints
497 if (vOutPoints
.size() > MAX_GETUTXOS_OUTPOINTS
)
498 return RESTERR(req
, HTTP_INTERNAL_SERVER_ERROR
, strprintf("Error: max outpoints exceeded (max: %d, tried: %d)", MAX_GETUTXOS_OUTPOINTS
, vOutPoints
.size()));
500 // check spentness and form a bitmap (as well as a JSON capable human-readable string representation)
501 vector
<unsigned char> bitmap
;
503 std::string bitmapStringRepresentation
;
504 boost::dynamic_bitset
<unsigned char> hits(vOutPoints
.size());
506 LOCK2(cs_main
, mempool
.cs
);
508 CCoinsView viewDummy
;
509 CCoinsViewCache
view(&viewDummy
);
511 CCoinsViewCache
& viewChain
= *pcoinsTip
;
512 CCoinsViewMemPool
viewMempool(&viewChain
, mempool
);
515 view
.SetBackend(viewMempool
); // switch cache backend to db+mempool in case user likes to query mempool
517 for (size_t i
= 0; i
< vOutPoints
.size(); i
++) {
519 uint256 hash
= vOutPoints
[i
].hash
;
520 if (view
.GetCoins(hash
, coins
)) {
521 mempool
.pruneSpent(hash
, coins
);
522 if (coins
.IsAvailable(vOutPoints
[i
].n
)) {
524 // Safe to index into vout here because IsAvailable checked if it's off the end of the array, or if
525 // n is valid but points to an already spent output (IsNull).
527 coin
.nTxVer
= coins
.nVersion
;
528 coin
.nHeight
= coins
.nHeight
;
529 coin
.out
= coins
.vout
.at(vOutPoints
[i
].n
);
530 assert(!coin
.out
.IsNull());
531 outs
.push_back(coin
);
535 bitmapStringRepresentation
.append(hits
[i
] ? "1" : "0"); // form a binary string representation (human-readable for json output)
538 boost::to_block_range(hits
, std::back_inserter(bitmap
));
543 // use exact same output as mentioned in Bip64
544 CDataStream
ssGetUTXOResponse(SER_NETWORK
, PROTOCOL_VERSION
);
545 ssGetUTXOResponse
<< chainActive
.Height() << chainActive
.Tip()->GetBlockHash() << bitmap
<< outs
;
546 string ssGetUTXOResponseString
= ssGetUTXOResponse
.str();
548 req
->WriteHeader("Content-Type", "application/octet-stream");
549 req
->WriteReply(HTTP_OK
, ssGetUTXOResponseString
);
554 CDataStream
ssGetUTXOResponse(SER_NETWORK
, PROTOCOL_VERSION
);
555 ssGetUTXOResponse
<< chainActive
.Height() << chainActive
.Tip()->GetBlockHash() << bitmap
<< outs
;
556 string strHex
= HexStr(ssGetUTXOResponse
.begin(), ssGetUTXOResponse
.end()) + "\n";
558 req
->WriteHeader("Content-Type", "text/plain");
559 req
->WriteReply(HTTP_OK
, strHex
);
564 UniValue
objGetUTXOResponse(UniValue::VOBJ
);
566 // pack in some essentials
567 // use more or less the same output as mentioned in Bip64
568 objGetUTXOResponse
.push_back(Pair("chainHeight", chainActive
.Height()));
569 objGetUTXOResponse
.push_back(Pair("chaintipHash", chainActive
.Tip()->GetBlockHash().GetHex()));
570 objGetUTXOResponse
.push_back(Pair("bitmap", bitmapStringRepresentation
));
572 UniValue
utxos(UniValue::VARR
);
573 BOOST_FOREACH (const CCoin
& coin
, outs
) {
574 UniValue
utxo(UniValue::VOBJ
);
575 utxo
.push_back(Pair("txvers", (int32_t)coin
.nTxVer
));
576 utxo
.push_back(Pair("height", (int32_t)coin
.nHeight
));
577 utxo
.push_back(Pair("value", ValueFromAmount(coin
.out
.nValue
)));
579 // include the script in a json output
580 UniValue
o(UniValue::VOBJ
);
581 ScriptPubKeyToJSON(coin
.out
.scriptPubKey
, o
, true);
582 utxo
.push_back(Pair("scriptPubKey", o
));
583 utxos
.push_back(utxo
);
585 objGetUTXOResponse
.push_back(Pair("utxos", utxos
));
587 // return json string
588 string strJSON
= objGetUTXOResponse
.write() + "\n";
589 req
->WriteHeader("Content-Type", "application/json");
590 req
->WriteReply(HTTP_OK
, strJSON
);
594 return RESTERR(req
, HTTP_NOT_FOUND
, "output format not found (available: " + AvailableDataFormatsString() + ")");
599 return true; // continue to process further HTTP reqs on this cxn
602 static const struct {
604 bool (*handler
)(HTTPRequest
* req
, const std::string
& strReq
);
606 {"/rest/tx/", rest_tx
},
607 {"/rest/block/notxdetails/", rest_block_notxdetails
},
608 {"/rest/block/", rest_block_extended
},
609 {"/rest/chaininfo", rest_chaininfo
},
610 {"/rest/mempool/info", rest_mempool_info
},
611 {"/rest/mempool/contents", rest_mempool_contents
},
612 {"/rest/headers/", rest_headers
},
613 {"/rest/getutxos", rest_getutxos
},
618 for (unsigned int i
= 0; i
< ARRAYLEN(uri_prefixes
); i
++)
619 RegisterHTTPHandler(uri_prefixes
[i
].prefix
, false, uri_prefixes
[i
].handler
);
629 for (unsigned int i
= 0; i
< ARRAYLEN(uri_prefixes
); i
++)
630 UnregisterHTTPHandler(uri_prefixes
[i
].prefix
, false);