You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

rest.py 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2014-2016 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. """Test the REST API."""
  6. from test_framework.test_framework import BitcoinTestFramework
  7. from test_framework.util import *
  8. from struct import *
  9. from io import BytesIO
  10. from codecs import encode
  11. import http.client
  12. import urllib.parse
  13. def deser_uint256(f):
  14. r = 0
  15. for i in range(8):
  16. t = unpack(b"<I", f.read(4))[0]
  17. r += t << (i * 32)
  18. return r
  19. #allows simple http get calls
  20. def http_get_call(host, port, path, response_object = 0):
  21. conn = http.client.HTTPConnection(host, port)
  22. conn.request('GET', path)
  23. if response_object:
  24. return conn.getresponse()
  25. return conn.getresponse().read().decode('utf-8')
  26. #allows simple http post calls with a request body
  27. def http_post_call(host, port, path, requestdata = '', response_object = 0):
  28. conn = http.client.HTTPConnection(host, port)
  29. conn.request('POST', path, requestdata)
  30. if response_object:
  31. return conn.getresponse()
  32. return conn.getresponse().read()
  33. class RESTTest (BitcoinTestFramework):
  34. FORMAT_SEPARATOR = "."
  35. def set_test_params(self):
  36. self.setup_clean_chain = True
  37. self.num_nodes = 3
  38. def setup_network(self, split=False):
  39. super().setup_network()
  40. connect_nodes_bi(self.nodes, 0, 2)
  41. def run_test(self):
  42. url = urllib.parse.urlparse(self.nodes[0].url)
  43. self.log.info("Mining blocks...")
  44. self.nodes[0].generate(1)
  45. self.sync_all()
  46. self.nodes[2].generate(100)
  47. self.sync_all()
  48. assert_equal(self.nodes[0].getbalance(), 50)
  49. txid = self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 0.1)
  50. self.sync_all()
  51. self.nodes[2].generate(1)
  52. self.sync_all()
  53. bb_hash = self.nodes[0].getbestblockhash()
  54. assert_equal(self.nodes[1].getbalance(), Decimal("0.1")) #balance now should be 0.1 on node 1
  55. # load the latest 0.1 tx over the REST API
  56. json_string = http_get_call(url.hostname, url.port, '/rest/tx/'+txid+self.FORMAT_SEPARATOR+"json")
  57. json_obj = json.loads(json_string)
  58. vintx = json_obj['vin'][0]['txid'] # get the vin to later check for utxo (should be spent by then)
  59. # get n of 0.1 outpoint
  60. n = 0
  61. for vout in json_obj['vout']:
  62. if vout['value'] == 0.1:
  63. n = vout['n']
  64. #######################################
  65. # GETUTXOS: query an unspent outpoint #
  66. #######################################
  67. json_request = '/checkmempool/'+txid+'-'+str(n)
  68. json_string = http_get_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json')
  69. json_obj = json.loads(json_string)
  70. #check chainTip response
  71. assert_equal(json_obj['chaintipHash'], bb_hash)
  72. #make sure there is one utxo
  73. assert_equal(len(json_obj['utxos']), 1)
  74. assert_equal(json_obj['utxos'][0]['value'], 0.1)
  75. #################################################
  76. # GETUTXOS: now query an already spent outpoint #
  77. #################################################
  78. json_request = '/checkmempool/'+vintx+'-0'
  79. json_string = http_get_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json')
  80. json_obj = json.loads(json_string)
  81. #check chainTip response
  82. assert_equal(json_obj['chaintipHash'], bb_hash)
  83. #make sure there is no utox in the response because this oupoint has been spent
  84. assert_equal(len(json_obj['utxos']), 0)
  85. #check bitmap
  86. assert_equal(json_obj['bitmap'], "0")
  87. ##################################################
  88. # GETUTXOS: now check both with the same request #
  89. ##################################################
  90. json_request = '/checkmempool/'+txid+'-'+str(n)+'/'+vintx+'-0'
  91. json_string = http_get_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json')
  92. json_obj = json.loads(json_string)
  93. assert_equal(len(json_obj['utxos']), 1)
  94. assert_equal(json_obj['bitmap'], "10")
  95. #test binary response
  96. bb_hash = self.nodes[0].getbestblockhash()
  97. binaryRequest = b'\x01\x02'
  98. binaryRequest += hex_str_to_bytes(txid)
  99. binaryRequest += pack("i", n)
  100. binaryRequest += hex_str_to_bytes(vintx)
  101. binaryRequest += pack("i", 0)
  102. bin_response = http_post_call(url.hostname, url.port, '/rest/getutxos'+self.FORMAT_SEPARATOR+'bin', binaryRequest)
  103. output = BytesIO()
  104. output.write(bin_response)
  105. output.seek(0)
  106. chainHeight = unpack("i", output.read(4))[0]
  107. hashFromBinResponse = hex(deser_uint256(output))[2:].zfill(64)
  108. assert_equal(bb_hash, hashFromBinResponse) #check if getutxo's chaintip during calculation was fine
  109. assert_equal(chainHeight, 102) #chain height must be 102
  110. ############################
  111. # GETUTXOS: mempool checks #
  112. ############################
  113. # do a tx and don't sync
  114. txid = self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 0.1)
  115. json_string = http_get_call(url.hostname, url.port, '/rest/tx/'+txid+self.FORMAT_SEPARATOR+"json")
  116. json_obj = json.loads(json_string)
  117. vintx = json_obj['vin'][0]['txid'] # get the vin to later check for utxo (should be spent by then)
  118. # get n of 0.1 outpoint
  119. n = 0
  120. for vout in json_obj['vout']:
  121. if vout['value'] == 0.1:
  122. n = vout['n']
  123. json_request = '/'+txid+'-'+str(n)
  124. json_string = http_get_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json')
  125. json_obj = json.loads(json_string)
  126. assert_equal(len(json_obj['utxos']), 0) #there should be an outpoint because it has just added to the mempool
  127. json_request = '/checkmempool/'+txid+'-'+str(n)
  128. json_string = http_get_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json')
  129. json_obj = json.loads(json_string)
  130. assert_equal(len(json_obj['utxos']), 1) #there should be an outpoint because it has just added to the mempool
  131. #do some invalid requests
  132. json_request = '{"checkmempool'
  133. response = http_post_call(url.hostname, url.port, '/rest/getutxos'+self.FORMAT_SEPARATOR+'json', json_request, True)
  134. assert_equal(response.status, 400) #must be a 400 because we send an invalid json request
  135. json_request = '{"checkmempool'
  136. response = http_post_call(url.hostname, url.port, '/rest/getutxos'+self.FORMAT_SEPARATOR+'bin', json_request, True)
  137. assert_equal(response.status, 400) #must be a 400 because we send an invalid bin request
  138. response = http_post_call(url.hostname, url.port, '/rest/getutxos/checkmempool'+self.FORMAT_SEPARATOR+'bin', '', True)
  139. assert_equal(response.status, 400) #must be a 400 because we send an invalid bin request
  140. #test limits
  141. json_request = '/checkmempool/'
  142. for x in range(0, 20):
  143. json_request += txid+'-'+str(n)+'/'
  144. json_request = json_request.rstrip("/")
  145. response = http_post_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json', '', True)
  146. assert_equal(response.status, 400) #must be a 400 because we exceeding the limits
  147. json_request = '/checkmempool/'
  148. for x in range(0, 15):
  149. json_request += txid+'-'+str(n)+'/'
  150. json_request = json_request.rstrip("/")
  151. response = http_post_call(url.hostname, url.port, '/rest/getutxos'+json_request+self.FORMAT_SEPARATOR+'json', '', True)
  152. assert_equal(response.status, 200) #must be a 200 because we are within the limits
  153. self.nodes[0].generate(1) #generate block to not affect upcoming tests
  154. self.sync_all()
  155. ################
  156. # /rest/block/ #
  157. ################
  158. # check binary format
  159. response = http_get_call(url.hostname, url.port, '/rest/block/'+bb_hash+self.FORMAT_SEPARATOR+"bin", True)
  160. assert_equal(response.status, 200)
  161. assert_greater_than(int(response.getheader('content-length')), 80)
  162. response_str = response.read()
  163. # compare with block header
  164. response_header = http_get_call(url.hostname, url.port, '/rest/headers/1/'+bb_hash+self.FORMAT_SEPARATOR+"bin", True)
  165. assert_equal(response_header.status, 200)
  166. assert_equal(int(response_header.getheader('content-length')), 80)
  167. response_header_str = response_header.read()
  168. assert_equal(response_str[0:80], response_header_str)
  169. # check block hex format
  170. response_hex = http_get_call(url.hostname, url.port, '/rest/block/'+bb_hash+self.FORMAT_SEPARATOR+"hex", True)
  171. assert_equal(response_hex.status, 200)
  172. assert_greater_than(int(response_hex.getheader('content-length')), 160)
  173. response_hex_str = response_hex.read()
  174. assert_equal(encode(response_str, "hex_codec")[0:160], response_hex_str[0:160])
  175. # compare with hex block header
  176. response_header_hex = http_get_call(url.hostname, url.port, '/rest/headers/1/'+bb_hash+self.FORMAT_SEPARATOR+"hex", True)
  177. assert_equal(response_header_hex.status, 200)
  178. assert_greater_than(int(response_header_hex.getheader('content-length')), 160)
  179. response_header_hex_str = response_header_hex.read()
  180. assert_equal(response_hex_str[0:160], response_header_hex_str[0:160])
  181. assert_equal(encode(response_header_str, "hex_codec")[0:160], response_header_hex_str[0:160])
  182. # check json format
  183. block_json_string = http_get_call(url.hostname, url.port, '/rest/block/'+bb_hash+self.FORMAT_SEPARATOR+'json')
  184. block_json_obj = json.loads(block_json_string)
  185. assert_equal(block_json_obj['hash'], bb_hash)
  186. # compare with json block header
  187. response_header_json = http_get_call(url.hostname, url.port, '/rest/headers/1/'+bb_hash+self.FORMAT_SEPARATOR+"json", True)
  188. assert_equal(response_header_json.status, 200)
  189. response_header_json_str = response_header_json.read().decode('utf-8')
  190. json_obj = json.loads(response_header_json_str, parse_float=Decimal)
  191. assert_equal(len(json_obj), 1) #ensure that there is one header in the json response
  192. assert_equal(json_obj[0]['hash'], bb_hash) #request/response hash should be the same
  193. #compare with normal RPC block response
  194. rpc_block_json = self.nodes[0].getblock(bb_hash)
  195. assert_equal(json_obj[0]['hash'], rpc_block_json['hash'])
  196. assert_equal(json_obj[0]['confirmations'], rpc_block_json['confirmations'])
  197. assert_equal(json_obj[0]['height'], rpc_block_json['height'])
  198. assert_equal(json_obj[0]['version'], rpc_block_json['version'])
  199. assert_equal(json_obj[0]['merkleroot'], rpc_block_json['merkleroot'])
  200. assert_equal(json_obj[0]['time'], rpc_block_json['time'])
  201. assert_equal(json_obj[0]['nonce'], rpc_block_json['nonce'])
  202. assert_equal(json_obj[0]['bits'], rpc_block_json['bits'])
  203. assert_equal(json_obj[0]['difficulty'], rpc_block_json['difficulty'])
  204. assert_equal(json_obj[0]['chainwork'], rpc_block_json['chainwork'])
  205. assert_equal(json_obj[0]['previousblockhash'], rpc_block_json['previousblockhash'])
  206. #see if we can get 5 headers in one response
  207. self.nodes[1].generate(5)
  208. self.sync_all()
  209. response_header_json = http_get_call(url.hostname, url.port, '/rest/headers/5/'+bb_hash+self.FORMAT_SEPARATOR+"json", True)
  210. assert_equal(response_header_json.status, 200)
  211. response_header_json_str = response_header_json.read().decode('utf-8')
  212. json_obj = json.loads(response_header_json_str)
  213. assert_equal(len(json_obj), 5) #now we should have 5 header objects
  214. # do tx test
  215. tx_hash = block_json_obj['tx'][0]['txid']
  216. json_string = http_get_call(url.hostname, url.port, '/rest/tx/'+tx_hash+self.FORMAT_SEPARATOR+"json")
  217. json_obj = json.loads(json_string)
  218. assert_equal(json_obj['txid'], tx_hash)
  219. # check hex format response
  220. hex_string = http_get_call(url.hostname, url.port, '/rest/tx/'+tx_hash+self.FORMAT_SEPARATOR+"hex", True)
  221. assert_equal(hex_string.status, 200)
  222. assert_greater_than(int(response.getheader('content-length')), 10)
  223. # check block tx details
  224. # let's make 3 tx and mine them on node 1
  225. txs = []
  226. txs.append(self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 11))
  227. txs.append(self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 11))
  228. txs.append(self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(), 11))
  229. self.sync_all()
  230. # check that there are exactly 3 transactions in the TX memory pool before generating the block
  231. json_string = http_get_call(url.hostname, url.port, '/rest/mempool/info'+self.FORMAT_SEPARATOR+'json')
  232. json_obj = json.loads(json_string)
  233. assert_equal(json_obj['size'], 3)
  234. # the size of the memory pool should be greater than 3x ~100 bytes
  235. assert_greater_than(json_obj['bytes'], 300)
  236. # check that there are our submitted transactions in the TX memory pool
  237. json_string = http_get_call(url.hostname, url.port, '/rest/mempool/contents'+self.FORMAT_SEPARATOR+'json')
  238. json_obj = json.loads(json_string)
  239. for tx in txs:
  240. assert_equal(tx in json_obj, True)
  241. # now mine the transactions
  242. newblockhash = self.nodes[1].generate(1)
  243. self.sync_all()
  244. #check if the 3 tx show up in the new block
  245. json_string = http_get_call(url.hostname, url.port, '/rest/block/'+newblockhash[0]+self.FORMAT_SEPARATOR+'json')
  246. json_obj = json.loads(json_string)
  247. for tx in json_obj['tx']:
  248. if not 'coinbase' in tx['vin'][0]: #exclude coinbase
  249. assert_equal(tx['txid'] in txs, True)
  250. #check the same but without tx details
  251. json_string = http_get_call(url.hostname, url.port, '/rest/block/notxdetails/'+newblockhash[0]+self.FORMAT_SEPARATOR+'json')
  252. json_obj = json.loads(json_string)
  253. for tx in txs:
  254. assert_equal(tx in json_obj['tx'], True)
  255. #test rest bestblock
  256. bb_hash = self.nodes[0].getbestblockhash()
  257. json_string = http_get_call(url.hostname, url.port, '/rest/chaininfo.json')
  258. json_obj = json.loads(json_string)
  259. assert_equal(json_obj['bestblockhash'], bb_hash)
  260. if __name__ == '__main__':
  261. RESTTest ().main ()