Inside Bitcoin
Opening the selected file…
Inside Bitcoin
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1#!/usr/bin/env python32# Copyright (c) 2014-present The Bitcoin Core developers3# Distributed under the MIT software license, see the accompanying4# file COPYING or http://www.opensource.org/licenses/mit-license.php.5"""Test the REST API."""7from decimal import Decimal8from enum import Enum9from io import BytesIO10import http.client11import json12import typing13import urllib.parse16from test_framework.messages import (17BLOCK_HEADER_SIZE,18COIN,19deser_block_spent_outputs,20)21from test_framework.test_framework import BitcoinTestFramework22from test_framework.util import (23assert_equal,24assert_greater_than,25assert_greater_than_or_equal,26assert_not_equal,27sync_txindex,28)29from test_framework.wallet import (30MiniWallet,31getnewdestination,32)35INVALID_PARAM = "abc"36UNKNOWN_PARAM = "0000000000000000000000000000000000000000000000000000000000000000"39class ReqType(Enum):40JSON = 141BIN = 242HEX = 344class RetType(Enum):45OBJ = 146BYTES = 247JSON = 349def filter_output_indices_by_value(vouts, value):50for vout in vouts:51if vout['value'] == value:52yield vout['n']54class RESTTest (BitcoinTestFramework):55def set_test_params(self):56self.num_nodes = 257self.extra_args = [["-rest", "-blockfilterindex=1", "-txindex"], []]58# whitelist peers to speed up tx relay / mempool sync59self.noban_tx_relay = True61def test_rest_request(62self,63uri: str,64http_method: str = 'GET',65req_type: typing.Optional[ReqType] = ReqType.JSON,66body: str = '',67status: int = 200,68ret_type: RetType = RetType.JSON,69query_params: typing.Union[dict[str, typing.Any], str, None] = None,70) -> typing.Union[http.client.HTTPResponse, bytes, str, None]:71rest_uri = '/rest' + uri72if isinstance(req_type, ReqType):73rest_uri += f'.{req_type.name.lower()}'74if query_params:75if isinstance(query_params, str):76rest_uri += f'?{query_params}'77else:78rest_uri += f'?{urllib.parse.urlencode(query_params)}'80conn = http.client.HTTPConnection(self.url.hostname, self.url.port)81self.log.debug(f'{http_method} {rest_uri} {body}')82if http_method == 'GET':83conn.request('GET', rest_uri)84elif http_method == 'POST':85conn.request('POST', rest_uri, body)86resp = conn.getresponse()88assert resp.status == status, f"Expected: {status}, Got: {resp.status} ({resp.reason}) - Response: {str(resp.read())}"90if ret_type == RetType.OBJ:91return resp92elif ret_type == RetType.BYTES:93return resp.read()94elif ret_type == RetType.JSON:95return json.loads(resp.read().decode('utf-8'), parse_float=Decimal)97return None99def run_test(self):100self.url = urllib.parse.urlparse(self.nodes[0].url)101self.wallet = MiniWallet(self.nodes[0])103self.log.info("Broadcast test transaction and sync nodes")104txid = self.wallet.send_to(from_node=self.nodes[0], scriptPubKey=getnewdestination()[1], amount=int(0.1 * COIN))["txid"]105self.sync_all()107self.log.info("Test the /tx URI")109json_obj = self.test_rest_request(f"/tx/{txid}")110assert_equal(json_obj['txid'], txid)112# Check hex format response113hex_response = self.test_rest_request(f"/tx/{txid}", req_type=ReqType.HEX, ret_type=RetType.OBJ)114assert_greater_than_or_equal(int(hex_response.getheader('content-length')),115json_obj['size']*2)117spent = (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 outpoint119n, = filter_output_indices_by_value(json_obj['vout'], Decimal('0.1'))120spending = (txid, n)122# Test /tx with an invalid and an unknown txid123resp = self.test_rest_request(uri=f"/tx/{INVALID_PARAM}", ret_type=RetType.OBJ, status=400)124assert_equal(resp.read().decode('utf-8').rstrip(), f"Invalid hash: {INVALID_PARAM}")125resp = self.test_rest_request(uri=f"/tx/{UNKNOWN_PARAM}", ret_type=RetType.OBJ, status=404)126assert_equal(resp.read().decode('utf-8').rstrip(), f"{UNKNOWN_PARAM} not found")128self.log.info("Query an unspent TXO using the /getutxos URI")130self.generate(self.wallet, 1)131bb_hash = self.nodes[0].getbestblockhash()133# Check chainTip response134json_obj = self.test_rest_request(f"/getutxos/{spending[0]}-{spending[1]}")135assert_equal(json_obj['chaintipHash'], bb_hash)137# Make sure there is one utxo138assert_equal(len(json_obj['utxos']), 1)139assert_equal(json_obj['utxos'][0]['value'], Decimal('0.1'))141self.log.info("Query a spent TXO using the /getutxos URI")143json_obj = self.test_rest_request(f"/getutxos/{spent[0]}-{spent[1]}")145# Check chainTip response146assert_equal(json_obj['chaintipHash'], bb_hash)148# Make sure there is no utxo in the response because this outpoint has been spent149assert_equal(len(json_obj['utxos']), 0)151# Check bitmap152assert_equal(json_obj['bitmap'], "0")154self.log.info("Query two TXOs using the /getutxos URI")156json_obj = self.test_rest_request(f"/getutxos/{spending[0]}-{spending[1]}/{spent[0]}-{spent[1]}")158assert_equal(len(json_obj['utxos']), 1)159assert_equal(json_obj['bitmap'], "10")161self.log.info("Query the TXOs using the /getutxos URI with a binary response")163bin_request = b'\x01\x02'164for txid, n in [spending, spent]:165bin_request += bytes.fromhex(txid)166bin_request += n.to_bytes(4, 'little')168bin_response = self.test_rest_request("/getutxos", http_method='POST', req_type=ReqType.BIN, body=bin_request, ret_type=RetType.BYTES)169chain_height = int.from_bytes(bin_response[0:4], 'little')170response_hash = bin_response[4:36][::-1].hex()172assert_equal(bb_hash, response_hash) # check if getutxo's chaintip during calculation was fine173assert_equal(chain_height, 201) # chain height must be 201 (pre-mined chain [200] + generated block [1])175self.log.info("Test the /getutxos URI with and without /checkmempool")176# Create a transaction, check that it's found with /checkmempool, but177# not found without. Then confirm the transaction and check that it's178# found with or without /checkmempool.180# do a tx and don't sync181txid = self.wallet.send_to(from_node=self.nodes[0], scriptPubKey=getnewdestination()[1], amount=int(0.1 * COIN))["txid"]182json_obj = self.test_rest_request(f"/tx/{txid}")183# get the spent output to later check for utxo (should be spent by then)184spent = (json_obj['vin'][0]['txid'], json_obj['vin'][0]['vout'])185# get n of 0.1 outpoint186n, = filter_output_indices_by_value(json_obj['vout'], Decimal('0.1'))187spending = (txid, n)189json_obj = self.test_rest_request(f"/getutxos/{spending[0]}-{spending[1]}")190assert_equal(len(json_obj['utxos']), 0)192json_obj = self.test_rest_request(f"/getutxos/checkmempool/{spending[0]}-{spending[1]}")193assert_equal(len(json_obj['utxos']), 1)195json_obj = self.test_rest_request(f"/getutxos/{spent[0]}-{spent[1]}")196assert_equal(len(json_obj['utxos']), 1)198json_obj = self.test_rest_request(f"/getutxos/checkmempool/{spent[0]}-{spent[1]}")199assert_equal(len(json_obj['utxos']), 0)201self.generate(self.nodes[0], 1)203json_obj = self.test_rest_request(f"/getutxos/{spending[0]}-{spending[1]}")204assert_equal(len(json_obj['utxos']), 1)206json_obj = self.test_rest_request(f"/getutxos/checkmempool/{spending[0]}-{spending[1]}")207assert_equal(len(json_obj['utxos']), 1)209self.log.info("Check some invalid requests")210self.test_rest_request("/getutxos", http_method='POST', req_type=ReqType.JSON, body='{"checkmempool', status=400, ret_type=RetType.OBJ)211self.test_rest_request("/getutxos", http_method='POST', req_type=ReqType.BIN, body='{"checkmempool', status=400, ret_type=RetType.OBJ)212self.test_rest_request("/getutxos/checkmempool", http_method='POST', req_type=ReqType.JSON, status=400, ret_type=RetType.OBJ)213self.test_rest_request(f"/getutxos/{spending[0]}_+1", ret_type=RetType.OBJ, status=400)214self.test_rest_request(f"/getutxos/{spending[0]}-+1", ret_type=RetType.OBJ, status=400)215self.test_rest_request(f"/getutxos/{spending[0]}--1", ret_type=RetType.OBJ, status=400)216self.test_rest_request(f"/getutxos/{spending[0]}aa-1234", ret_type=RetType.OBJ, status=400)217self.test_rest_request("/getutxos/aa-1234", ret_type=RetType.OBJ, status=400)219# Test limits220long_uri = '/'.join([f"{txid}-{n_}" for n_ in range(20)])221self.test_rest_request(f"/getutxos/checkmempool/{long_uri}", http_method='POST', status=400, ret_type=RetType.OBJ)223long_uri = '/'.join([f'{txid}-{n_}' for n_ in range(15)])224self.test_rest_request(f"/getutxos/checkmempool/{long_uri}", http_method='POST', status=200)226self.generate(self.nodes[0], 1) # generate block to not affect upcoming tests228self.log.info("Test the /block, /blockhashbyheight, /headers, and /blockfilterheaders URIs")229bb_hash = self.nodes[0].getbestblockhash()231# Check result if block does not exists232assert_equal(self.test_rest_request(f"/headers/{UNKNOWN_PARAM}", query_params={"count": 1}), [])233self.test_rest_request(f"/block/{UNKNOWN_PARAM}", status=404, ret_type=RetType.OBJ)235# Check result if block is not in the active chain236self.nodes[0].invalidateblock(bb_hash)237assert_equal(self.test_rest_request(f'/headers/{bb_hash}', query_params={'count': 1}), [])238self.test_rest_request(f'/block/{bb_hash}')239self.nodes[0].reconsiderblock(bb_hash)241# Check binary format242response = self.test_rest_request(f"/block/{bb_hash}", req_type=ReqType.BIN, ret_type=RetType.OBJ)243assert_greater_than(int(response.getheader('content-length')), BLOCK_HEADER_SIZE)244response_bytes = response.read()246# Compare with block header247response_header = self.test_rest_request(f"/headers/{bb_hash}", req_type=ReqType.BIN, ret_type=RetType.OBJ, query_params={"count": 1})248assert_equal(int(response_header.getheader('content-length')), BLOCK_HEADER_SIZE)249response_header_bytes = response_header.read()250assert_equal(response_bytes[:BLOCK_HEADER_SIZE], response_header_bytes)
Independent explanations by MyBitcoinExplorer. Not affiliated with or endorsed by Bitcoin Core. Guides are educational and do not replace the source or its tests.
Bitcoin Core source © its contributors, distributed under the MIT license. Original notices and bundled third-party licenses are retained in the source tree.