interface_rest.py raw

   1  #!/usr/bin/env python3
   2  # Copyright (c) 2014-2022 The Limenka 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  
   7  from decimal import Decimal
   8  from enum import Enum
   9  from io import BytesIO
  10  import http.client
  11  import json
  12  import typing
  13  import urllib.parse
  14  
  15  
  16  from test_framework.messages import (
  17      BLOCK_HEADER_SIZE,
  18      COIN,
  19      deser_block_spent_outputs,
  20  )
  21  from test_framework.test_framework import LimenkaTestFramework
  22  from test_framework.util import (
  23      assert_equal,
  24      assert_greater_than,
  25      assert_greater_than_or_equal,
  26  )
  27  from test_framework.wallet import (
  28      MiniWallet,
  29      getnewdestination,
  30  )
  31  from typing import Optional
  32  
  33  
  34  INVALID_PARAM = "abc"
  35  UNKNOWN_PARAM = "0000000000000000000000000000000000000000000000000000000000000000"
  36  
  37  
  38  class ReqType(Enum):
  39      JSON = 1
  40      BIN = 2
  41      HEX = 3
  42  
  43  class RetType(Enum):
  44      OBJ = 1
  45      BYTES = 2
  46      JSON = 3
  47  
  48  def filter_output_indices_by_value(vouts, value):
  49      for vout in vouts:
  50          if vout['value'] == value:
  51              yield vout['n']
  52  
  53  class RESTTest (LimenkaTestFramework):
  54      def add_options(self, parser):
  55          self.add_wallet_options(parser)
  56  
  57      def set_test_params(self):
  58          self.num_nodes = 2
  59          self.extra_args = [["-rest", "-blockfilterindex=1"], []]
  60          # whitelist peers to speed up tx relay / mempool sync
  61          self.noban_tx_relay = True
  62          self.supports_cli = False
  63  
  64      def test_rest_request(
  65              self,
  66              uri: str,
  67              http_method: str = 'GET',
  68              req_type: ReqType = ReqType.JSON,
  69              body: str = '',
  70              status: int = 200,
  71              ret_type: RetType = RetType.JSON,
  72              query_params: Optional[dict[str, typing.Any]] = None,
  73              ) -> typing.Union[http.client.HTTPResponse, bytes, str, None]:
  74          rest_uri = '/rest' + uri
  75          if req_type in ReqType:
  76              rest_uri += f'.{req_type.name.lower()}'
  77          if query_params:
  78              rest_uri += f'?{urllib.parse.urlencode(query_params)}'
  79  
  80          conn = http.client.HTTPConnection(self.url.hostname, self.url.port)
  81          self.log.debug(f'{http_method} {rest_uri} {body}')
  82          if http_method == 'GET':
  83              conn.request('GET', rest_uri)
  84          elif http_method == 'POST':
  85              conn.request('POST', rest_uri, body)
  86          resp = conn.getresponse()
  87  
  88          assert_equal(resp.status, status)
  89  
  90          if ret_type == RetType.OBJ:
  91              return resp
  92          elif ret_type == RetType.BYTES:
  93              return resp.read()
  94          elif ret_type == RetType.JSON:
  95              return json.loads(resp.read().decode('utf-8'), parse_float=Decimal)
  96  
  97          return None
  98  
  99      def run_test(self):
 100          self.url = urllib.parse.urlparse(self.nodes[0].url)
 101          self.wallet = MiniWallet(self.nodes[0])
 102  
 103          self.log.info("Broadcast test transaction and sync nodes")
 104          txid = self.wallet.send_to(from_node=self.nodes[0], scriptPubKey=getnewdestination()[1], amount=int(0.1 * COIN))["txid"]
 105          self.sync_all()
 106  
 107          self.log.info("Test the /tx URI")
 108  
 109          json_obj = self.test_rest_request(f"/tx/{txid}")
 110          assert_equal(json_obj['txid'], txid)
 111  
 112          # Check hex format response
 113          hex_response = self.test_rest_request(f"/tx/{txid}", req_type=ReqType.HEX, ret_type=RetType.OBJ)
 114          assert_greater_than_or_equal(int(hex_response.getheader('content-length')),
 115                                       json_obj['size']*2)
 116  
 117          spent = (json_obj['vin'][0]['txid'], json_obj['vin'][0]['vout'])  # get the vin to later check for utxo (should be spent by then)
 118          # get n of 0.1 outpoint
 119          n, = filter_output_indices_by_value(json_obj['vout'], Decimal('0.1'))
 120          spending = (txid, n)
 121  
 122          # Test /tx with an invalid and an unknown txid
 123          resp = self.test_rest_request(uri=f"/tx/{INVALID_PARAM}", ret_type=RetType.OBJ, status=400)
 124          assert_equal(resp.read().decode('utf-8').rstrip(), f"Invalid hash: {INVALID_PARAM}")
 125          resp = self.test_rest_request(uri=f"/tx/{UNKNOWN_PARAM}", ret_type=RetType.OBJ, status=404)
 126          assert_equal(resp.read().decode('utf-8').rstrip(), f"{UNKNOWN_PARAM} not found")
 127  
 128          self.log.info("Query an unspent TXO using the /getutxos URI")
 129  
 130          self.generate(self.wallet, 1)
 131          bb_hash = self.nodes[0].getbestblockhash()
 132  
 133          # Check chainTip response
 134          json_obj = self.test_rest_request(f"/getutxos/{spending[0]}-{spending[1]}")
 135          assert_equal(json_obj['chaintipHash'], bb_hash)
 136  
 137          # Make sure there is one utxo
 138          assert_equal(len(json_obj['utxos']), 1)
 139          assert_equal(json_obj['utxos'][0]['value'], Decimal('0.1'))
 140  
 141          self.log.info("Query a spent TXO using the /getutxos URI")
 142  
 143          json_obj = self.test_rest_request(f"/getutxos/{spent[0]}-{spent[1]}")
 144  
 145          # Check chainTip response
 146          assert_equal(json_obj['chaintipHash'], bb_hash)
 147  
 148          # Make sure there is no utxo in the response because this outpoint has been spent
 149          assert_equal(len(json_obj['utxos']), 0)
 150  
 151          # Check bitmap
 152          assert_equal(json_obj['bitmap'], "0")
 153  
 154          self.log.info("Query two TXOs using the /getutxos URI")
 155  
 156          json_obj = self.test_rest_request(f"/getutxos/{spending[0]}-{spending[1]}/{spent[0]}-{spent[1]}")
 157  
 158          assert_equal(len(json_obj['utxos']), 1)
 159          assert_equal(json_obj['bitmap'], "10")
 160  
 161          self.log.info("Query the TXOs using the /getutxos URI with a binary response")
 162  
 163          bin_request = b'\x01\x02'
 164          for txid, n in [spending, spent]:
 165              bin_request += bytes.fromhex(txid)
 166              bin_request += n.to_bytes(4, 'little')
 167  
 168          bin_response = self.test_rest_request("/getutxos", http_method='POST', req_type=ReqType.BIN, body=bin_request, ret_type=RetType.BYTES)
 169          chain_height = int.from_bytes(bin_response[0:4], 'little')
 170          response_hash = bin_response[4:36][::-1].hex()
 171  
 172          assert_equal(bb_hash, response_hash)  # check if getutxo's chaintip during calculation was fine
 173          assert_equal(chain_height, 201)  # chain height must be 201 (pre-mined chain [200] + generated block [1])
 174  
 175          self.log.info("Test the /getutxos URI with and without /checkmempool")
 176          # Create a transaction, check that it's found with /checkmempool, but
 177          # not found without. Then confirm the transaction and check that it's
 178          # found with or without /checkmempool.
 179  
 180          # do a tx and don't sync
 181          txid = self.wallet.send_to(from_node=self.nodes[0], scriptPubKey=getnewdestination()[1], amount=int(0.1 * COIN))["txid"]
 182          json_obj = self.test_rest_request(f"/tx/{txid}")
 183          # get the spent output to later check for utxo (should be spent by then)
 184          spent = (json_obj['vin'][0]['txid'], json_obj['vin'][0]['vout'])
 185          # get n of 0.1 outpoint
 186          n, = filter_output_indices_by_value(json_obj['vout'], Decimal('0.1'))
 187          spending = (txid, n)
 188  
 189          json_obj = self.test_rest_request(f"/getutxos/{spending[0]}-{spending[1]}")
 190          assert_equal(len(json_obj['utxos']), 0)
 191  
 192          json_obj = self.test_rest_request(f"/getutxos/checkmempool/{spending[0]}-{spending[1]}")
 193          assert_equal(len(json_obj['utxos']), 1)
 194  
 195          json_obj = self.test_rest_request(f"/getutxos/{spent[0]}-{spent[1]}")
 196          assert_equal(len(json_obj['utxos']), 1)
 197  
 198          json_obj = self.test_rest_request(f"/getutxos/checkmempool/{spent[0]}-{spent[1]}")
 199          assert_equal(len(json_obj['utxos']), 0)
 200  
 201          self.generate(self.nodes[0], 1)
 202  
 203          json_obj = self.test_rest_request(f"/getutxos/{spending[0]}-{spending[1]}")
 204          assert_equal(len(json_obj['utxos']), 1)
 205  
 206          json_obj = self.test_rest_request(f"/getutxos/checkmempool/{spending[0]}-{spending[1]}")
 207          assert_equal(len(json_obj['utxos']), 1)
 208  
 209          self.log.info("Check some invalid requests")
 210          self.test_rest_request("/getutxos", http_method='POST', req_type=ReqType.JSON, body='{"checkmempool', status=400, ret_type=RetType.OBJ)
 211          self.test_rest_request("/getutxos", http_method='POST', req_type=ReqType.BIN, body='{"checkmempool', status=400, ret_type=RetType.OBJ)
 212          self.test_rest_request("/getutxos/checkmempool", http_method='POST', req_type=ReqType.JSON, status=400, ret_type=RetType.OBJ)
 213          self.test_rest_request(f"/getutxos/{spending[0]}_+1", ret_type=RetType.OBJ, status=400)
 214          self.test_rest_request(f"/getutxos/{spending[0]}-+1", ret_type=RetType.OBJ, status=400)
 215          self.test_rest_request(f"/getutxos/{spending[0]}--1", ret_type=RetType.OBJ, status=400)
 216          self.test_rest_request(f"/getutxos/{spending[0]}aa-1234", ret_type=RetType.OBJ, status=400)
 217          self.test_rest_request("/getutxos/aa-1234", ret_type=RetType.OBJ, status=400)
 218  
 219          # Test limits
 220          long_uri = '/'.join([f"{txid}-{n_}" for n_ in range(20)])
 221          self.test_rest_request(f"/getutxos/checkmempool/{long_uri}", http_method='POST', status=400, ret_type=RetType.OBJ)
 222  
 223          long_uri = '/'.join([f'{txid}-{n_}' for n_ in range(15)])
 224          self.test_rest_request(f"/getutxos/checkmempool/{long_uri}", http_method='POST', status=200)
 225  
 226          self.generate(self.nodes[0], 1)  # generate block to not affect upcoming tests
 227  
 228          self.log.info("Test the /block, /blockhashbyheight, /headers, and /blockfilterheaders URIs")
 229          bb_hash = self.nodes[0].getbestblockhash()
 230  
 231          # Check result if block does not exists
 232          assert_equal(self.test_rest_request(f"/headers/{UNKNOWN_PARAM}", query_params={"count": 1}), [])
 233          self.test_rest_request(f"/block/{UNKNOWN_PARAM}", status=404, ret_type=RetType.OBJ)
 234  
 235          # Check result if block is not in the active chain
 236          self.nodes[0].invalidateblock(bb_hash)
 237          assert_equal(self.test_rest_request(f'/headers/{bb_hash}', query_params={'count': 1}), [])
 238          self.test_rest_request(f'/block/{bb_hash}')
 239          self.nodes[0].reconsiderblock(bb_hash)
 240  
 241          # Check binary format
 242          response = self.test_rest_request(f"/block/{bb_hash}", req_type=ReqType.BIN, ret_type=RetType.OBJ)
 243          assert_greater_than(int(response.getheader('content-length')), BLOCK_HEADER_SIZE)
 244          response_bytes = response.read()
 245  
 246          # Compare with block header
 247          response_header = self.test_rest_request(f"/headers/{bb_hash}", req_type=ReqType.BIN, ret_type=RetType.OBJ, query_params={"count": 1})
 248          assert_equal(int(response_header.getheader('content-length')), BLOCK_HEADER_SIZE)
 249          response_header_bytes = response_header.read()
 250          assert_equal(response_bytes[:BLOCK_HEADER_SIZE], response_header_bytes)
 251  
 252          # Check block hex format
 253          response_hex = self.test_rest_request(f"/block/{bb_hash}", req_type=ReqType.HEX, ret_type=RetType.OBJ)
 254          assert_greater_than(int(response_hex.getheader('content-length')), BLOCK_HEADER_SIZE*2)
 255          response_hex_bytes = response_hex.read().strip(b'\n')
 256          assert_equal(response_bytes.hex().encode(), response_hex_bytes)
 257  
 258          # Compare with hex block header
 259          response_header_hex = self.test_rest_request(f"/headers/{bb_hash}", req_type=ReqType.HEX, ret_type=RetType.OBJ, query_params={"count": 1})
 260          assert_greater_than(int(response_header_hex.getheader('content-length')), BLOCK_HEADER_SIZE*2)
 261          response_header_hex_bytes = response_header_hex.read(BLOCK_HEADER_SIZE*2)
 262          assert_equal(response_bytes[:BLOCK_HEADER_SIZE].hex().encode(), response_header_hex_bytes)
 263  
 264          # Check json format
 265          block_json_obj = self.test_rest_request(f"/block/{bb_hash}")
 266          assert_equal(block_json_obj['hash'], bb_hash)
 267          assert_equal(self.test_rest_request(f"/blockhashbyheight/{block_json_obj['height']}")['blockhash'], bb_hash)
 268  
 269          # Check hex/bin format
 270          resp_hex = self.test_rest_request(f"/blockhashbyheight/{block_json_obj['height']}", req_type=ReqType.HEX, ret_type=RetType.OBJ)
 271          assert_equal(resp_hex.read().decode('utf-8').rstrip(), bb_hash)
 272          resp_bytes = self.test_rest_request(f"/blockhashbyheight/{block_json_obj['height']}", req_type=ReqType.BIN, ret_type=RetType.BYTES)
 273          blockhash = resp_bytes[::-1].hex()
 274          assert_equal(blockhash, bb_hash)
 275  
 276          # Check invalid blockhashbyheight requests
 277          resp = self.test_rest_request(f"/blockhashbyheight/{INVALID_PARAM}", ret_type=RetType.OBJ, status=400)
 278          assert_equal(resp.read().decode('utf-8').rstrip(), f"Invalid height: {INVALID_PARAM}")
 279          resp = self.test_rest_request("/blockhashbyheight/1000000", ret_type=RetType.OBJ, status=404)
 280          assert_equal(resp.read().decode('utf-8').rstrip(), "Block height out of range")
 281          resp = self.test_rest_request("/blockhashbyheight/-1", ret_type=RetType.OBJ, status=400)
 282          assert_equal(resp.read().decode('utf-8').rstrip(), "Invalid height: -1")
 283          self.test_rest_request("/blockhashbyheight/", ret_type=RetType.OBJ, status=400)
 284  
 285          # Compare with json block header
 286          json_obj = self.test_rest_request(f"/headers/{bb_hash}", query_params={"count": 1})
 287          assert_equal(len(json_obj), 1)  # ensure that there is one header in the json response
 288          assert_equal(json_obj[0]['hash'], bb_hash)  # request/response hash should be the same
 289  
 290          # Check invalid uri (% symbol at the end of the request)
 291          for invalid_uri in [f"/headers/{bb_hash}%", f"/blockfilterheaders/basic/{bb_hash}%", "/mempool/contents.json?%"]:
 292              resp = self.test_rest_request(invalid_uri, ret_type=RetType.OBJ, status=400)
 293              assert_equal(resp.read().decode('utf-8').rstrip(), "URI parsing failed, it likely contained RFC 3986 invalid characters")
 294  
 295          # Compare with normal RPC block response
 296          rpc_block_json = self.nodes[0].getblock(bb_hash)
 297          for key in ['hash', 'confirmations', 'height', 'version', 'merkleroot', 'time', 'nonce', 'bits', 'target', 'difficulty', 'chainwork', 'previousblockhash']:
 298              assert_equal(json_obj[0][key], rpc_block_json[key])
 299  
 300          # See if we can get 5 headers in one response
 301          self.generate(self.nodes[1], 5)
 302          expected_filter = {
 303              'basic block filter index': {'synced': True, 'best_block_height': 208},
 304          }
 305          self.wait_until(lambda: self.nodes[0].getindexinfo() == expected_filter)
 306          json_obj = self.test_rest_request(f"/headers/{bb_hash}", query_params={"count": 5})
 307          assert_equal(len(json_obj), 5)  # now we should have 5 header objects
 308          json_obj = self.test_rest_request(f"/blockfilterheaders/basic/{bb_hash}", query_params={"count": 5})
 309          first_filter_header = json_obj[0]
 310          assert_equal(len(json_obj), 5)  # now we should have 5 filter header objects
 311          json_obj = self.test_rest_request(f"/blockfilter/basic/{bb_hash}")
 312  
 313          # Compare with normal RPC blockfilter response
 314          rpc_blockfilter = self.nodes[0].getblockfilter(bb_hash)
 315          assert_equal(first_filter_header, rpc_blockfilter['header'])
 316          assert_equal(json_obj['filter'], rpc_blockfilter['filter'])
 317  
 318          # Test blockfilterheaders with an invalid hash and filtertype
 319          resp = self.test_rest_request(f"/blockfilterheaders/{INVALID_PARAM}/{bb_hash}", ret_type=RetType.OBJ, status=400)
 320          assert_equal(resp.read().decode('utf-8').rstrip(), f"Unknown filtertype {INVALID_PARAM}")
 321          resp = self.test_rest_request(f"/blockfilterheaders/basic/{INVALID_PARAM}", ret_type=RetType.OBJ, status=400)
 322          assert_equal(resp.read().decode('utf-8').rstrip(), f"Invalid hash: {INVALID_PARAM}")
 323  
 324          # Test number parsing
 325          for num in ['5a', '-5', '0', '2001', '99999999999999999999999999999999999']:
 326              assert_equal(
 327                  bytes(f'Header count is invalid or out of acceptable range (1-2000): {num}\r\n', 'ascii'),
 328                  self.test_rest_request(f"/headers/{bb_hash}", ret_type=RetType.BYTES, status=400, query_params={"count": num}),
 329              )
 330  
 331          self.log.info("Test tx inclusion in the /mempool and /block URIs")
 332  
 333          # Make 3 chained txs and mine them on node 1
 334          txs = []
 335          input_txid = txid
 336          for _ in range(3):
 337              utxo_to_spend = self.wallet.get_utxo(txid=input_txid)
 338              txs.append(self.wallet.send_self_transfer(from_node=self.nodes[0], utxo_to_spend=utxo_to_spend)['txid'])
 339              input_txid = txs[-1]
 340          self.sync_all()
 341  
 342          # Check that there are exactly 3 transactions in the TX memory pool before generating the block
 343          json_obj = self.test_rest_request("/mempool/info")
 344          assert_equal(json_obj['size'], 3)
 345          # the size of the memory pool should be greater than 3x ~100 bytes
 346          assert_greater_than(json_obj['bytes'], 300)
 347  
 348          mempool_info = self.nodes[0].getmempoolinfo()
 349          # pop unstable unbroadcastcount before check
 350          for obj in [json_obj, mempool_info]:
 351              obj.pop("unbroadcastcount")
 352          assert_equal(json_obj, mempool_info)
 353          json_obj = self.test_rest_request("/mempool/info/with_fee_histogram")
 354          mempool_info = self.nodes[0].getmempoolinfo(with_fee_histogram=True)
 355          assert_equal(json_obj, mempool_info)
 356  
 357          # Check that there are our submitted transactions in the TX memory pool
 358          json_obj = self.test_rest_request("/mempool/contents")
 359          raw_mempool_verbose = self.nodes[0].getrawmempool(verbose=True)
 360  
 361          assert_equal(json_obj, raw_mempool_verbose)
 362  
 363          for i, tx in enumerate(txs):
 364              assert tx in json_obj
 365              assert_equal(json_obj[tx]['spentby'], txs[i + 1:i + 2])
 366              assert_equal(json_obj[tx]['depends'], txs[i - 1:i])
 367  
 368          # Check the mempool response for explicit parameters
 369          json_obj = self.test_rest_request("/mempool/contents", query_params={"verbose": "true", "mempool_sequence": "false"})
 370          assert_equal(json_obj, raw_mempool_verbose)
 371  
 372          # Check the mempool response for not verbose
 373          json_obj = self.test_rest_request("/mempool/contents", query_params={"verbose": "false"})
 374          raw_mempool = self.nodes[0].getrawmempool(verbose=False)
 375  
 376          assert_equal(json_obj, raw_mempool)
 377  
 378          # Check the mempool response for sequence
 379          json_obj = self.test_rest_request("/mempool/contents", query_params={"verbose": "false", "mempool_sequence": "true"})
 380          raw_mempool = self.nodes[0].getrawmempool(verbose=False, mempool_sequence=True)
 381  
 382          assert_equal(json_obj, raw_mempool)
 383  
 384          # Check for error response if verbose=true and mempool_sequence=true
 385          resp = self.test_rest_request("/mempool/contents", ret_type=RetType.OBJ, status=400, query_params={"verbose": "true", "mempool_sequence": "true"})
 386          assert_equal(resp.read().decode('utf-8').strip(), 'Verbose results cannot contain mempool sequence values. (hint: set "verbose=false")')
 387  
 388          # Check for error response if verbose is not "true" or "false"
 389          resp = self.test_rest_request("/mempool/contents", ret_type=RetType.OBJ, status=400, query_params={"verbose": "TRUE"})
 390          assert_equal(resp.read().decode('utf-8').strip(), 'The "verbose" query parameter must be either "true" or "false".')
 391  
 392          # Check for error response if mempool_sequence is not "true" or "false"
 393          resp = self.test_rest_request("/mempool/contents", ret_type=RetType.OBJ, status=400, query_params={"verbose": "false", "mempool_sequence": "TRUE"})
 394          assert_equal(resp.read().decode('utf-8').strip(), 'The "mempool_sequence" query parameter must be either "true" or "false".')
 395  
 396          # Now mine the transactions
 397          newblockhash = self.generate(self.nodes[1], 1)
 398  
 399          # Check if the 3 tx show up in the new block
 400          json_obj = self.test_rest_request(f"/block/{newblockhash[0]}")
 401          non_coinbase_txs = {tx['txid'] for tx in json_obj['tx']
 402                              if 'coinbase' not in tx['vin'][0]}
 403          assert_equal(non_coinbase_txs, set(txs))
 404  
 405          # Verify that the non-coinbase tx has "prevout" key set
 406          for tx_obj in json_obj["tx"]:
 407              for vin in tx_obj["vin"]:
 408                  if "coinbase" not in vin:
 409                      assert "prevout" in vin
 410                      assert_equal(vin["prevout"]["generated"], False)
 411                  else:
 412                      assert "prevout" not in vin
 413  
 414          # Check the same but without tx details
 415          json_obj = self.test_rest_request(f"/block/notxdetails/{newblockhash[0]}")
 416          for tx in txs:
 417              assert tx in json_obj['tx']
 418  
 419          self.log.info("Test the /chaininfo URI")
 420  
 421          bb_hash = self.nodes[0].getbestblockhash()
 422  
 423          json_obj = self.test_rest_request("/chaininfo")
 424          assert_equal(json_obj['bestblockhash'], bb_hash)
 425  
 426          # Compare with normal RPC getblockchaininfo response
 427          blockchain_info = self.nodes[0].getblockchaininfo()
 428          assert_equal(blockchain_info, json_obj)
 429  
 430          # Test compatibility of deprecated and newer endpoints
 431          self.log.info("Test compatibility of deprecated and newer endpoints")
 432          assert_equal(self.test_rest_request(f"/headers/{bb_hash}", query_params={"count": 1}), self.test_rest_request(f"/headers/1/{bb_hash}"))
 433          assert_equal(self.test_rest_request(f"/blockfilterheaders/basic/{bb_hash}", query_params={"count": 1}), self.test_rest_request(f"/blockfilterheaders/basic/5/{bb_hash}"))
 434  
 435          self.log.info("Test the /spenttxouts URI")
 436  
 437          block_count = self.nodes[0].getblockcount()
 438          for height in range(0, block_count + 1):
 439              blockhash = self.nodes[0].getblockhash(height)
 440              spent_bin = self.test_rest_request(f"/spenttxouts/{blockhash}", req_type=ReqType.BIN, ret_type=RetType.BYTES)
 441              spent_hex = self.test_rest_request(f"/spenttxouts/{blockhash}", req_type=ReqType.HEX, ret_type=RetType.BYTES)
 442              spent_json = self.test_rest_request(f"/spenttxouts/{blockhash}", req_type=ReqType.JSON, ret_type=RetType.JSON)
 443  
 444              assert_equal(bytes.fromhex(spent_hex.decode()), spent_bin)
 445  
 446              spent = deser_block_spent_outputs(BytesIO(spent_bin))
 447              block = self.nodes[0].getblock(blockhash, 3)  # return prevout for each input
 448              assert_equal(len(spent), len(block["tx"]))
 449              assert_equal(len(spent_json), len(block["tx"]))
 450  
 451              for i, tx in enumerate(block["tx"]):
 452                  prevouts = [txin["prevout"] for txin in tx["vin"] if "coinbase" not in txin]
 453                  # compare with `getblock` JSON output (coinbase tx has no prevouts)
 454                  actual = [(txout.scriptPubKey.hex(), Decimal(txout.nValue) / COIN) for txout in spent[i]]
 455                  expected = [(p["scriptPubKey"]["hex"], p["value"]) for p in prevouts]
 456                  assert_equal(expected, actual)
 457                  # also compare JSON format
 458                  actual = [(prevout["scriptPubKey"], prevout["value"]) for prevout in spent_json[i]]
 459                  expected = [(p["scriptPubKey"], p["value"]) for p in prevouts]
 460                  assert_equal(expected, actual)
 461  
 462  
 463          self.log.info("Test the /deploymentinfo URI")
 464  
 465          deployment_info = self.nodes[0].getdeploymentinfo()
 466          assert_equal(deployment_info, self.test_rest_request('/deploymentinfo'))
 467  
 468          previous_bb_hash = self.nodes[0].getblockhash(self.nodes[0].getblockcount() - 1)
 469          deployment_info = self.nodes[0].getdeploymentinfo(previous_bb_hash)
 470          assert_equal(deployment_info, self.test_rest_request(f"/deploymentinfo/{previous_bb_hash}"))
 471  
 472          non_existing_blockhash = '42759cde25462784395a337460bde75f58e73d3f08bd31fdc3507cbac856a2c4'
 473          resp = self.test_rest_request(f'/deploymentinfo/{non_existing_blockhash}', ret_type=RetType.OBJ, status=400)
 474          assert_equal(resp.read().decode('utf-8').rstrip(), "Block not found")
 475  
 476          resp = self.test_rest_request(f"/deploymentinfo/{INVALID_PARAM}", ret_type=RetType.OBJ, status=400)
 477          assert_equal(resp.read().decode('utf-8').rstrip(), f"Invalid hash: {INVALID_PARAM}")
 478  
 479          if self.is_wallet_compiled():
 480              self.import_deterministic_coinbase_privkeys()
 481  
 482              # Random address so node1's balance doesn't increase
 483              not_related_address = "2MxqoHEdNQTyYeX1mHcbrrpzgojbosTpCvJ"
 484  
 485              # Prepare for Fee estimation
 486              for i in range(18):
 487                  self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 0.1)
 488                  self.sync_all()
 489                  self.generatetoaddress(self.nodes[1], 1, not_related_address)
 490              self.sync_all()
 491  
 492              json_obj = self.test_rest_request("/fee/conservative/1")
 493              assert_greater_than(float(json_obj["feerate"]), 0)
 494              assert_greater_than(int(json_obj["blocks"]), 0)
 495  
 496  
 497  if __name__ == '__main__':
 498      RESTTest(__file__).main()
 499