#!/usr/bin/env python3 """Reference implementation of BTCP's public network-magic draw, version V1. Standard library only. Usage: python3 draw.py is the Bitcoin block hash as 64 hexadecimal digits in display order (the order that block explorers and `bitcoin-cli getblockhash` print). is the published list of known network magics: tab-separated, one header line, with a column named "magic" holding 8 hexadecimal digits in wire order. The rule, as published: For each network in the order mainnet, testnet, regtest, devnet, and for k = 0, 1, 2, ...: 1. Form the ASCII message BTCP-PHOENIX-MAGIC-V1||| (network name in lower case, the hash as 64 lower-case hex digits, k in decimal with no leading zeros, fields joined by "|" with no spaces, no trailing newline). 2. The candidate is the first four bytes of the message's SHA-256, in that order. 3. It passes only if: F1 every byte is 0x80 or more; F2 the four bytes are not valid UTF-8 (strict); F3 the value read as a 32-bit integer is 0xD0000000 or more in both byte orders. 4. A passing candidate is rejected if it equals, or differs in exactly one byte position from, any magic on the list, any of a8eaa2cd, a8eaa2ce, a8eaa2cf, or a value already drawn for an earlier network. 5. The network takes the first candidate (lowest k) that passes and is not rejected. The script prints every rejected candidate with its reason, then the four values with their k, and the SHA-256 of the list file it read. """ import hashlib import re import sys LABEL = "BTCP-PHOENIX-MAGIC-V1" NETWORKS = ["mainnet", "testnet", "regtest", "devnet"] # the draw order RESERVED = [bytes.fromhex(x) for x in ("a8eaa2cd", "a8eaa2ce", "a8eaa2cf")] MIN_LARGE = 0xD0000000 # F3, in both byte orders def candidate(network, anchor_hash, k): message = f"{LABEL}|{network}|{anchor_hash}|{k}".encode("ascii") return hashlib.sha256(message).digest()[:4] def filter_failure(m): """Return the first filter the candidate fails (F1, F2 or F3), or None if it passes all three.""" if any(b < 0x80 for b in m): return "F1 (a byte below 0x80)" try: m.decode("utf-8") return "F2 (valid UTF-8)" except UnicodeDecodeError: pass if int.from_bytes(m, "big") < MIN_LARGE or int.from_bytes(m, "little") < MIN_LARGE: return "F3 (below 0xD0000000 in a byte order)" return None def within_one_byte(a, b): return sum(x != y for x, y in zip(a, b)) <= 1 def load_list(path): with open(path, "rb") as f: raw = f.read() rows = raw.decode("utf-8").splitlines() header = rows[0].split("\t") col = header.index("magic") magics = [bytes.fromhex(r.split("\t")[col]) for r in rows[1:] if r.strip()] return magics, hashlib.sha256(raw).hexdigest() def draw(anchor_hash, listed, out=print): rejected = [(m, "on the list") for m in listed] + [(m, "a reserved value") for m in RESERVED] result = {} for network in NETWORKS: k = 0 while True: m = candidate(network, anchor_hash, k) failure = filter_failure(m) if failure is None: hit = next(((r, why) for r, why in rejected if within_one_byte(m, r)), None) if hit is None: break r, why = hit kind = "equal to" if r == m else "one byte from" out(f"{network} k={k} {m.hex()} rejected: {kind} {r.hex()} ({why})") k += 1 result[network] = (m, k) rejected.append((m, f"the {network} value already drawn")) return result def main(): if len(sys.argv) != 3: sys.exit(__doc__) anchor = sys.argv[1].strip() if not re.fullmatch(r"[0-9a-f]{64}", anchor): sys.exit("the anchor hash must be 64 lower-case hexadecimal digits in display order") listed, list_sha256 = load_list(sys.argv[2]) result = draw(anchor, listed) print(f"list sha256 {list_sha256} ({len(listed)} magics)") for network in NETWORKS: m, k = result[network] print(f"{network} {m.hex()} k={k}") if __name__ == "__main__": main()