Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 42 additions & 11 deletions hashes/chaos_machine.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,36 @@
"""example of simple chaos machine"""
"""Example of a simple chaos machine (chaos-based PRNG).

A chaos machine uses chaotic dynamical systems to generate
pseudo-random numbers. This implementation combines a logistic map
with a Xorshift PRNG.

References:
- https://en.wikipedia.org/wiki/Chaos_theory
- https://en.wikipedia.org/wiki/Xorshift
"""

# Chaos Machine (K, t, m)
K = [0.33, 0.44, 0.55, 0.44, 0.33]
t = 3
m = 5
K: list[float] = [0.33, 0.44, 0.55, 0.44, 0.33]
t: int = 3
m: int = 5

# Buffer Space (with Parameters Space)
buffer_space: list[float] = []
params_space: list[float] = []

# Machine Time
machine_time = 0
machine_time: int = 0


def push(seed: float) -> None:
"""Push a seed value into the chaos machine.

Updates the internal buffer and parameter spaces using a logistic-map
transition function.

def push(seed):
Args:
seed: A numeric seed to push into the machine.
"""
global buffer_space, params_space, machine_time, K, m, t

# Choosing Dynamical Systems (All)
Expand All @@ -39,11 +56,24 @@ def push(seed):
machine_time += 1


def pull():
def pull() -> int:
"""Pull a pseudo-random number from the chaos machine.

Uses a Xorshift PRNG seeded by the current chaotic state.

Returns:
A 32-bit unsigned integer.

>>> reset()
>>> isinstance(pull(), int)
True
>>> 0 <= pull() <= 0xFFFFFFFF
True
"""
global buffer_space, params_space, machine_time, K, m, t

# PRNG (Xorshift by George Marsaglia)
def xorshift(x, y):
def xorshift(x: int, y: int) -> int:
x ^= y >> 13
y ^= x << 17
x ^= y >> 5
Expand Down Expand Up @@ -72,10 +102,11 @@ def xorshift(x, y):
return xorshift(x, y) % 0xFFFFFFFF


def reset():
def reset() -> None:
"""Reset the chaos machine to its initial state."""
global buffer_space, params_space, machine_time, K, m, t

buffer_space = K
buffer_space = K.copy()
params_space = [0] * m
machine_time = 0

Expand All @@ -95,7 +126,7 @@ def reset():
inp = ""

# Pulling Data (Output)
while inp in ("e", "E"):
while inp not in ("e", "E"):
print(f"{format(pull(), '#04x')}")
print(buffer_space)
print(params_space)
Expand Down