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

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