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) 2016-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"""SipHash-2-4 implementation.7This implements SipHash-2-4. For convenience, an interface taking 256-bit8integers is provided in addition to the one accepting generic data.9"""11import json12from pathlib import Path13import unittest16def rotl64(n, b):17return n >> (64 - b) | (n & ((1 << (64 - b)) - 1)) << b20def siphash_round(v0, v1, v2, v3):21v0 = (v0 + v1) & ((1 << 64) - 1)22v1 = rotl64(v1, 13)23v1 ^= v024v0 = rotl64(v0, 32)25v2 = (v2 + v3) & ((1 << 64) - 1)26v3 = rotl64(v3, 16)27v3 ^= v228v0 = (v0 + v3) & ((1 << 64) - 1)29v3 = rotl64(v3, 21)30v3 ^= v031v2 = (v2 + v1) & ((1 << 64) - 1)32v1 = rotl64(v1, 17)33v1 ^= v234v2 = rotl64(v2, 32)35return (v0, v1, v2, v3)38def siphash(k0, k1, data):39assert type(data) is bytes40v0 = 0x736f6d6570736575 ^ k041v1 = 0x646f72616e646f6d ^ k142v2 = 0x6c7967656e657261 ^ k043v3 = 0x7465646279746573 ^ k144c = 045t = 046for d in data:47t |= d << (8 * (c % 8))48c = (c + 1) & 0xff49if (c & 7) == 0:50v3 ^= t51v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3)52v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3)53v0 ^= t54t = 055t = t | (c << 56)56v3 ^= t57v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3)58v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3)59v0 ^= t60v2 ^= 0xff61v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3)62v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3)63v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3)64v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3)65return v0 ^ v1 ^ v2 ^ v368def siphash256(k0, k1, num):69assert type(num) is int70return siphash(k0, k1, num.to_bytes(32, 'little'))73class TestFrameworkSipHash(unittest.TestCase):74def test_vectors(self):75with (Path(__file__).parents[4] / "src/test/data/siphash.json").open() as vectors_file:76for test in json.load(vectors_file):77k0, k1 = (int(key, 16) for key in test["key"])78data = b"".join(bytes.fromhex(block) for block in test["input"])79self.assertEqual(siphash(k0, k1, data), int(test["expected"]["siphash24"], 16))
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.