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#3# linearize-hashes.py: List blocks in a linear, no-fork version of the chain.4#5# Copyright (c) 2013-present The Bitcoin Core developers6# Distributed under the MIT software license, see the accompanying7# file COPYING or http://www.opensource.org/licenses/mit-license.php.8#10from http.client import HTTPConnection11import json12import re13import base6414import sys15import os16import os.path18settings = {}20class BitcoinRPC:21def __init__(self, host, port, username, password):22authpair = "%s:%s" % (username, password)23authpair = authpair.encode('utf-8')24self.authhdr = b"Basic " + base64.b64encode(authpair)25self.conn = HTTPConnection(host, port=port, timeout=30)27def execute(self, obj):28try:29self.conn.request('POST', '/', json.dumps(obj),30{ 'Authorization' : self.authhdr,31'Content-type' : 'application/json' })32except ConnectionRefusedError:33print('RPC connection refused. Check RPC settings and the server status.',34file=sys.stderr)35return None37resp = self.conn.getresponse()38if resp is None:39print("JSON-RPC: no response", file=sys.stderr)40return None42body = resp.read().decode('utf-8')43resp_obj = json.loads(body)44return resp_obj46@staticmethod47def build_request(idx, method, params):48obj = { 'version' : '1.1',49'method' : method,50'id' : idx }51if params is None:52obj['params'] = []53else:54obj['params'] = params55return obj57@staticmethod58def response_is_error(resp_obj):59return 'error' in resp_obj and resp_obj['error'] is not None61def get_block_hashes(settings, max_blocks_per_call=10000):62rpc = BitcoinRPC(settings['host'], settings['port'],63settings['rpcuser'], settings['rpcpassword'])65height = settings['min_height']66while height < settings['max_height']+1:67num_blocks = min(settings['max_height']+1-height, max_blocks_per_call)68batch = []69for x in range(num_blocks):70batch.append(rpc.build_request(x, 'getblockhash', [height + x]))72reply = rpc.execute(batch)73if reply is None:74print('Cannot continue. Program will halt.')75return None77for x,resp_obj in enumerate(reply):78if rpc.response_is_error(resp_obj):79print('JSON-RPC: error at height', height+x, ': ', resp_obj['error'], file=sys.stderr)80sys.exit(1)81assert resp_obj['id'] == x # assume replies are in-sequence82if settings['rev_hash_bytes'] == 'true':83resp_obj['result'] = bytes.fromhex(resp_obj['result'])[::-1].hex()84print(resp_obj['result'])86height += num_blocks88def get_rpc_cookie():89# Open the cookie file90with open(os.path.join(os.path.expanduser(settings['datadir']), '.cookie'), 'r') as f:91combined = f.readline()92combined_split = combined.split(":")93settings['rpcuser'] = combined_split[0]94settings['rpcpassword'] = combined_split[1]96if __name__ == '__main__':97if len(sys.argv) != 2:98print("Usage: linearize-hashes.py CONFIG-FILE")99sys.exit(1)101with open(sys.argv[1]) as f:102for line in f:103# skip comment lines104m = re.search(r'^\s*#', line)105if m:106continue108# parse key=value lines109m = re.search(r'^(\w+)\s*=\s*(\S.*)$', line)110if m is None:111continue112settings[m.group(1)] = m.group(2)114if 'host' not in settings:115settings['host'] = '127.0.0.1'116if 'port' not in settings:117settings['port'] = 8332118if 'min_height' not in settings:119settings['min_height'] = 0120if 'max_height' not in settings:121settings['max_height'] = 313000122if 'rev_hash_bytes' not in settings:123settings['rev_hash_bytes'] = 'false'125use_userpass = True126use_datadir = False127if 'rpcuser' not in settings or 'rpcpassword' not in settings:128use_userpass = False129if 'datadir' in settings and not use_userpass:130use_datadir = True131if not use_userpass and not use_datadir:132print("Missing datadir or username and/or password in cfg file", file=sys.stderr)133sys.exit(1)135settings['port'] = int(settings['port'])136settings['min_height'] = int(settings['min_height'])137settings['max_height'] = int(settings['max_height'])139# Force hash byte format setting to be lowercase to make comparisons easier.140settings['rev_hash_bytes'] = settings['rev_hash_bytes'].lower()142# Get the rpc user and pass from the cookie if the datadir is set143if use_datadir:144get_rpc_cookie()146get_block_hashes(settings)
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.