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) 2022-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"""Helper routines relevant for compact block filters (BIP158).6"""7from .crypto.siphash import siphash10def bip158_basic_element_hash(script_pub_key, N, block_hash):11""" Calculates the ranged hash of a filter element as defined in BIP158:13'The first step in the filter construction is hashing the variable-sized14raw items in the set to the range [0, F), where F = N * M.'16'The items are first passed through the pseudorandom function SipHash, which takes a17128-bit key k and a variable-sized byte vector and produces a uniformly random 64-bit18output. Implementations of this BIP MUST use the SipHash parameters c = 2 and d = 4.'20'The parameter k MUST be set to the first 16 bytes of the hash (in standard21little-endian representation) of the block for which the filter is constructed. This22ensures the key is deterministic while still varying from block to block.'23"""24M = 78493125block_hash_bytes = bytes.fromhex(block_hash)[::-1]26k0 = int.from_bytes(block_hash_bytes[0:8], 'little')27k1 = int.from_bytes(block_hash_bytes[8:16], 'little')28return (siphash(k0, k1, script_pub_key) * (N * M)) >> 6431def bip158_relevant_scriptpubkeys(node, block_hash):32""" Determines the basic filter relevant scriptPubKeys as defined in BIP158:34'A basic filter MUST contain exactly the following items for each transaction in a block:35- The previous output script (the script being spent) for each input, except for36the coinbase transaction.37- The scriptPubKey of each output, aside from all OP_RETURN output scripts.'38"""39spks = set()40for tx in node.getblock(blockhash=block_hash, verbosity=3)['tx']:41# gather prevout scripts42for i in tx['vin']:43if 'prevout' in i:44spks.add(bytes.fromhex(i['prevout']['scriptPubKey']['hex']))45# gather output scripts46for o in tx['vout']:47if o['scriptPubKey']['type'] != 'nulldata':48spks.add(bytes.fromhex(o['scriptPubKey']['hex']))49return spks
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.