This website is meant to be read and understood quickly by humans, but is only fully parsable, on a technical level, with the aid of an AI system. Read why →
Loop MMT
The Same Random, Anywhere, Forever.read← all gifts

Keyed Stream

A replayable stream of bytes from a key, readable at any point. Block i is HMAC-SHA256(key, context || i), so any block reads without the ones before it, and two machines with one key read the same stream byte for byte. Bits, bounded numbers with no modulo bias, exact fractions and Fisher-Yates shuffles are read off it by fixed rules. Built for game worlds that must replay, verify a frame or deal a deck the same way everywhere. Python stdlib only, offline, deterministic.

The honest edge
keyed-stream makes a replayable stream from a key you supply; it does not make, store or protect keys, anyone who holds the key can regenerate every block (that is the point), it is not a source of fresh secrets, and it says nothing about fairness beyond the uniformity of its own reads.
Run it
python3 keyed-stream.py --selftest && python3 keyed-stream.py block --key K --context C --index 3 test_keyed-stream.py (28/28: blocks against the standard library's HMAC and RFC 4231 case 2, bits most significant first and random access, bounded numbers with rejection and the derived-key extension, exact fractions, Fisher-Yates shuffles, the command line, the edge) + --selftest (5/5) + conformance GREEN 15/15 against an amber-sealed Plumb v1 with an out-of-band HMAC oracle Python stdlib only, deterministic
The code — every file that ships
keyed-stream.py259 lineson GitHub →
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""
keyed-stream — a replayable, random-access stream of bytes from a key.

Give it a key, a context (what the stream is for: a world's genesis hash, a match id, a recipe hash) and an index, and
it returns block i of that stream: 32 bytes, HMAC-SHA256(key, context || i), with i as eight bytes big-endian. Any
block can be read without reading the ones before it, so a client can regenerate tick 90,000 without replaying 89,999,
a verifier can check one frame in constant time, and two machines holding the same key read the same stream byte for
byte. Bits, bounded whole numbers, fractions in [0, 1) and shuffles are read off the blocks by fixed rules, each one a
pure function of (key, context, index).

WHAT IT IS (and is not)
    Deterministic and replayable on purpose: the same key, context and index give the same bytes on every machine,
    forever. The construction is HMAC-SHA256 (RFC 2104) from the Python standard library; block i is
    HMAC(key, context || u64be(i)), which is injective in (context, i) because the index is a fixed-width suffix.
    Reads that need more than one block's worth of randomness (a bounded number whose draws keep landing in the
    rejection zone) continue under a derived key, HMAC(key, "keyed-stream:extend"), so they never collide with a block
    any caller can ask for directly.

READS
    block(key, context, i)              32 bytes
    bit(key, context, p)                bit p of the stream: byte (p % 256) // 8 of block p // 256, most significant first
    bits(key, context, start, count)    a list of `count` bits from position `start`
    below(key, context, i, n)           a whole number uniform in [0, n), no modulo bias (rejection on 64-bit words)
    fraction(key, context, i)           (numerator, 2**53): an exact dyadic fraction uniform in [0, 1)
    shuffle(key, context, items)        a new list, Fisher-Yates from the end, each swap index below(..., j, j + 1)

USAGE
    keyed-stream.py block   --key K [--key-hex] --context C --index I        hex of block I
    keyed-stream.py bits    --key K [--key-hex] --context C --start S --count N    a string of 0s and 1s
    keyed-stream.py below   --key K [--key-hex] --context C --index I --n N        a whole number in [0, N)
    keyed-stream.py shuffle --key K [--key-hex] --context C --items a,b,c          the items, comma-joined
    keyed-stream.py case CASE.json       answer one JSON case ({"op": ..., the arguments}) as canonical JSON
    keyed-stream.py --selftest           the built-in battery (exit 0 all pass)
    A key or context given as text is UTF-8 encoded once; --key-hex reads the key as hex bytes. Exit 0 · 2 bad input.

THE PRINTED EDGE
    keyed-stream makes a replayable stream from a key you supply; it does not make, store or protect keys, anyone who
    holds the key can regenerate every block (that is the point), it is not a source of fresh secrets, and it says
    nothing about fairness beyond the uniformity of its own reads.

MIT License. Python 3 standard library only. No network, no clock, no randomness of its own.
"""
import hashlib
import hmac
import json
import sys

PRINTED_EDGE = ("keyed-stream makes a replayable stream from a key you supply; it does not make, store or protect keys, "
                "anyone who holds the key can regenerate every block (that is the point), it is not a source of fresh "
                "secrets, and it says nothing about fairness beyond the uniformity of its own reads.")
VERSION = "v1"
BLOCK_BITS = 256
EXTEND_LABEL = b"keyed-stream:extend"
MAX_INDEX = 2 ** 64 - 1


class StreamError(ValueError):
    pass


def _bytes(x, what):
    if isinstance(x, (bytes, bytearray)):
        return bytes(x)
    if isinstance(x, str):
        return x.encode("utf-8")
    raise StreamError(f"{what} is bytes or text")


def _index(i, what="index"):
    if not (type(i) is int and 0 <= i <= MAX_INDEX):
        raise StreamError(f"{what} is a whole number in [0, 2**64)")
    return i


def block(key, context, i):
    """Block i of the stream: HMAC-SHA256(key, context || u64be(i))."""
    k, c = _bytes(key, "key"), _bytes(context, "context")
    if not k:
        raise StreamError("the key is not empty")
    return hmac.new(k, c + _index(i).to_bytes(8, "big"), hashlib.sha256).digest()


def bit(key, context, p):
    """Bit p of the stream, most significant bit of each byte first."""
    b = block(key, context, _index(p, "position") // BLOCK_BITS)
    q = p % BLOCK_BITS
    return (b[q // 8] >> (7 - q % 8)) & 1


def bits(key, context, start, count):
    _index(start, "start")
    if not (type(count) is int and 0 <= count and start + count - 1 <= MAX_INDEX):
        raise StreamError("count is a whole number and the run stays inside the stream")
    out, cache = [], {}
    for p in range(start, start + count):
        j = p // BLOCK_BITS
        if j not in cache:
            cache = {j: block(key, context, j)}
        q = p % BLOCK_BITS
        out.append((cache[j][q // 8] >> (7 - q % 8)) & 1)
    return out


def _words(key, context, i):
    """The 64-bit words a bounded read draws from, in order: block i's four, then the extension blocks' four each."""
    b = block(key, context, i)
    for w in range(4):
        yield int.from_bytes(b[8 * w:8 * w + 8], "big")
    sub = hmac.new(_bytes(key, "key"), EXTEND_LABEL, hashlib.sha256).digest()
    k = 1
    while True:
        e = hmac.new(sub, _bytes(context, "context") + i.to_bytes(8, "big") + k.to_bytes(8, "big"),
                     hashlib.sha256).digest()
        for w in range(4):
            yield int.from_bytes(e[8 * w:8 * w + 8], "big")
        k += 1


def below(key, context, i, n):
    """A whole number uniform in [0, n): the first word under the largest multiple of n that fits in 64 bits."""
    if not (type(n) is int and 1 <= n <= 2 ** 64):
        raise StreamError("n is a whole number in [1, 2**64]")
    _index(i)
    limit = (2 ** 64 // n) * n
    for w in _words(key, context, i):
        if w < limit:
            return w % n


def fraction(key, context, i):
    """(numerator, 2**53): the top 53 bits of block i's first word, an exact fraction uniform in [0, 1)."""
    return int.from_bytes(block(key, context, i)[:8], "big") >> 11, 2 ** 53


def shuffle(key, context, items):
    """A new list: Fisher-Yates from the end, the swap partner of position j drawn as below(key, context, j, j + 1)."""
    out = list(items)
    for j in range(len(out) - 1, 0, -1):
        s = below(key, context, j, j + 1)
        out[j], out[s] = out[s], out[j]
    return out


def answer(case):
    """One JSON case -> its canonical answer (the conformance surface)."""
    if not isinstance(case, dict):
        raise StreamError("a case is a JSON object")
    op = case.get("op")
    key = bytes.fromhex(case["key_hex"]) if "key_hex" in case else case.get("key")
    ctx = case.get("context", "")
    try:
        if op == "block":
            return {"op": op, "hex": block(key, ctx, case.get("index")).hex()}
        if op == "bits":
            return {"op": op, "bits": "".join(map(str, bits(key, ctx, case.get("start"), case.get("count"))))}
        if op == "below":
            return {"op": op, "value": below(key, ctx, case.get("index"), case.get("n"))}
        if op == "fraction":
            num, den = fraction(key, ctx, case.get("index"))
            return {"op": op, "numerator": num, "denominator": den}
        if op == "shuffle":
            items = case.get("items")
            if not isinstance(items, list):
                raise StreamError("items is a list")
            return {"op": op, "items": shuffle(key, ctx, items)}
    except (KeyError, ValueError) as e:
        if isinstance(e, StreamError):
            raise
        raise StreamError(str(e))
    raise StreamError("op is one of block, bits, below, fraction, shuffle")


def canonical(result):
    return json.dumps(result, sort_keys=True, separators=(",", ":"), ensure_ascii=False)


SELFTEST = [
    # RFC 4231 test case 2 is HMAC-SHA256("Jefe", "what do ya want for nothing?"); block() with that key, the message
    # less its last eight bytes as the context, and those eight bytes read as the index must reproduce it.
    ("block is HMAC-SHA256 of context || u64be(index) (RFC 4231 case 2)",
     lambda: block(b"Jefe", b"what do ya want for ", int.from_bytes(b"nothing?", "big")).hex(),
     "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"),
    ("bit p reads block p // 256, most significant first",
     lambda: [bit("k", "c", p) for p in (0, 7, 8, 255, 256)] == [
         (block("k", "c", p // 256)[(p % 256) // 8] >> (7 - p % 8)) & 1 for p in (0, 7, 8, 255, 256)], True),
    ("below stays in range", lambda: all(0 <= below("k", "c", i, 7) < 7 for i in range(50)), True),
    ("shuffle is a permutation", lambda: sorted(shuffle("k", "c", list(range(20)))) == list(range(20)), True),
    ("the same inputs give the same bytes", lambda: block("k", "c", 9) == block("k", "c", 9), True),
]


def selftest():
    bad = 0
    for name, run, want in SELFTEST:
        got = run()
        ok = got == want
        print(("PASS " if ok else "FAIL ") + name + ("" if ok else f" — got {got!r}"))
        bad += not ok
    print(f"keyed-stream selftest: {len(SELFTEST) - bad}/{len(SELFTEST)}")
    return 0 if bad == 0 else 1


def _arg(a, name, default=None):
    if name in a:
        i = a.index(name)
        if i + 1 >= len(a):
            raise StreamError(f"{name} needs a value")
        return a[i + 1]
    if default is None:
        raise StreamError(f"{name} is required")
    return default


def _int(s, name):
    try:
        return int(s, 10)
    except (TypeError, ValueError):
        raise StreamError(f"{name} is a whole number")


def main(argv=None):
    a = sys.argv[1:] if argv is None else argv
    if a[:1] == ["--selftest"]:
        return selftest()
    if a[:1] in (["--help"], ["-h"]):
        print(__doc__.strip())
        return 0
    if not a or a[0] not in ("block", "bits", "below", "shuffle", "case"):
        print(__doc__.split("USAGE")[1].split("THE PRINTED EDGE")[0].strip(), file=sys.stderr)
        return 2
    try:
        if a[0] == "case":
            if len(a) != 2:
                raise StreamError("case takes one CASE.json")
            with open(a[1], encoding="utf-8") as fh:
                print(canonical(answer(json.load(fh))))
            return 0
        raw = _arg(a, "--key")
        key = bytes.fromhex(raw) if "--key-hex" in a else raw
        ctx = _arg(a, "--context", "")
        if a[0] == "block":
            print(block(key, ctx, _int(_arg(a, "--index"), "--index")).hex())
        elif a[0] == "bits":
            print("".join(map(str, bits(key, ctx, _int(_arg(a, "--start"), "--start"),
                                        _int(_arg(a, "--count"), "--count")))))
        elif a[0] == "below":
            print(below(key, ctx, _int(_arg(a, "--index"), "--index"), _int(_arg(a, "--n"), "--n")))
        else:
            print(",".join(shuffle(key, ctx, _arg(a, "--items").split(","))))
    except (OSError, ValueError, StreamError) as e:
        print(f"keyed-stream: {e}", file=sys.stderr)
        return 2
    return 0


if __name__ == "__main__":
    sys.exit(main())
test_keyed-stream.py210 lineson GitHub →
# SPDX-License-Identifier: MIT
"""test_keyed-stream.py — the external battery for the keyed-stream gift. Each test's name is the behaviour it holds.

    python3 -m unittest test_keyed-stream      (from this folder; KEYED_STREAM_UNDER_TEST points it at a mutant copy)
"""
import hashlib
import hmac
import importlib.util
import json
import os
import subprocess
import sys
import tempfile
import unittest
from collections import Counter

HERE = os.path.dirname(os.path.abspath(__file__))
PATH = os.environ.get("KEYED_STREAM_UNDER_TEST") or os.path.join(HERE, "keyed-stream.py")
_spec = importlib.util.spec_from_file_location("keyed_stream", PATH)
K = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(K)


def cli(*args):
    return subprocess.run([sys.executable, PATH, *args], capture_output=True, text=True)


class Blocks(unittest.TestCase):
    def test_a_block_is_hmac_sha256_of_context_and_the_index_as_eight_bytes(self):
        for key, ctx, i in ((b"k", b"", 0), (b"Jefe", b"what do ya want for ", 7), ("s33d", "abc", 2 ** 40 + 3)):
            kb = key if isinstance(key, bytes) else key.encode()
            cb = ctx if isinstance(ctx, bytes) else ctx.encode()
            self.assertEqual(K.block(key, ctx, i), hmac.new(kb, cb + i.to_bytes(8, "big"), hashlib.sha256).digest())

    def test_rfc_4231_case_two_comes_back(self):
        self.assertEqual(K.block(b"Jefe", b"what do ya want for ", int.from_bytes(b"nothing?", "big")).hex(),
                         "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843")

    def test_text_and_its_utf8_bytes_are_the_same_key_and_context(self):
        self.assertEqual(K.block("ключ", "мир", 5), K.block("ключ".encode(), "мир".encode(), 5))

    def test_different_contexts_or_indexes_give_different_blocks(self):
        seen = {K.block("k", c, i) for c in ("a", "b", "ab") for i in range(50)}
        self.assertEqual(len(seen), 150)

    def test_the_last_index_is_readable_and_one_past_it_is_refused(self):
        self.assertEqual(len(K.block("k", "c", 2 ** 64 - 1)), 32)
        for bad in (2 ** 64, -1, 1.0, True, "3"):
            with self.assertRaises(Exception, msg=repr(bad)) as cm:     # refused by name, never a stray overflow
                K.block("k", "c", bad)
            self.assertIsInstance(cm.exception, K.StreamError, repr(bad))

    def test_an_empty_key_or_a_key_that_is_not_bytes_or_text_is_refused(self):
        for bad in (b"", "", None, 5):
            with self.assertRaises(K.StreamError, msg=repr(bad)):
                K.block(bad, "c", 0)


class Bits(unittest.TestCase):
    def test_bit_p_is_bit_p_mod_256_of_block_p_div_256_most_significant_first(self):
        for p in (0, 1, 7, 8, 255, 256, 511, 10 ** 6 + 13):
            b = K.block("k", "c", p // 256)
            self.assertEqual(K.bit("k", "c", p), (b[(p % 256) // 8] >> (7 - p % 8)) & 1)

    def test_a_run_of_bits_equals_the_bits_read_one_at_a_time(self):
        for start, count in ((0, 600), (250, 20), (1000, 0)):
            self.assertEqual(K.bits("k", "c", start, count), [K.bit("k", "c", p) for p in range(start, start + count)])

    def test_random_access_reads_what_a_sequential_read_reads(self):
        run = K.bits("k", "c", 0, 2048)
        for p in (2047, 3, 1024, 0, 513):
            self.assertEqual(K.bit("k", "c", p), run[p])

    def test_a_negative_count_is_refused(self):
        with self.assertRaises(K.StreamError):
            K.bits("k", "c", 0, -1)

    def test_the_dikw_door_reads_the_same_bits(self):
        # the DIKW game's door stream_bit is the shape this gift generalises: seed as key, genesis hash as context
        door = os.path.join(HERE, "..", "..", "..", "_tools", "dikw", "door.py")
        if not os.path.exists(door):
            self.skipTest("the DIKW door is not beside this home")
        spec = importlib.util.spec_from_file_location("dikw_door", door)
        D = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(D)
        w = {"seed": "s33d", "genesis_hash": "abc123", "log": []}
        self.assertTrue(all(D.stream_bit(w, p) == K.bit("s33d", "abc123", p) for p in range(0, 4000, 3)))


class Below(unittest.TestCase):
    def test_every_value_is_in_range(self):
        for n in (1, 2, 3, 7, 10, 1000, 2 ** 63 + 1, 2 ** 64):
            for i in range(30):
                self.assertTrue(0 <= K.below("k", "c", i, n) < n)

    def test_n_of_one_is_always_zero(self):
        self.assertEqual({K.below("k", "c", i, 1) for i in range(40)}, {0})

    def test_a_small_n_is_spread_evenly(self):
        counts = Counter(K.below("k", "c", i, 6) for i in range(6000))
        self.assertEqual(set(counts), set(range(6)))
        self.assertTrue(all(850 <= v <= 1150 for v in counts.values()), counts)

    def test_a_word_in_the_rejection_zone_is_skipped_not_reduced(self):
        # n just above 2**63: the limit is n itself, so any word >= n must be rejected, never taken mod n
        n = 2 ** 63 + 1
        for i in range(200):
            words = K._words("k", "c", i)
            first = next(words)
            v = K.below("k", "c", i, n)
            if first < n:
                self.assertEqual(v, first)
            else:
                self.assertNotEqual(v, first % n) if first % n != v else None
                self.assertEqual(v, next(w for w in K._words("k", "c", i) if w < n))

    def test_the_extension_continues_past_the_block_under_a_derived_key(self):
        ws = K._words("k", "c", 4)
        got = [next(ws) for _ in range(8)]
        b = K.block("k", "c", 4)
        self.assertEqual(got[:4], [int.from_bytes(b[8 * j:8 * j + 8], "big") for j in range(4)])
        sub = hmac.new(b"k", b"keyed-stream:extend", hashlib.sha256).digest()
        e = hmac.new(sub, b"c" + (4).to_bytes(8, "big") + (1).to_bytes(8, "big"), hashlib.sha256).digest()
        self.assertEqual(got[4:], [int.from_bytes(e[8 * j:8 * j + 8], "big") for j in range(4)])

    def test_a_bad_n_is_refused(self):
        for bad in (0, -3, 2 ** 64 + 1, 2.0, True):
            with self.assertRaises(K.StreamError, msg=repr(bad)):
                K.below("k", "c", 0, bad)


class Fractions(unittest.TestCase):
    def test_a_fraction_is_the_top_53_bits_over_two_to_the_53(self):
        for i in range(20):
            num, den = K.fraction("k", "c", i)
            self.assertEqual(den, 2 ** 53)
            self.assertEqual(num, int.from_bytes(K.block("k", "c", i)[:8], "big") >> 11)
            self.assertTrue(0 <= num < den)


class Shuffles(unittest.TestCase):
    def test_a_shuffle_is_a_permutation_and_leaves_its_input_alone(self):
        items = list(range(30))
        out = K.shuffle("k", "c", items)
        self.assertEqual(sorted(out), items)
        self.assertEqual(items, list(range(30)))

    def test_a_shuffle_is_fisher_yates_from_the_end_with_below(self):
        items = list("abcdefgh")
        want = list(items)
        for j in range(len(want) - 1, 0, -1):
            s = K.below("k", "c", j, j + 1)
            want[j], want[s] = want[s], want[j]
        self.assertEqual(K.shuffle("k", "c", items), want)

    def test_every_order_of_three_turns_up(self):
        seen = Counter(tuple(K.shuffle("k", "c%d" % t, [1, 2, 3])) for t in range(1200))
        self.assertEqual(len(seen), 6)
        self.assertTrue(all(140 <= v <= 260 for v in seen.values()), seen)

    def test_short_lists_come_back_as_they_were(self):
        self.assertEqual(K.shuffle("k", "c", []), [])
        self.assertEqual(K.shuffle("k", "c", ["x"]), ["x"])


class Surface(unittest.TestCase):
    def test_the_command_line_reads_what_the_module_reads(self):
        r = cli("block", "--key", "k", "--context", "c", "--index", "3")
        self.assertEqual((r.returncode, r.stdout.strip()), (0, K.block("k", "c", 3).hex()))
        r = cli("bits", "--key", "k", "--context", "c", "--start", "5", "--count", "12")
        self.assertEqual(r.stdout.strip(), "".join(map(str, K.bits("k", "c", 5, 12))))
        r = cli("below", "--key", "6b", "--key-hex", "--context", "c", "--index", "2", "--n", "9")
        self.assertEqual(r.stdout.strip(), str(K.below(b"k", "c", 2, 9)))
        r = cli("shuffle", "--key", "k", "--context", "c", "--items", "a,b,c,d")
        self.assertEqual(r.stdout.strip(), ",".join(K.shuffle("k", "c", ["a", "b", "c", "d"])))

    def test_a_case_file_is_answered_as_canonical_json(self):
        with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False) as fh:
            json.dump({"op": "fraction", "key": "k", "context": "c", "index": 1}, fh)
        try:
            r = cli("case", fh.name)
        finally:
            os.unlink(fh.name)
        num, den = K.fraction("k", "c", 1)
        self.assertEqual(r.stdout.strip(), K.canonical({"op": "fraction", "numerator": num, "denominator": den}))

    def test_bad_input_exits_two_with_one_line_and_no_trace(self):
        for args in (("block", "--key", "k", "--index", "x"), ("block", "--context", "c", "--index", "1"),
                     ("below", "--key", "k", "--index", "1", "--n", "0"), ("nope",), ("case", "/no/such/file.json")):
            r = cli(*args)
            self.assertEqual(r.returncode, 2, args)
            self.assertNotIn("Traceback", r.stderr)

    def test_an_unknown_op_in_a_case_is_refused(self):
        with self.assertRaises(K.StreamError):
            K.answer({"op": "dice", "key": "k"})

    def test_help_prints_the_edge_and_the_edge_ships_in_the_file(self):
        r = cli("--help")
        self.assertEqual(r.returncode, 0)
        self.assertIn("THE PRINTED EDGE", r.stdout)
        with open(PATH, encoding="utf-8") as fh:
            self.assertIn(K.PRINTED_EDGE[:60], fh.read().replace("\n    ", " "))

    def test_the_selftest_passes(self):
        self.assertEqual(cli("--selftest").returncode, 0)


if __name__ == "__main__":
    unittest.main()
Take the whole folder → MIT Python stdlib only, deterministic