#!/usr/bin/env python3 """Build a DCSO-format bloom filter from files of hex digest lines. Standalone, zero dependencies — everything needed to reproduce the .bloom files in this dataset from the digest lists / harvest scripts alongside it. Format (github.com/DCSO/bloom, the format CIRCL hashlookup uses): 48-byte header of little-endian u64s (version=1, n capacity, p as f64 bits, k, m, N inserted) followed by ceil(m/64) u64 words of bit array. Keys are hex digest STRINGS: UPPERCASE for sha1 (the hashlookup convention), lowercase for everything else. Membership hashing (Go semantics preserved from the reference implementation): h = FNV-1 64(key) mod M with M = 2^64 - 87, then k rounds of h = (h * g mod 2^64) mod M with g = 18446744073709550147, setting bit h mod m each round. Usage: dcso_bloom_build.py OUT.bloom SCHEME HEXFILE... [--fpp 0.0001] (SCHEME in md5|sha1|sha256 — sets required line length + key case) """ import math import struct import sys MOD = 2**64 - 87 G = 18446744073709550147 MASK = 2**64 - 1 HEX_LEN = {"md5": 32, "sha1": 40, "sha256": 64} def fnv1_64(data: bytes) -> int: h = 0xCBF29CE484222325 for b in data: h = (h * 0x100000001B3) & MASK h ^= b return h def main() -> None: args = [a for a in sys.argv[1:] if not a.startswith("--")] fpp = 0.0001 for a in sys.argv[1:]: if a.startswith("--fpp"): fpp = float(a.split("=", 1)[1] if "=" in a else sys.argv[sys.argv.index(a) + 1]) if len(args) < 3 or args[1] not in HEX_LEN: sys.exit(__doc__) out, scheme, inputs = args[0], args[1], args[2:] hex_len = HEX_LEN[scheme] upper = scheme == "sha1" n = 0 for path in inputs: with open(path) as f: for line in f: t = line.strip() if not t: continue if len(t) != hex_len or not all(c in "0123456789abcdefABCDEF" for c in t): sys.exit(f"{path}: line {t!r} is not a {hex_len}-char hex digest") n += 1 if n == 0: sys.exit("no digests found in input") ln2 = math.log(2) m = math.ceil(n * -math.log(fpp) / (ln2 * ln2)) k = max(1, round((m / n) * ln2)) words = bytearray((m + 63) // 64 * 8) print(f"building {out}: {n} keys, p={fpp}, {len(words) >> 20} MiB", file=sys.stderr) done = 0 for path in inputs: with open(path) as f: for line in f: t = line.strip() if not t: continue key = (t.upper() if upper else t.lower()).encode() h = fnv1_64(key) % MOD for _ in range(k): h = (h * G & MASK) % MOD bit = h % m words[bit >> 6 << 3 | (bit >> 3) & 7] |= 1 << (bit & 7) done += 1 if done % 50_000_000 == 0: print(f" … {done}/{n}", file=sys.stderr) with open(out, "wb") as f: f.write(struct.pack("<6Q", 1, n, struct.unpack("