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# Copyright (c) 2020 Pieter Wuille2# Distributed under the MIT software license, see the accompanying3# file COPYING or http://www.opensource.org/licenses/mit-license.php.4"""Native Python MuHash3072 implementation."""6import hashlib7import unittest9from .chacha20 import chacha20_block11def data_to_num3072(data):12"""Hash a 32-byte array data to a 3072-bit number using 6 Chacha20 operations."""13bytes384 = b""14for counter in range(6):15bytes384 += chacha20_block(data, bytes(12), counter)16return int.from_bytes(bytes384, 'little')18class MuHash3072:19"""Class representing the MuHash3072 computation of a set.21See https://cseweb.ucsd.edu/~mihir/papers/inchash.pdf and https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2017-May/014337.html22"""24MODULUS = 2**3072 - 110371726def __init__(self):27"""Initialize for an empty set."""28self.numerator = 129self.denominator = 131def insert(self, data):32"""Insert a byte array data in the set."""33data_hash = hashlib.sha256(data).digest()34self.numerator = (self.numerator * data_to_num3072(data_hash)) % self.MODULUS36def remove(self, data):37"""Remove a byte array from the set."""38data_hash = hashlib.sha256(data).digest()39self.denominator = (self.denominator * data_to_num3072(data_hash)) % self.MODULUS41def digest(self):42"""Extract the final hash. Does not modify this object."""43val = (self.numerator * pow(self.denominator, -1, self.MODULUS)) % self.MODULUS44bytes384 = val.to_bytes(384, 'little')45return hashlib.sha256(bytes384).digest()47class TestFrameworkMuhash(unittest.TestCase):48def test_muhash(self):49muhash = MuHash3072()50muhash.insert(b'\x00' * 32)51muhash.insert((b'\x01' + b'\x00' * 31))52muhash.remove((b'\x02' + b'\x00' * 31))53finalized = muhash.digest()54# This mirrors the result in the C++ MuHash3072 unit test55self.assertEqual(finalized[::-1].hex(), "10d312b100cbd32ada024a6646e40d3482fcff103668d2625f10002a607d5863")
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.